Skip to content

Instantly share code, notes, and snippets.

@SeanMcMillan
Created July 26, 2013 12:34
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 SeanMcMillan/6088521 to your computer and use it in GitHub Desktop.
Save SeanMcMillan/6088521 to your computer and use it in GitHub Desktop.
Attempting to load browser-js on node. I can make a fake window and load it, but if I turn `global` into the fake window, it fails with vm.runInNewContext(source, fakewindow); ^ ReferenceError: window is not defined
'use strict';
var fakewindow;
var fakedocument, fakenode;
fakedocument = {
createDocumentFragment: function() {
return {
appendChild: function() {}
};
},
documentElement: {},
nodeType: 9,
attachEvent: function() {}
};
fakenode = {
setAttribute: function() {},
getElementsByTagName: function() {
return {};
},
ownerDocument: fakedocument
};
fakedocument.createElement = function() {
return fakenode;
};
if (typeof window !== 'undefined') {
fakewindow = window;
fakewindow.loadGlobalScript = function() {};
} else if (typeof global !== 'undefined') {
fakewindow = {};
//fakewindow = global; // If this is uncommeted, it fails
fakewindow.window = fakewindow;
fakewindow.document = fakedocument;
fakewindow.attachEvent = function(){};
fakewindow.console || (fakewindow.console = console);
var source, vm;
vm = require('vm');
source = '(function(window, x) { console.log(window);})(window);';
vm.runInNewContext(source, fakewindow);
}
module.exports = fakewindow;
@jackcviers
Copy link

@SeanMcMillan I see two possibilities for this code: 1. A crawler. 2. A testing framework for DOM interactions.

For the crawler application, take a look at Casperjs[1] and crawler[2]. For the testing framework use case, I suggest grunt [3], grunt-mocha [4], sinon [5] and chai [6].

As for why this occurs - Form the Sandbox[7] section of the docs:

while properties of your sandbox object will be available in the context, any properties
from the prototypes of the sandbox may not be available

[1] http://casperjs.org/ Casperjs
[2] https://npmjs.org/package/crawler Crawler
[3] http://gruntjs.com/ grunt
[4] https://github.com/kmiyashiro/grunt-mocha grunt-mocha
[5] http://sinonjs.org/ sinon
[6] http://chaijs.com/ chai
[7] http://nodejs.org/api/vm.html#vm_sandboxes vm Sandbox

@SeanMcMillan
Copy link
Author

Oh, how did I miss your comment?

Yeah, it was for a testing framework. We eventually went with Testem + PhantomJs, and stopped trying to run on node at all.

I guess that the global object is actually derived from some kind of "default globals" object, and only hasOwnProperty of things you define on it directly? that's pretty cool, except that it breaks this use case. (Which is, pretty far from normal, I admit.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment