How to detect private browsing in iOS 11 Mobile Safari or MacOS High Sierra Safari?

Viewed 2375

On the new iOS 11 Safari and MacOS High Sierra Safari, that trick of seeing if window.localStorage.setItem('test', 1); (see https://stackoverflow.com/a/17741714/1330341) throws an error no longer works, because it no longer throws an error, and it also properly sets the localStorage item. Has anyone figured out any other way to check for private browsing mode in the new versions of Safari?

4 Answers

Thing that I realized is Safari throws a "Quota Exceeded" error in the Private mode. So here is what I did!

isPrivateMode: function () {
  if (localStorage.length === 0) {
    try {
      localStorage.setItem('isLocalStorageAvaialble', 'That is being tested!');
      localStorage.removeItem('isLocalStorageAvaialble');
      return false;
    } catch (e) {
      return true;
    }
  }
}

Checking the length of localStorage is important for the fact that, if you are trying this method on a browser that supports localStorage, but is full, you still will get the "Quota Exceeded" error. In private mode, the length of localStorage is always 0.

Hope this helps!

Related