-
-
Save devshark/8742475e11c626d8023e4244fb28090b to your computer and use it in GitHub Desktop.
Detect if the browser is running in Private mode
This file contains 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
// uncomment if you are transpiling with Babel + Webpack | |
// const { window, document } = global; | |
/** | |
* Lightweight script to detect whether the browser is running in Private mode. | |
* | |
* You should use a polyfill for Promise. | |
* @see https://ourcodeworld.com/articles/read/316/top-5-best-javascript-promises-polyfills | |
* | |
* @returns {Promise} | |
*/ | |
function isPrivateMode() { | |
return new Promise((resolve) => { | |
const yes = () => resolve(true); // is in private mode | |
const not = () => resolve(false); // not in private mode | |
const testLocalStorage = () => { | |
try { | |
if (localStorage.length) not(); | |
else { | |
localStorage.x = 1; | |
localStorage.removeItem('x'); | |
not(); | |
} | |
} 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 ? yes() : not(); | |
} | |
}; | |
// Chrome & Opera | |
if (window.webkitRequestFileSystem) { | |
return void window.webkitRequestFileSystem(0, 0, not, yes); | |
} | |
// Firefox | |
if ('MozAppearance' in document.documentElement.style) { | |
if (indexedDB === null) return yes(); | |
const db = indexedDB.open('test'); | |
db.onerror = yes; | |
db.onsuccess = not; | |
return void 0; | |
} | |
// Safari | |
const isSafari = navigator.userAgent.match(/Version\/([0-9\._]+).*Safari/); | |
if (isSafari) { | |
const version = parseInt(isSafari[1], 10); | |
if (version < 11) return testLocalStorage(); | |
try { | |
window.openDatabase(null, null, null, null); | |
return not(); | |
} catch (_) { | |
return yes(); | |
}; | |
} | |
// IE10+ & Edge InPrivate | |
if (!window.indexedDB && (window.PointerEvent || window.MSPointerEvent)) { | |
return yes(); | |
} | |
// default navigation mode | |
return not(); | |
}); | |
} |
This file contains 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
isPrivateMode().then((isPrivate) => { | |
console.log('browsing in private mode? ', isPrivate); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment