我想在当前的safari选项卡上找到一个文本,并将颜色和文本更改为粗体。
我假设这方面的JS代码如下所示:
// Define the text to search for
var searchText = "example text";
// Get all the text nodes in the current page
var textNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
// Find the text in the text nodes and change the color and make the text bold
while(textNodes.nextNode()) {
var node = textNodes.currentNode;
if(node.nodeValue.includes(searchText)) {
var span = document.createElement("span");
span.style.color = "#FF0000";
span.style.fontWeight = "bold";
span.innerHTML = node.nodeValue;
node.parentNode.replaceChild(span, node);
}
}
但是我不知道如何从地址栏运行这个程序?我试着用"javascript:"作为前缀,但是不起作用。
Safari异常可能更合适,但我不知道如何操作
如果有帮助话,下面是我的AppleScript,它也可以做到这一点:- -这个applescript还设置了同一页上列表中的文本,如果我能做完全相同的事情,那就更好了
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
更新:
我觉得这个JavaScript更像是我想做的(应该作为我的AppleSript工作),但我仍然有同样的问题(我想从地址栏运行它,这样我就可以很容易地从书签调用它)
// Get all elements with class "sortable webOrder" and filter out elements with text "Web Order"
var elements = Array.from(document.querySelectorAll('.sortable.webOrder'))
.filter(x => x.textContent.trim() !== 'Web Order');
// Get the text content of the elements
var texts = elements.map(x => x.textContent.trim());
// Remove duplicates
var theList = [...new Set(texts)];
// Find the text in the current page and change color and make it bold
theList.forEach(aText => {
var range, sel;
if (document.createRange) {
range = document.createRange();
range.selectNodeContents(document.body);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
while (window.find(aText, true)) {
document.execCommand("ForeColor", false, "#FF0000");
document.execCommand("bold");
}
sel.removeAllRanges();
}
});
1条答案
按热度按时间myzjeezk1#
你几乎已经明白了:
同样的写法: