Skip to content

Instantly share code, notes, and snippets.

@cowchimp
Created December 23, 2017 22:35
Show Gist options
  • Save cowchimp/c1c59e26bc75001f91b91f4023743dcb to your computer and use it in GitHub Desktop.
Save cowchimp/c1c59e26bc75001f91b91f4023743dcb to your computer and use it in GitHub Desktop.
simple example of how to run js code that was meant to run in a browser context from node
document.addEventListener('DOMContentLoaded', function() {
console.log(window.location.protocol);
});
const fs = require('fs');
const clientCode = fs.readFileSync('client-code.js', 'utf8');
const fakeLocation = { protocol: 'https:' };
const fakeWindow = { location: fakeLocation };
const fakeDocument = { addEventListener: (type, callback) => callback() }
const globals = {
window: fakeWindow,
document: fakeDocument
};
runClientScript(clientCode, globals);
function runClientScript(source, globals) {
const globalKeys = Object.keys(globals);
const globalValues = Object.values(globals);
const fn = new Function(globalKeys, source);
fn.apply(fakeWindow, globalValues);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment