Jay Scott
Jay Scott

Reputation: 33

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
    }
  ]
}

Upvotes: 3

Views: 337

Answers (1)

user149341
user149341

Reputation:

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.

Upvotes: 2

Related Questions