Mac利用快捷指令实现一键Google翻译剪贴板

本文中,我使用的是 Microsoft Edge 浏览器,通过快捷指令可以实现一键将剪贴板中的内容复制到 Google 翻译网页。


image.png
Google 翻译

一般我是在阅读 PDF 的时候,有些英文句子或者段落需要翻译。但是每次从 Adobe Acrobat Reader 中复制大段文字的时候,都需要去除换行,再手动粘贴到浏览器中。

这个过程其实挺麻烦的,之前只是用快捷指令去除换行,所以这次再通过 AppleScript 来在浏览器中执行 JavaScript,成功实现一键复制到网页中。这时如果已经打开了 Google Translate 标签页,那么就还是在这个页面中粘贴剪贴板中的内容到文本区,否则就是打开一个新的 Google Translate 标签页。

一、首先设置浏览器中的“允许Apple事件中的JavaScript”

Edge 浏览器——(左上角菜单栏)查看——开发人员——允许Apple事件中的JavaScript


允许Apple事件中的JavaScript.png

二、创建一个新的快捷指令

我的快捷指令执行了两个正则表达式,第一次是为了去除剪贴板中的换行。第二次,是有时候从 Acrobat Reader 中复制带有“'s”的内容时会出现乱码“...阵”,于是进行了替换。


Google翻译剪贴板快捷指令配置1.png

三、快捷指令中添加AppleScript

-- 备份剪贴板内容
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
    -- 在当前标签页执行 JS:聚焦、赋值、触发 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

四、最后设置“在菜单栏中固定”

将快捷指令固定到菜单栏就可以实现一键粘贴到 Google 翻译了。此外,AppleScript 是参考了一些网上内容和 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容