Created
December 23, 2017 22:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener('DOMContentLoaded', function() { | |
console.log(window.location.protocol); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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