🕵🏼 How to detect that my website is displayed in the Mobile FIRST simulator ?

Context

You may want to run specific code only when your website is displayed in the simulator: disable a feature that doesn't make sense on a desktop, hide a banner, add debug logs, etc.
When the simulator is active, the extension defines a global variable window.isMobileFirstSimulatorActive set to true in the page of your website.

This variable may be defined after your own scripts have started. A simple if (window.isMobileFirstSimulatorActive) at page load can therefore return a false negative. That's why we recommend waiting for the variable as shown below.

Detect the simulator

Step 1

Add this helper function to your website. It returns a Promise that resolves as soon as the variable exists, whether it is already defined or defined later.

function whenVariableExists(name, target = window) {
  return new Promise((resolve) => {
    // If the variable is already defined
    if (name in target) {
      return resolve(target[name]);
    }

    // Otherwise, intercept its future assignment
    let value;
    Object.defineProperty(target, name, {
      configurable: true,
      enumerable: true,
      get() {
        return value;
      },
      set(newValue) {
        value = newValue;
        resolve(newValue);
      }
    });
  });
}

Step 2

Use it to wait for isMobileFirstSimulatorActive and run your code.

// Usage:
whenVariableExists('isMobileFirstSimulatorActive').then((value) => {
  // Code to execute
});
Outside the simulator, the variable is never defined, so the Promise never resolves and your code is never executed. This is the expected behavior: you don't need to handle the opposite case.

Contact

If you still have a question you can contact us