【问题标题】:Highlight All Words in Chrome Extension突出显示 Chrome 扩展程序中的所有单词
【发布时间】:2014-01-14 17:13:52
【问题描述】:

我是一个尝试创建 chrome 扩展的初学者。在这个扩展中,我想要一个 popup.html 文件,上面有“突出显示”按钮。如果用户点击突出显示页面中的所有单词应该被突出显示。

清单

"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 以突出显示每个单词?

提前致谢!

【问题讨论】:

标签: javascript html google-chrome google-chrome-extension


【解决方案1】:

您无法从 popup 访问 DOM,但您可以使用 content script 访问 DOM。查看this question,它解释了content script 和background script 之间的区别。 弹出脚本与后台脚本具有相同的权限/权力。

要添加内容脚本,请将其添加到您的 manifest.json

"content_scripts": [
  {
    "matches": ["http://*/*"], 
    "js": ["temp.js"]
  }
] 

然后如 cmets 中所述,使用一些小 jQuery 代码来突出显示单词。

【讨论】:

    【解决方案2】:

    通过 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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2012-08-04
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多