Chrome Extension: DOM traversal

前端 未结 3 1099
天命终不由人
天命终不由人 2021-02-04 22:36

I want to write a Chrome extension that looks at the HTML of the page its on, and if it finds eg

then it will output, as a HTML list in the
3条回答
  •  北海茫月
    2021-02-04 23:01

    Well that stackoverflow question asked how to let your extension talk to the DOM. There are numerous ways, one way is through chrome.tabs.executeScript, and another way is through Message Passing as I explained in that question.

    Back to your question, you could use XPath to search within the DOM. It is pretty powerful. For example you said you want to search for

    , you can do it like this:

    var nodes = document.evaluate("//div[@id='hello']", document, null, 
                                   XPathResult.ANY_TYPE, null)
    var resultNode = nodes.iterateNext()
    if (resultNode) {
      // Found the first node. Output its contents.
      alert(resultNode.innerHTML);
    }
    

    Now for your second example, same thing .. I am married to a banana

    var nodes = document.evaluate("//a[@href='http://bananas.com']/text()[contains(.,'married')]",
                                   document, null, 
                                   XPathResult.ANY_TYPE, null)
    var resultNode = nodes.iterateNext()
    if (resultNode) {
      // Found the first node. Output its contents.
      alert('This guy is weird');
    }
    

    Well you could use XPath which does work perfectly in Chrome, and you can make your query simple such as finding nodes that you want or even complex with detail. You can query any node, and then do post processing if you wish as well.

    Hope that helped. Remember all this should be within a content script in the Chrome Extension. And if you want your extension to communicate to that, you can use Message Passing as I explained in the other post. So basically, within your popup.html, you send a request to the content script to find you text. Your content script will send back a response from its callback. To send the request, you should use chrome.tabs.sendRequest and within the content script.You listen for that request and handle it. As I explained in the other stackoverflow question.

提交回复
热议问题