我是一个尝试创建Chrome扩展程序的初学者。在此扩展程序中,我想创建一个popup.html文件,上面带有“highlight”按钮。如果用户单击突出显示,则页面中的所有单词都应突出显示。
显现
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs", "activeTab"
]
Popup.html
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<button id="highlight">Highlight</button>
</body>
</html>
popup.js
window.onload = function(){
document.getElementById('highlight').onclick = highLight;
function = highLight(){
//How can I make all the text highlighted
}
};
如何访问DOM,以便每个单词都突出显示?
提前致谢!
最佳答案
通过Chrome扩展程序突出显示页面上的文本(或在页面上执行任何操作)必须通过Content Script完成。但是,当在弹出窗口中单击按钮时,弹出窗口必须与内容脚本进行对话,以告诉它突出显示页面。这称为Message Passing。
您的popup.js
应该看起来像这样:
document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false);
function sendHighlightMessage() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) {
console.log(response);
});
});
}
content_script.js
是实际进行DOM操作的地方。它应该监听您的弹出窗口中的消息,并适当突出显示该页面。它应包含以下内容:chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.highlight === true) {
highlightText(document.body);
sendResponse({messageStatus: "received"});
}
});
仔细阅读Chrome扩展程序文档中有关内容脚本和消息传递的信息(如上链接),以更全面地了解此处发生的情况。
实际上,无法像选择文本一样在页面上突出显示文本(例如,单击并拖动文本以进行复制和粘贴),无法在文本区域或输入字段之外以编程方式完成。但是,您可以使用样式来更改文本的背景颜色。为了仅突出显示文本,您需要使用突出显示样式将每个文本节点包装在一个跨度中。这是很多DOM操作,将完全破坏原始页面。您应该考虑这对于扩展来说是否真的必要和有用。也就是说,它看起来像这样:
function highlightText(element) {
var nodes = element.childNodes;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i].nodeType === 3) // Node Type 3 is a text node
var text = nodes[i].innerHTML;
nodes[i].innerHTML = "<span style='background-color:#FFEA0'>" + text + "</span>";
}
else if (nodes[i].childNodes.length > 0) {
highlightText(nodes[i]); // Not a text node or leaf, so check it's children
}
}
}
关于javascript - 突出显示Chrome扩展程序中的所有单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20795142/