Detect private browsing mode in mobile Safari on iOS5

I don’t know why the iOS developers decided to handle it in this way, but when you attempt to set an item to either localStorage or sessionStorage on iOS5 with Safari in ‘private browsing’ mode, a quota exceeded error will be thrown.

You’re allowed to set at least 5MB of data to DOM storage without asking the user for permission, so if the key length is zero then you can be certain that the user is in ‘private browsing’ mode when you catch the error….

var testKey = 'qeTest', storage = window.sessionStorage; try { // Try and catch quota exceeded errors storage.setItem(testKey, '1'); storage.removeItem(testKey); } catch (error) { if (error.code === DOMException.QUOTA_EXCEEDED_ERR && storage.length === 0) alert('Hello, private browser.'); else throw error; }

It’s interesting that Apple developer Brady Eidson actually suggested this behaviour in a discussion on persistence and private browsing, on the WHATWG mailing list, but later on in the discussion said that it would be “unsatisfactory”. There’s a full summary of the discussion on the WHATWG blog.

  1. matthewcaruanagalizia posted this