You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript开发需求:Chrome选词转剑桥词典查询脚本修复

修复后的AppleScript实现方案

核心实现逻辑

  • 无需剪贴板的选中文本获取:利用Chrome的AppleScript原生API直接读取当前标签页的选中内容,避免覆盖用户剪贴板。
  • 健壮的空格替换:通过shell命令处理连续空格,统一替换为单个连字符。
  • 新标签页打开词典:构造剑桥词典的查询URL,在当前Chrome窗口创建新标签加载目标页面。

修复后的可运行脚本

tell application "Google Chrome"
    -- 获取当前激活标签页的选中文本
    set selectedText to selection of active tab of front window as string
    
    -- 处理空选中的情况
    if selectedText is equal to "" then
        display alert "请先选中要查询的文本"
        return
    end if
    
    -- 替换所有连续空格为连字符(支持多个空格的情况)
    set hyphenatedText to do shell script "echo " & quoted form of selectedText & " | sed 's/\\s\\+/-/g'"
    
    -- 构造剑桥英汉词典的查询URL
    set dictURL to "https://dictionary.cambridge.org/dictionary/english-chinese-simplified/" & hyphenatedText
    
    -- 在当前窗口末尾创建新标签并加载URL
    make new tab at end of tabs of front window with properties {URL:dictURL}
end tell

关键说明

  1. 原生选中文本读取:selection of active tab of front window是Chrome官方支持的AppleScript属性,能直接获取用户选中的文本,比剪贴板方案更高效且无副作用。
  2. 异常处理:增加了空选中的判断,避免脚本因无选中内容而报错。
  3. 空格替换逻辑:使用sed的正则表达式\s\+匹配所有连续空白字符(包括空格、制表符等),替换为单个连字符,处理更全面。
  4. 新标签创建方式:make new tab at end of tabs确保新标签在当前窗口的末尾打开,符合常规使用习惯。

权限配置

首次运行脚本时,系统可能会提示权限请求,需前往「系统设置 > 安全性与隐私 > 隐私 > 自动化」,允许对应的鼠标手势应用和AppleScript控制Google Chrome。

内容的提问来源于stack exchange,提问作者Ace Ace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:30:46