Skip to content

Instantly share code, notes, and snippets.

@ricokahler
Last active February 20, 2017 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricokahler/c8aef41ee27e5304e94f6a255b048f87 to your computer and use it in GitHub Desktop.
Save ricokahler/c8aef41ee27e5304e94f6a255b048f87 to your computer and use it in GitHub Desktop.
Evaluate JS to JSDOM

To answer this question.

Clone this gist, cd, install, and run

git clone https://gist.github.com/c8aef41ee27e5304e94f6a255b048f87.git apply-js-to-html
cd apply-js-to-html
npm install
node example.js

Observe that the output has applied the javascript.

const applu = require('./index');
const html = `
<html>
<head></head>
<body>
<p id="content"></p>
<body>
</html>
`;
const js = `document.getElementById("content").innerHTML = "Hello";`
applu(html, js).then(result => {
console.log('input html: ', html);
console.log('output html: ', result);
}).catch(err => console.error(error));
const jsdom = require('jsdom');
module.exports = function (html, js) {
return new Promise((resolve, reject) => {
jsdom.env(html, (error, window) => {
if (error) {
reject(error);
}
try {
(function evalInContext () {
'use strict';
const document = this.document;
const window = this.window;
eval(js);
resolve(window.document.documentElement.innerHTML);
}).call(window);
} catch (e) {
reject(e);
}
});
});
}
{
"name": "apply-js-to-html",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"jsdom": "^9.11.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment