Skip to content Skip to sidebar Skip to footer

Chrome Extension, Inject Html Then Continue Loading Page

The extension I am writing triggers a content script on the start of page load, using: 'run_at': 'document_start' This works just fine. However, I need to 'inject' something an

Solution 1:

Well, I don't see much point writing to the document before<body> even exists, but you can do this with DOM manipulation as opposed to document.write:

var el = document.createElement("span");
el.textContent = "Hello, World!";
document.documentElement.appendChild(el);

This will not block the subsequent DOM parsing.

If you want to conform to a standard page structure and add it to the body element, you can add a MutationObserver to wait for it (though this may not be better than "document_end" injection):

var observer = newMutationObserver(function(mutations) {
  mutations.find(function(mutation) {
    for (var i = 0; i < mutation.addedNodes.length; i++) {
      if(mutation.addedNodes[i].nodeName === "BODY") {
        var el = document.createElement("span");
        el.textContent = "Hello, World!";
        // Clunky way to prepend a node
        mutation.addedNodes[i].insertBefore(el, mutation.addedNodes[i].firstChild);

        observer.disconnect();
        returntrue; // Early termination of find()
      }
    }
  });
});
observer.observe(document.documentElement, {childList: true});

Post a Comment for "Chrome Extension, Inject Html Then Continue Loading Page"