skip to Main Content

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.

2

Answers


  1. Use setInterval() to check periodically to see if it has changed.

    let lastUA = null;
    
    setInterval(() => {
      if (navigator.userAgent != lastUA) {
        updateDisplayBasedOnUA();
        lastUA = navigator.userAgent;
      }
    }, 500);
    
    let counter = 0;
    function updateDisplayBasedOnUA() {
      document.querySelector("#displayCount").innerText = counter++;
      console.log(counter);
    }
    UA changed <span id="displayCount"></span> times
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search