通过一种或另一种技巧,我设法使用 SlimerJS 处理新窗口(window.open、target=blank 等)和 iframe 中的标题。也可以为新窗口更改导航器数据(例如 navigator.appVersion),但我坚持为 iframe 执行此操作。看起来 onInitialized 方法仅适用于主窗口和新窗口,但不适用于 iframe。
这是代码的一些部分。
var headers =
{
"Accept-Language" : "test_language",
"Accept" : "test/accpet",
"Connection" : "keep-alive",
"Keep-Alive" : "333",
"Accept-Charset" : "test-utf",
"User-Agent" : "test_ua"
}
var webpage = require('webpage').create(
{
pageSettings:
{
javascriptEnabled: true,
loadImages: true,
loadPlugins: true,
}
});
_onPageCreated = function(childPage)
{
console.log('a new window is opened');
childPage.settings.userAgent = options.useragent["navigator.userAgent"];
childPage.customHeaders = headers;
childPage.viewportSize = { width:400, height: 500 };
childPage.onInitialized = _onInitialized;
childPage.onNavigationRequested = _onNavigationRequested;
childPage.onLoadStarted = _onLoadStarted;
childPage.onLoadFinished = _onLoadFinished;
childPage.onResourceRequested = _onResourceRequested;
childPage.onPageCreated = _onPageCreated;
};
_onResourceRequested = function(requestData, networkRequest)
{
for(var h in headers)
{
networkRequest.setHeader(h, headers[h], false);
}
...
}
var _onInitialized = function()
{
this.customHeaders = headers;
console.log("[webpage.onInitialized]");
this.evaluate(function(options)
{
(function()
{
window.navigator.__defineGetter__('appVersion', function ()
{
return options.useragent["navigator.appVersion"];
});
...
})();
}, options);
};
...
webpage.onInitialized = _onInitialized;
webpage.onNavigationRequested = _onNavigationRequested;
webpage.onLoadFinished = _onLoadFinished;
webpage.onResourceRequested = _onResourceRequested;
webpage.onPageCreated = _onPageCreated;
我尝试使用 PhantomJS 执行此操作,但在以下情况下似乎无法使用“this”而不是“webpage”:
var _onInitialized = function()
{
console.log("[webpage.onInitialized]");
this.evaluate(function() // <<---not working
{
});
console.log("test"); //is not being printed
};
我希望此函数与“this”对象一起使用,以便可以将其定义为主页面和子页面的 onInitialized。
无论如何,主要问题是关于 SlimerJS 代码,而不是 Phantom 代码。