3

For my project, I want to get and print the user-agent of my browser. I'm using javascript (with node) to accomplish my goal. How can I get and print the user-agent header without using the HTTP module and html if possible and inside of this blank function:

function userAgent() {
  
}
Sergio Ley
  • 85
  • 1
  • 14

2 Answers2

5

Just use window.navigator.userAgent

function userAgent() {
  return window.navigator.userAgent;
}

console.log(userAgent());
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • I get this error: ` return window.navigator.userAgent;` `^` `ReferenceError: window is not defined` I should clarify that I also don't want to use html for this – Sergio Ley Jul 29 '20 at 07:04
  • How do you run this code? Are you using Node maybe? – Sebastian Kaczmarek Jul 29 '20 at 07:13
  • I am using node – Sergio Ley Jul 29 '20 at 07:14
  • 2
    Well, then you should definitely clarify that in the question because that changes like everything. You cannot get a user agent in the Node app itself because UA is something tightly connected with a **client app**. You could do that if you had for example some frontend app that makes a request to your Node server - then you can get the UA header **from the request**. – Sebastian Kaczmarek Jul 29 '20 at 07:17
  • You have reference this article https://stackoverflow.com/questions/6163350/server-side-browser-detection-node-js – Minwoo Kim Jul 29 '20 at 07:24
1

You can try this.

<script>
   window.onload = function () {
        var agent = navigator.userAgent.toLowerCase();
        if (agent.indexOf('chrome') != -1) { 
           alert('Chrome');
        }
        if (agent.indexOf('msie') != -1) {
           alert('Explorer');
        }
        if (agent.indexOf('safari') != -1) {
           alert('Safari');
        }
        if (agent.indexOf('firefox') != -1) {
           alert('Firefox');
        }
   }
</script>
Minwoo Kim
  • 497
  • 1
  • 5
  • 21