DOMNodeInserted not working properly

I have a problem.

"DOMNodeInserted" does not work as intended. I am not sure if I am using it correctly.

Any ideas?

+1
source share
1 answer

<Sub> EDIT: Scroll down for a better approach using MutationObserver .. p>


sub>

When building the DOM, page loads do not trigger events DOMNodeInserted. I don’t think there is a way for HTML to go through the filter before being rendered (or, if there is, I don’t know).

DOMContentLoaded , (, , ).

, DOM (, , AJAX ..) . A MutationObserver .

, :

manifest.json
( , :
browser_action, page_action, background, permissions)

...
"content_scripts": [
    {
        "matches": [
            "http://stackoverflow.com/*",
            "http://www.stackoverflow.com/*"
        ],
        "js":         ["content.js"],
        "run_at":     "document_start",
        "all_frames": true
    }
],
...

content.js

// Implement your filtering mechanism
// Good luck trying not to break the HTML :)
var doFilter = function(elem) {
    // Demo filtering: highlighting links 
    // (and possibly breaking HTML in many pages)
    elem.innerHTML = elem.innerHTML.replace(
        /(<a[^>]*)(>[^<]*<\/a>)/ig,
        "$1 style=\"background-color: yellow;\"$2");
};

window.addEventListener("DOMContentLoaded", function() {
    doFilter(document.body);
});

UPDATE

, MutationObserver, . , "" .
( - twicking, , node.)

content.js

// Highligth the element by giving it a yellow background
var doFilter = function(link) {
    link.style.backgroundColor = "yellow";
}

// Create a MutationObserver to handle events (i.e. filtering <a> elements)
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.addedNodes) {
            for (var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.nodeName == "A") {
                    doFilter(node);
                }
            }
        }
    });
});

// Start observing "childList" events in document and its descendants
observer.observe(document, {
    childList:     true,
    subtree:       true
});

MutationObserver, JS, : mutation-summary

+4

All Articles