-
-
Save subversivo58/735ec7dbf8c2fdaf7a699ad370f847cd to your computer and use it in GitHub Desktop.
Detect if a browser is in Private Browsing mode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Detect if the browser is running in Private Browsing mode | |
*/ | |
function isPrivateMode() { | |
return new Promise((resolve) => { | |
const on = () => resolve(true); // is in private mode | |
const off = () => resolve(false); // not private mode | |
const testLocalStorage = () => { | |
try { | |
if (localStorage.length) off(); | |
else { | |
localStorage.x = 1; | |
localStorage.removeItem('x'); | |
off(); | |
} | |
} catch (e) { | |
// Safari only enables cookie in private mode | |
// if cookie is disabled then all client side storage is disabled | |
// if all client side storage is disabled, then there is no point | |
// in using private mode | |
navigator.cookieEnabled ? on() : off(); | |
} | |
}; | |
// Chrome & Opera | |
if (window.webkitRequestFileSystem) { | |
return void window.webkitRequestFileSystem(0, 0, on, off); | |
} | |
// Firefox | |
if ('MozAppearance' in document.documentElement.style) { | |
const db = indexedDB.open('test'); | |
db.onerror = on; | |
db.onsuccess = off; | |
return void 0; | |
} | |
// Safari | |
if (/constructor/i.test(window.HTMLElement)) { | |
return testLocalStorage(); | |
} | |
// IE10+ & Edge | |
if (!window.indexedDB && (window.PointerEvent || window.MSPointerEvent)) { | |
return on(); | |
} | |
// others | |
return off(); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for IE: Promises aren't natively supported in IE10 or 11 | |
isPrivateMode().then((isPrivate) => { | |
console.log('Is in private mode: ', isPrivate); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment