Set window width in jsDom?

倖福魔咒の 提交于 2019-12-07 01:46:53

问题


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


回答1:


There isn't currently a formal option or API for doing so.

The values of 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,
  // ...
});

Beyond test cases and documentation, outerWidth isn't referenced elsewhere else in jsdom, so you could probably assign a new value within the created event, updating outerWidth as well.

The primary use-case for created is to modify the window object (e.g. add new functions on built-in prototypes) before any scripts execute.

created: function (errors, tstWindow) {
    tstWindow.outerWidth = tstWindow.innerWidth = 1440;
},
done: function(errors, tstWindow) {
    console.log(tstWindow.innerWidth);
}



回答2:


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.



来源:https://stackoverflow.com/questions/26513921/set-window-width-in-jsdom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!