【问题标题】:Calling a function from PhantomJS onLoadFinished callback从 PhantomJS onLoadFinished 回调调用函数
【发布时间】:2016-08-19 21:55:01
【问题描述】:

几天前我开始使用 PhantomJS 和 NodeJS。 我正在使用这个库来集成它:https://github.com/amir20/phantomjs-node。 一切都很完美,但是当我尝试在页面加载(来自回调)后继续我的应用程序时出现问题。

function doStuff ()
{
    page.open("http://stackoverflow.com/")
        .then(function (status) {
                function responseHandler(status) {
                    console.log("loaded");
                    iAmHere();
                    console.log("Here Again");
                }

                function loginAction() {
                    var btn = document.querySelector("#button");
                    btn.click();
                }

                page.property('onLoadFinished', responseHandler);
                page.evaluate(loginAction)
            }
    );
}


function iAmHere (){
    console.log("iAmHere");
}

#button 元素触发了一些页面加载,调用了 responseHandler 函数,输出为:

信息:已加载

并且函数 iAmHere 根本没有被调用,调用之后的日志也没有。 我做错了什么?

谢谢!

【问题讨论】:

    标签: javascript node.js phantomjs browser-automation


    【解决方案1】:

    iAmHere()onLoadFinished 事件触发时未被调用的原因是您提供的函数responseHandler 实际上是由PhantomJS JavaScript 引擎 执行的,并且不是 Node.js。

    因此,它无法访问您在 Node.js 脚本中定义的 iAmHere() 函数。

    您可以在页面完成加载时收到通知,如下所示:

    var phantom = require('phantom');
    
    var sitepage = null;
    var phInstance = null;
    phantom.create()
        .then(instance => {
            phInstance = instance;
            return instance.createPage();
        })
        .then(page => {
            sitepage = page;
            return page.open('https://stackoverflow.com/');
        })
        .then(status => {
            console.log(status);
    
            // Page loaded, do something with it
    
            return sitepage.property('content');
        })
        .then(content => {
            console.log(content);
            sitepage.close();
            phInstance.exit();
        })
        .catch(error => {
            console.log(error);
            phInstance.exit();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多