在 Safari 中创建用于更改样式 sheet 的快捷方式

create a shortcut for changing style sheet in Safari

Safari 没有像 Chrome 这样的内置“黑暗主题”或夜间模式扩展,所以当我需要在黑暗的房间里做作业时(当我的室友正在睡觉时)真的很痛苦。值得庆幸的是,Safari 可以更改其默认 css sheet 偏好。所以我写了如下内容,

* {
color: rgb(176, 176,176) !important;

background: #000000  !important;
}

a:link {
color: rgb(99,202,67)!important;
}

它通常很好用,但我需要反复切换样式 sheet 特别是当它不是文本时 material。

所以我想知道如何创建用于切换样式的快捷方式sheet?
使用 AppleScript 怎么样?

我在各种应用程序中有很多设置,我定期在两种状态之间切换,并使用 AppleScript 自动执行任务。如果可能,我个人尽量不使用 UI 脚本,因为它可能有问题,但是,在您的特定情况下,我相信需要使用 AppleScript 的 UI 脚本解决方案来完成它。

就是说,如果 Safari 关闭,则在浏览 UI 时对 ~/Library/Preferences/com.apple.Safari.plist 文件所做的更改可能也可以使用 defaults 命令,然后打开 Safari。但是,我假设您希望能够在 Safari 打开的情况下即时进行此更改,而不必 close/reopen 来完成任务,因此 UI 编写脚本。

我把你问题中的代码保存为MyStyleSheet.css。

然后我手动完成了将其设置为样式 sheet 的过程:Safari > 首选项... > 高级 > 样式 sheet:

完成后,我将其设置回 None 选中状态,然后编写了这个 AppleScript 脚本:

示例 AppleScript 代码:

if not running of application "Safari" then
    display dialog "Safari is not open." buttons {"OK"} default button "OK"
    return
end if

tell application "Safari" to activate
delay 0.5
tell application "System Events"
    tell application process "Safari"
        click menu bar item "Safari" of menu bar 1
        click menu item "Preferences…" of menu 1 of menu bar item "Safari" of menu bar 1
        click UI element "Advanced" of toolbar 1 of window 1
    end tell
    tell group 1 of group 1 of window "Advanced" of application process "Safari"
        set currentStyleSheet to (value of pop up button 1)
        click pop up button 1
        if currentStyleSheet contains "None Selected" then
            click menu item "MyStyleSheet" of menu 1 of pop up button 1
        else
            click menu item "None Selected" of menu 1 of pop up button 1
        end if
    end tell
    click button 1 of window "Advanced" of application process "Safari"
end tell

我将上面的示例 AppleScript 代码保存为名为 Toggle Safari Style Sheet 的 AppleScript 应用程序,并测试它是否按预期工作。请注意,在更改样式 sheet 后,关闭 Safari 偏好设置可能会有时间延迟。滞后时间取决于 Safari windows 的打开方式以及系统上同时发生的其他 activity 的情况。无论是手动更改还是使用 AppleScript,此延迟都是一样的。


请注意,示例 AppleScript 代码仅此而已,旨在展示完成给定任务的方法。用户有责任根据需要添加任何适当的错误处理,并根据需要添加其他 delay 命令。