Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to detect a change to the user agent information, using JavaScript?

I’d like to display different content based on window.navigator.userAgent, but it doesn’t seem to be updated when you change it via a browser’s devtools.

I want to automatically refresh the page when the user agent is changed using the devtools, to prevent use of a page meant for the actual device/browser instead of the one specified with the devtools.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The userAgent can only change if the person viewing the site opens up their DevTools and manually changes it. Since this is not really a normal use case, there is no event to watch for when the userAgent changes. The only way to do this—that I’m aware of—is to manually poll for changes (e.g., with setInterval):

function uaChanged(prevUa, newUa) {
  console.log('UserAgent changed!');
  console.log('Previous UA:', prevUa);
  console.log('New UA:', newUa);
}

let ua = navigator.userAgent;
setInterval(function() {
  if (navigator.userAgent !== ua) {
    uaChanged(ua, navigator.userAgent);
    ua = navigator.userAgent;
  }
}, 1000);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading