I'm trying to write AppleScript which would tell whether a window of Safari is in private mode. Here is the AppleScript to do so in Chrome:
tell application "Google Chrome"
set incognitoIsRunning to the (count of (get every window whose mode is "incognito")) is greater than 0
end tell
if (incognitoIsRunning) then
return "-- PRIVATE MODE --"
end tell
The old solution to see whether private browsing menu option is checked no longer works.
There is a quirk in Safari that can be exploited to determine whether private mode is enabled: Safari does not allow localStorage.setItem to be used in private mode (see related StackOverflow post). We can take advantage of this by using a snippet of JavaScript from within AppleScript. If localStorage is not supported, the JavaScript throws an error (caught by the try/catch block), which we use to set our boolean.
tell application "Safari"
set checkMode to "
var isprivate = false;
try {
window.localStorage.setItem('foobar', 1);
} catch(e) {
isprivate = true;
}
isprivate;
"
set isPrivate to do JavaScript checkMode in current tab of first window
end tell
log isPrivate
Of course you will need to adjust this AppleScript to set the appropriate target window/tab within Safari.