在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屋!