节点js + PhantomJs:将数据发送到page.evaluate

时间:2013-12-10 11:41:36

标签: node.js phantomjs

如何从服务器向page.evaluate发送变量?

var test = 'Lorem Ipsum';

phantom = require('phantom')
    phantom.create(function(ph){
        ph.createPage(function(page) {
            page.open("http://www.google.com", function(status) {
            page.evaluate(function(){
               $('body').html(test);
            });
            page.render('google.pdf', function(){

             console.log('Page Rendered');
             ph.exit();
           });
        });
    });
});

提前感谢您的帮助。

Edit1

现在看起来像

var message = function(){
    return {message: 'Hello Word'};
};

phantom = require('phantom')
    phantom.create(function(ph){
        ph.createPage(function(page) {
            page.open("http://www.google.com", function(status) {
            page.evaluate(function(content){
               $('body').html(content);
            }, message);
            page.render('google.pdf', function(){

             console.log('Page Rendered');
             ph.exit();
           });
       });
    });
});

现在我没有任何错误,但我不知道如何处理此对象以在page.evaluate

中使用它

1 个答案:

答案 0 :(得分:1)

尝试

page.evaluate(function (...) {...}, function (err, data){...}, arg1, arg2, ...);

示例:

var message = 'hello world';
page.evaluate(function(content){
    $('body').html(content);
    return 'any data'
}, function (err, anydata) {}, message);

将jquery添加到页面

page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {
    //jQuery Loaded.
    //Wait for a bit if site have AJAX
    setTimeout(function() {
        return page.evaluate(function() {
            // USE JQUERY HERE
            //
            //

            return
        }, function(err, result) {
            console.log(result);
            ph.exit();
        });
    }, 3000);
});

请参阅自述文件: https://github.com/alexscheelmeyer/node-phantom

相关问题