Set window width in jsDom?

Skip Huffman picture Skip Huffman · Oct 22, 2014 · Viewed 7.5k times · Source

Should be a simple question. How do I set the width in a jsDom object?

    jsdom.env({
        url:'http://testdatalocation',
        scripts: ['http://code.jquery.com/jquery.js'],
        done: function(errors, tstWindow) {
            console.log(tstWindow.innerWidth);
};
}
});

I can't figure out how to get the "innerWidth" to be anything but 1024

Answer

Louis picture Louis · Oct 22, 2014

The resizeTo and resizeBy methods are not implemented. You can see that by searching through the code base of jsdom:

$ grep -P 'resize(To|By)' `find . -type f`
./lib/jsdom/browser/index.js:    resizeBy: NOT_IMPLEMENTED(null, 'window.resizeBy'),
./lib/jsdom/browser/index.js:    resizeTo: NOT_IMPLEMENTED(null, 'window.resizeTo'),

If you just want to set the window size once and for all at initialization time, you could just set the innerWidth value to whatever you want. In a real browser, this is not the right way to do it, but in jsdom it would work.

However, if you have code that depends on resizeTo being present, you can add your own polyfill to the constructor that builds windows:

var jsdom = require("jsdom");

var document = jsdom.env({
    html: "<html></html>",
    done: function (error, w) {
        console.log(w.innerWidth, w.innerHeight);
        w.constructor.prototype.resizeTo = function (width, height) {
            this.innerWidth = this.outerWidth = width;
            this.innerHeight = this.outerHeight = height;
        };
        w.resizeTo(100, 200);
        console.log(w.innerWidth, w.innerHeight);
    }
});

This displays:

1024 768
100 200

The code above is for illustration purposes. I've not thought about all the ins and outs of writing a polyfill for resizeTo. resizeBy would be handled similarly but would add deltas to the size of the window.