How to detect that your website is displayed in the simulator

Run JavaScript code only in the Mobile FIRST simulator with the window.isMobileFirstSimulatorActive variable.

Why detect the simulator

You may want to run some code only when your website is displayed in the simulator: disable a feature that makes no sense on a computer, hide a banner, add debug logs, etc. When the simulator is active, the extension defines a global variable window.isMobileFirstSimulatorActive set to true in your website's page.

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 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: the Promise never resolves and your code never runs. This is the expected behavior, you don't need to handle the opposite case.

Need help?

If you still have a question, contact us.