Set window width in jsDom?
There should be a simple question. How to set width in 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 "innerWidth" to be only 1024
source to share
There is currently no formal option or API for this.
Values innerWidth
and similar properties are simply set to literal values :
DOMWindow.prototype = createFrom(dom || null, {
// ...
name: 'nodejs',
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
// ...
});
Apart from test cases and documentation, outerWidth
not mentioned elsewhere in jsdom , so you can probably assign a new value within the created
event by updating outerWidth
.
The main use case
created
is to modify the window object (for example, add new functionality to built-in prototypes) before executing any scripts.
created: function (errors, tstWindow) {
tstWindow.outerWidth = tstWindow.innerWidth = 1440;
},
done: function(errors, tstWindow) {
console.log(tstWindow.innerWidth);
}
source to share
Methods resizeTo
and are resizeBy
not implemented. You can see this by searching the jsdom codebase:
$ 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 during initialization, you can simply set the value innerWidth
to whatever you want. In a real browser, this is not the correct way to do it, but in jsdom it will work.
However, if you have code that depends on presence resizeTo
, 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);
}
});
Displayed:
1024 768
100 200
The above code is for illustration purposes only. I didn't think about all the mistakes in writing the polyfill for resizeTo
. resizeBy
will be handled similarly, but will add deltas to the window size.
source to share