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

如何在Safari地址栏运行JS脚本实现指定文本红体加粗?

Safari地址栏运行文本高亮脚本指南

问题背景

需要在Safari当前标签页中定位指定文本,将其设置为红色加粗,编写的JS脚本加javascript:前缀在地址栏运行失败,同时有实现相同功能的AppleScript,希望了解地址栏的正确运行方式。

地址栏运行失败的核心原因

  • Safari默认会拦截地址栏中直接输入的javascript:脚本,需确保输入格式完全合规
  • 脚本中的换行、未转义的双引号会触发语法错误
  • 初始脚本的文本节点替换逻辑存在漏洞(未处理文本拆分场景)

修正后的可运行脚本

版本1:指定单个文本高亮

将以下代码压缩为单行,添加javascript:前缀后粘贴到地址栏运行(替换"目标文本"为你需要查找的内容):

javascript:(function(){var t="目标文本",n=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,!1);while(n.nextNode()){var e=n.currentNode;if(e.nodeValue.includes(t)){var o=document.createElement("span");o.style.color="#FF0000",o.style.fontWeight="bold",o.textContent=e.nodeValue,e.parentNode.replaceChild(o,e)}}})();

版本2:提取.sortable.webOrder元素文本批量高亮

对应你更新后的JS逻辑,压缩为可直接运行的单行版本:

javascript:(function(){var e=Array.from(document.querySelectorAll(".sortable.webOrder")).filter(e=>e.textContent.trim()!=="Web Order"),t=[...new Set(e.map(e=>e.textContent.trim()))];t.forEach(e=>{var t,n;document.createRange&&(t=document.createRange(),t.selectNodeContents(document.body),n=window.getSelection(),n.removeAllRanges(),n.addRange(t),while(window.find(e,!0)){document.execCommand("ForeColor",!1,"#FF0000"),document.execCommand("bold")},n.removeAllRanges())})})();

地址栏运行的正确步骤

  1. 复制上述压缩后的完整脚本(包含javascript:前缀)
  2. 点击Safari地址栏,全选现有内容
  3. 粘贴脚本后按回车键执行

AppleScript版本说明(可选)

你的AppleScript逻辑是可行的,它通过Safari的do JavaScript接口执行DOM操作,适合批量自动化场景,但临时单次操作时,地址栏运行JS脚本更便捷:

set theList to {}
tell application "Safari" to tell tab 1 of window 1 to tell (do JavaScript "
    [...new Set( document.querySelectorAll('.sortable.webOrder') )]
    .map( x => x.textContent.trim() )
    .filter( x => x !== 'Web Order');") ¬
    to set theList to every text

tell application "Safari"
    activate
    set theWindow to front window
    tell theWindow
        tell current tab
            do JavaScript "document.designMode = 'on'"
            repeat with aText in theList
                do JavaScript "var sel = window.getSelection(); sel.collapse(document.body, 0); while (window.find('" & aText & "', true)) {document.execCommand('ForeColor', false, '#FF0000');document.execCommand('bold');}"
            end repeat
            do JavaScript "document.designMode = 'off'"
        end tell
    end tell
end tell

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:06:04