在jsDom中设置窗口宽度?

时间:2014-10-22 17:54:07

标签: node.js jsdom

应该是一个简单的问题。如何在jsDom对象中设置宽度?

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

我无法弄清楚如何获得" innerWidth"不过是1024

2 个答案:

答案 0 :(得分:3)

未实施resizeToresizeBy方法。你可以通过搜索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'),

如果您只想在初始化时一次性设置窗口大小,您可以将innerWidth值设置为您想要的任何值。在真正的浏览器中,这不是正确的方法,但在jsdom中它可以工作。

但是,如果您的代码依赖于resizeTo,则可以将自己的polyfill添加到构建窗口的构造函数中:

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);
    }
});

显示:

1024 768
100 200

上面的代码仅用于说明目的。我没有想过为resizeTo编写polyfill的所有细节。 resizeBy将以类似方式处理,但会将增量添加到窗口大小。

答案 1 :(得分:3)

目前没有正式的选项或API可供使用。

innerWidth和类似属性的值只是set to literal values

DOMWindow.prototype = createFrom(dom || null, {
  // ...
  name: 'nodejs',
  innerWidth: 1024,
  innerHeight: 768,
  outerWidth: 1024,
  outerHeight: 768,
  // ...
});

除了测试用例和文档outerWidth isn't referenced elsewhere else in jsdom之外,您可以在created event中分配新值,同时更新outerWidth

  

created的主要用例是在任何脚本执行之前修改窗口对象(例如在内置原型上添加新函数)。

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