如何在 PhantomJS 中捕获由 window.open(url, _blank) 打开的新 window?

How to catch new window opend by window.open(url, _blank) in PhantomJS?

我想与 PhantomJS 检查我的脚本是否在点击时正确打开一个新的 window/tab。 open由js事件监听触发,通过window.open(url, "_blank").

打开

如何使用 PhantomJS 收听新的 window?

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

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 一个新的 page/tab 时,将为该页面创建一个新的 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 中捕获的幻像上下文中注册事件处理程序.

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