Chrome Extension: DOM traversal

前端 未结 3 1101
天命终不由人
天命终不由人 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 22:53

    Do NOT use regular expressions to parse HTML. The

    cannot hold.

    With that out of the way... although you can use XPath, I think querySelector is similar in power while being somewhat simpler as well.

    You simply pass a CSS selector as a string, and it returns the elements that match the selector. Kinda like using jQuery without needing to load the jQuery library.

    Here's how you would use it:

    var query = document.querySelector("div#hello");
    if (query) {
        alert("This page has a friendly div");
    }
    
    var query = document.querySelectorAll("a[href='http://bananas.com']");
    for (var i = 0; i < query.length; i += 1) {
        if (query[i].textContent === "I am married to a banana") {
            alert("This guy is weird.");
            return;
        }
    }
    

    document.querySelector finds only a single element, and returns null if that element is not found.

    document.querySelectorAll returns a fake-array of elements, or an empty fake-array if none are found.

    ...however, it sounds like you're wanting to update the browser action popup when something is detected in a webpage, correct? If so, that is possible but immensely more difficult.

    Mohamed Mansour's post will get you to the point where you can communicate between content scripts and the background page/popup, but there are other bits that need to be done as well.

提交回复
热议问题