本文中,我使用的是 Microsoft Edge 瀏覽器,通過快捷指令可以實現(xiàn)一鍵將剪貼板中的內(nèi)容復制到 Google 翻譯網(wǎng)頁。


一般我是在閱讀 PDF 的時候,有些英文句子或者段落需要翻譯。但是每次從 Adobe Acrobat Reader 中復制大段文字的時候,都需要去除換行,再手動粘貼到瀏覽器中。
這個過程其實挺麻煩的,之前只是用快捷指令去除換行,所以這次再通過 AppleScript 來在瀏覽器中執(zhí)行 JavaScript,成功實現(xiàn)一鍵復制到網(wǎng)頁中。這時如果已經(jīng)打開了 Google Translate 標簽頁,那么就還是在這個頁面中粘貼剪貼板中的內(nèi)容到文本區(qū),否則就是打開一個新的 Google Translate 標簽頁。
一、首先設置瀏覽器中的“允許Apple事件中的JavaScript”
Edge 瀏覽器——(左上角菜單欄)查看——開發(fā)人員——允許Apple事件中的JavaScript

二、創(chuàng)建一個新的快捷指令
我的快捷指令執(zhí)行了兩個正則表達式,第一次是為了去除剪貼板中的換行。第二次,是有時候從 Acrobat Reader 中復制帶有“'s”的內(nèi)容時會出現(xiàn)亂碼“...陣”,于是進行了替換。

三、快捷指令中添加AppleScript
-- 備份剪貼板內(nèi)容
set clipText to the clipboard
tell application "Microsoft Edge"
activate
set foundTab to false
repeat with thisWindow in windows
set cnt to 1
repeat with thisTab in (tabs of thisWindow)
if URL of thisTab contains "https://translate.google.com/" then
set active tab index of thisWindow to cnt
set index of thisWindow to 1
set foundTab to true
exit repeat
end if
set cnt to cnt + 1
end repeat
end repeat
-- 如果沒找到,就在最前窗口新開一個標簽
if not foundTab then
set thisWindow to front window
set newTab to make new tab at end of tabs of thisWindow with properties {URL:"https://translate.google.com/"}
delay 1 -- 等待新頁面加載
end if
-- 在當前標簽頁執(zhí)行 JS:聚焦、賦值、觸發(fā) input 事件
execute front window's active tab javascript ?
"var input = document.querySelector('textarea[aria-label=\"原文\"]') || document.querySelector('textarea[aria-label=\"Source text\"]');" & ?
" input.focus();" & ?
" input.value = " & quoted form of clipText & ";" & ?
" input.dispatchEvent(new Event('input', { bubbles: true }));"
end tell
四、最后設置“在菜單欄中固定”
將快捷指令固定到菜單欄就可以實現(xiàn)一鍵粘貼到 Google 翻譯了。此外,AppleScript 是參考了一些網(wǎng)上內(nèi)容和 Copilot 一起完成的。如果你想要問這些代碼是什么意思,請你直接問 AI 助手喲。

參考文檔:
https://stackoverflow.com/questions/63839202/applescript-a-class-name-cant-go-after-this-identifier-error-what-does-it-m
https://apple.stackexchange.com/questions/278514/copy-selected-text-paste-on-google-translate-app-fluid-app-and-translate-it-w
https://gist.github.com/stevenschobert/ba6845feb5b0db7cdf04d04362720424