在AppleScript中检测Safari私密浏览(Detect Safari Private Browsing in AppleScript)

我正在尝试编写AppleScript,它可以判断Safari的窗口是否处于私有模式 。 以下是在Chrome中执行此操作的AppleScript:

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

查看是否已选中隐私浏览菜单选项的旧解决方案不再有效。

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.

最满意答案

Safari中有一个怪癖,可以利用它来确定是否启用了私有模式:Safari不允许在私有模式下使用localStorage.setItem(请参阅相关的StackOverflow帖子 )。 我们可以通过在AppleScript中使用JavaScript片段来利用这一点。 如果不支持localStorage,则JavaScript会抛出一个错误(由try / catch块捕获),我们用它来设置我们的布尔值。

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

当然,您需要调整此AppleScript以在Safari中设置适当的目标窗口/选项卡。

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.

更多推荐