Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove <script> elements before they render

I am trying to piece together a chrome extension that will delete all script elements before they are rendered... I think I am close, as it appears I am catching them ahead of time, but I just can't get them removed:

content.js

var mo = new MutationObserver(process);
mo.observe(document, {subtree:true, childList:true});
document.addEventListener('DOMContentLoaded', function() { mo.disconnect() 

});

function process(mutations) {
    for (var i = 0; i < mutations.length; i++) {
        var nodeArray = mutations[i].addedNodes;
        for (var j = 0; j < nodeArray.length; j++) {
            var n = nodeArray[j];
            if (n.nodeName == "SCRIPT") {
                deleteNode(n);
            }                
        }
    }
}

function deleteNode(node) {
    console.log("ATTEMPTING TO DELETE " + node.nodeName);
    node.remove();
}

manifest.json

{
  "name": "Test Extension",
  "version": "1.0",
  "description": "This is just a test",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": ["http://myRealUrl.com/internal/default.asp?*"],
      "js": ["content.js"],
      "run_at": "document_start",
      "all_frames": true
    }
  ]
}
like image 206
Jay Scott Avatar asked Sep 24 '26 17:09

Jay Scott


1 Answers

You can't.

In most situations*, <script> elements are executed as soon as they are encountered by the parser, before the DOM tree has been fully constructed. (This is required to allow document.write() to work correctly, among other things.) There is no window of opportunity for an extension to interrupt this process.

(Here is the relevant portion of the HTML5 specification.)

If you want to prevent scripts from executing, one viable approach might be to set a Content Security Policy which does not allow scripting. Keep in mind that this will also disable inline event handlers (like onclick), though.


*: An exception is scripts which have the async attribute set. Most scripts don't, though.