在 AppleScript 中检测 Safari 私密浏览 [英] Detect Safari Private Browsing in AppleScript
问题描述
我正在尝试编写 AppleScript,它可以判断 Safari 的窗口是否处于私密模式.这是在 Chrome 中执行此操作的 AppleScript:
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 块捕获),我们用它来设置布尔值.
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
当然,您需要调整此 AppleScript 以在 Safari 中设置适当的目标窗口/选项卡.
Of course you will need to adjust this AppleScript to set the appropriate target window/tab within Safari.
这篇关于在 AppleScript 中检测 Safari 私密浏览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!