Phantomjs使用page.evaluate在page.open之外

时间:2014-05-07 14:28:09

标签: javascript phantomjs

我正在使用phantomjs向网页注入一个命令以模拟按键。

在page.open上,我有一个事件处理程序,用于查看网页是否已完成加载,作为控制台消息。

然后使用:

page.onConsoleMessage = function(msg) { }

我看看是否返回了msg。在这个onconsole消息中,我调用了一个page.evaluate函数来模拟按键,但似乎没有任何事情发生。

可以这样做吗?或者page.evaluate是否需要在page.open请求中。

代码

page.onConsoleMessage = function(msg) {
    var phantomCommand = null;
    //console.log(msg);
    try {
        phantomCommand = JSON.parse(msg);
    }
    catch(e) {
    }

    if(phantomCommand != null) {
        switch(phantomCommand.command) {
            case "PageChangeCompleted":
                for ( var a in this.actions) {
                    if ( profile == a ) {
                    for ( var la in this.actions[a] ) {
                        var nextAction = this.actions[a][la];
                    if ( nextAction.action == 'keyPress' ) {
                        keyCode = this.clientInfo.keyCodes[nextAction.key];
                        console.log("# Send key press " + nextAction.key + " with keyCode " + keyCode);
                        page.evaluate(function(keyCode) {
                                var event = {
                                    keyCode: keyCode
                                };
                                event.preventDefault = function(){};
                                KeyHandler.KeyPressed(event);
                            }, keyCode);
                    } else if ( nextAction.action == 'waitForPageChange') {
                        var output = "/tmp/" + profile + ".png";
                        page.render(output);
                    }
                }
            }
        }
    }
}
}


//console.log("Initialized " + ip);

page.open(url, function(status) {page
    console.log("opened "+ ip + " to URL "+url);
    page.evaluate(function(ip, mac, serial, next) {
    ASTB.IpAddress = ip;
    ASTB.MacAddress = mac;
    ASTB.Serial = serial;
    Portal.PageChangeCompleted.AddHandler(function(e) {
        console.log(JSON.stringify({
            command: "PageChangeCompleted",
            page: e.params.page,
            params: e.params.params,
            index: next
        }));
    });
    }, ip, mac, serial, next);
    //console.log("PageChangeCompleted")

});

0 个答案:

没有答案