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

Man*_*uel 5 javascript window.open phantomjs

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

如何使用PhantomJS监听新窗口?

Art*_* B. 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);
    }
})
Run Code Online (Sandbox Code Playgroud)

网页

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

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

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);
    }
})
Run Code Online (Sandbox Code Playgroud)

代理解决方案

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);
    }
})
Run Code Online (Sandbox Code Playgroud)