CasperJS无法设置window.navigator对象

时间:2014-12-17 10:42:01

标签: javascript phantomjs casperjs headless-browser

尝试使用CasperJS抓取网页。网页检查浏览器是否为IE 6/7。

使用casperjs传递userAgent似乎并不满足其条件。 UserAgent传递:Mozilla / 4.0(兼容; MSIE 6.0; Windows NT 5.1) 以下是页面进行检查以确定浏览器

agt = navigator.userAgent.toLowerCase();
browserType = navigator.appName;

if( ((browserType.indexOf("xplorer") != -1) 
    && (agt.indexOf("msie 6.") != -1))
    ||  ((browserType.indexOf("xplorer") != -1) 
    && (agt.indexOf("msie 7.") != -1)) )
{

}
else
{
    alert("This "+ browserType + " Version is not supported by this application. Please use Internet Explorer  6.x or Internet Explorer 7.x.");
    window.close();
}

以下是来自casperjs的调试信息。

  

[info] [remote] [alert]此应用程序不支持此Netscape版本   上。请使用Internet Explorer 6.x或Internet Explorer 7.x。

     

[警告] [幻影]加载资源失败,状态=失败(HTTP 200):http://

在页面重定向之前设置window.navigator对象的任何指针?

1 个答案:

答案 0 :(得分:3)

navigator属性是只读的,因此您无法设置它们,PhantomJS不提供设置它的功能。

解决方案是创建navigator对象的代理。旧的navigator会保留在后台,但会被替换为行为相同的新appName,但会使用casper.on('page.initialized', function(){ this.evaluate(function(){ (function(oldNav){ var newNav = {}; [].forEach.call(Object.getOwnPropertyNames(navigator), function(prop){ if (prop === 'appName') { Object.defineProperty(newNav, prop, { enumerable: false, configurable: false, writable: false, value: 'Internet Explorer' }); } else { Object.defineProperty(newNav, prop, { enumerable: false, configurable: false, get: function(){ return oldNav[prop]; } }); } }); window.navigator = newNav; })(window.navigator); }); }); 的“Internet Explorer”。可以从page.initialized回调触发整个引导过程。

page.onInitialized

对于带有{{1}}事件处理程序的vanilla PhantomJS,同样如此。

使用浏览器检测并不能保证页面在PhantomJS上运行或看起来不错。有一个原因是某些页面被IE“优化”了,原因在于大多数时候某些使用的专有功能在其他浏览器中没有。

相关问题