Update @20210922: 更新支持Safari 15
可能不是很多人知道Omnikey for Safari,但用上以后很难离开。Omnikey的作用是按照你的设定扩展URL,最常见的用途是输入关键字,自动帮你搜索对应的网站。比如我设置在Safari地址栏输入tb 商品名
,可以自动帮你转成到淘宝搜索。
可惜的是,因为这是一个独立的第三方免费开源插件,所以Safari 13(特别是macOS 10.15 Catalina)以后,这个插件没法安装使用了。估计短时间内原作者不会在Mac App Store上架。最近搜索进展的时候,找到了替代脚本,实现效果也还不错:
这是把插件自动运行的方式变成了要通过快捷键激活脚本的形式,多了个输入快捷键的步骤。先分享一下脚本。
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions
property |⌘| : a reference to current application
property shortcuts : {{"a", "https://www.amazon.com/s/?link_code=wsw&_encoding=UTF-8&search-alias=aps&field-keywords={search}&Submit.x=0&Submit.y=0&Submit=Go"}, ¬
{"imdb", "https://www.imdb.com/find?q={search}&s=all"}, ¬
{"maps", "https://maps.google.com/maps?hl=en&authuser=0&q={search}&ie=UTF-8"}, ¬
{"w", "https://en.wikipedia.org/w/index.php?title=Special:Search&search={search}"}, ¬
{"y", "https://www.youtube.com/results?search_query={search}"}, ¬
{"bk", "https://search.douban.com/book/subject_search?search_text={search}&cat=1001"}, ¬
{"tb", "https://s.taobao.com/search?q={search}"}, ¬
{"jd", "https://search.jd.com/Search?keyword={search}&enc=utf-8"}, ¬
{"z", "https://www.amazon.cn/s?k={search}"}}
-- Get the existing clipboard contents.
set oldClipboard to (the clipboard)
-- Ensure Safari's the frontmost process.
activate application "Safari"
tell application "System Events"
set frontmost of application process "Safari" to true
-- Select and copy the address field contents.
keystroke "lc" using {command down}
end tell
-- Keep getting the clipboard contents until they change or haven't changed after a certain time. (Adjust as required.)
repeat 2 times
set textValue to (the clipboard)
if (textValue is not oldClipboard) then exit repeat
delay 0.5
end repeat
-- Restore the old contents. (Optional.)
set the clipboard to oldClipboard
set spaceOffset to offset of space in textValue
if spaceOffset = 0 then return
set token to text 1 thru (spaceOffset - 1) of textValue
set query to text (spaceOffset + 1) thru -1 of textValue
set nsQuery to |⌘|'s NSString's stringWithString:query
set allowedPathCharacterSet to |⌘|'s NSCharacterSet's URLPathAllowedCharacterSet()
set encodedQuery to nsQuery's stringByAddingPercentEncodingWithAllowedCharacters:allowedPathCharacterSet
repeat with aShortcut in shortcuts
set {_token, _url} to contents of aShortcut
if _token is token then
set queryURL to (|⌘|'s NSString's stringWithString:_url)
set searchURL to (queryURL's stringByReplacingOccurrencesOfString:"{search}" withString:encodedQuery)
tell application "Safari" to set URL of current tab of window 1 to (searchURL as text)
exit repeat
end if
end repeat
这个脚本的主体版本是来自这里。我稍微加了一点国内购物网站的配置。为了方便大家使用,也提供附件下载。
需要个性化定制的,就直接修改脚本里property shortcuts
的部分,{}
里都是一对配置,第一个是缩写字符,后面是扩展后的URL,{search}
代表你搜索的关键词。比如第一行配置就表示先输入a
再输入关键词,就变成到美亚搜索关键词。
因为是AppleScript,所以脚本可以配置好几种触发方式,我个人是在Keyboard Maestro里配置了一个脚本组,仅在Safari里用Command+K激活;也可以直接在系统偏好设置的键盘快捷键那里设置,用系统自己的功能调用;要是喜欢Alfred的也可以改造下。原作者的Github里有个issue也讨论了这个问题,大家可以参考。