Detecting incognito mode reliably in web browsers

73 views Asked by At

I'm working on a web application and need to determine whether the user is in incognito mode.I am using react and creating custom hook for that manner, I've tried using methods like checking localStorage, sessionStorage, and the FileSystem API, but I'm facing issues with reliability.

Here's the code I've tried:

  const isIncognitoMode = () => {
    try {
      // Attempt to use localStorage
      localStorage.setItem('test', 'test');
      localStorage.removeItem('test');

      // Attempt to use sessionStorage
      sessionStorage.setItem('test', 'test');
      sessionStorage.removeItem('test');

      return false;
    } catch (e) {
      // If an exception is thrown, it's likely incognito mode
      return true;
    }
  };

Unfortunately, this approach doesn't work in all scenarios, and I'm looking for a more reliable global way to detect incognito mode. Has anyone encountered a similar problem or found a better solution?

1

There are 1 answers

0
Joe Rutkowski On

I've been maintaining a script on GitHub to do this for all browsers for several years now, it's more complicated than a few lines of code. It's also available on npm.

https://github.com/Joe12387/detectIncognito