Mac利用快捷指令實現(xiàn)一鍵Google翻譯剪貼板

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


image.png
Google 翻譯

一般我是在閱讀 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


允許Apple事件中的JavaScript.png

二、創(chuàng)建一個新的快捷指令

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


Google翻譯剪貼板快捷指令配置1.png

三、快捷指令中添加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 助手喲。


Google翻譯剪貼板快捷指令配置2.png

參考文檔:

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容