如何在PhantomJS中通过window.open(url,_blank)捕获新窗口?

时间:2015-01-16 08:50:31

标签: javascript phantomjs window.open

我想查看PhantomJS是否我的脚本在点击时正确打开了一个新窗口/标签。 open由js事件监听器触发,并通过window.open(url, "_blank")打开。

如何使用PhantomJS收听新窗口?

1 个答案:

答案 0 :(得分:13)

似乎有三种方法可以做到这一点:

onPageCreated

CasperJS使用page.onPageCreated解决了这个问题。因此,当在页面中调用window.open时,将创建一个新页面,并使用新创建的页面触发page.onPageCreated

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        page.onPageCreated = function(newPage){
            newPage.onLoadFinished = function(){
                console.log(newPage.url);
                phantom.exit();
            };
        };
        page.evaluate(function(url){
            window.open(url+"?something=other", "_blank");
        }, address);
    }
})

PhantomJS' page具有pages属性,用于处理子页面。因此,当您open新页面/选项卡时,会为该页面创建一个新的webpage对象。您需要尝试在触发之前向页面添加onLoadFinished事件侦听器(无承诺)。如果从页面上下文中调用window.open未知延迟,则可能很难。

这可以通过使用waitFor之类的东西来修复,以等待新页面出现,并在加载页面之前附加事件处理程序。这是一个小调整的完整代码。重试间隔从250毫秒减少到50毫秒。

var page = require('webpage').create();
var address = "http://example.com/";

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 50); //< repeat check every 50ms
};

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        console.log("p:", page.ownsPages, typeof page.pages, page.pages.length, page.pages);
        waitFor(function test(){
            return page.pages && page.pages[0];
        }, function ready(){
            page.pages[0].onLoadFinished = function(){
                console.log("p:", page.ownsPages, typeof page.pages, page.pages.length, page.pages);
                console.log("inner:", page.pages[0].url);
                phantom.exit();
            };
        });
        page.evaluate(function(url){
            window.open(url+"?something=other", "_blank");
        }, address);
    }
})

代理解决方案

可以代理window.open函数,在页面上下文中打开页面之后,可以在通过window.callPhantom发出信号的虚拟上下文中注册事件处理程序,并将其记录在onCallback中。< / p>

page.onInitialized = function(){
    page.evaluate(function(){
        var _oldOpen = window.open;
        window.open = function(url, type){
            _oldOpen.call(window, url, type);
            window.callPhantom({type: "open"});
        };
    });
};
page.onCallback = function(data){
    // a little delay might be necessary
    if (data.type === "open" && page.pages.length > 0) {
        var newPage = page.pages[page.pages.length-1];
        newPage.onLoadFinished = function(){
            console.log(newPage.url);
            phantom.exit();
        };
    }
};
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        page.evaluate(function(url){
            window.open(url+"?something=other", "_blank");
        }, address);
    }
})