Alberto La Rocca Alberto La Rocca - 1 month ago 23
Node.js Question

Add script element to DOM without executing it

I am creating a Node script that reads an HTML file, manipulates it as a DOM document, and serializes it back to another file. I'm using jsdom for now.

One of the operations I need to do is to add a

<script>
element whose JavaScript code will do further manipulation on the DOM.

The problem is that as soon as I add the script to the jsdom node, jsdom runs it and the second stage of the manipulation is done immediately, therefore the output HTML is wrong.

I thought that would only happen in PhantomJS, not jsdom, but I was wrong.

I don't have particular constraints for using jsdom, I can switch to PhantomJS or whatever else, but I need to produce an HTML file with a script added to it without running the script during the execution of my Node program.

Is there a way to do that?

Answer

Use this to disable Javascript execution in jsdom

jsdom.defaultDocumentFeatures = {
FetchExternalResources: false,
ProcessExternalResources: false
};

If nodejs produces error disable mutation events also in jsdom

jsdom.defaultDocumentFeatures = {
FetchExternalResources: false,
ProcessExternalResources: false,
MutationEvents : false
};