Can not evaluate jquery function in phantomjs

2019-09-02 19:45发布

问题:

I'd like to build a phantomjs broker service which embed with jquery and accept url and javascript code.

I write a example work well:

var webPage = require('webpage');
var page = webPage.create();

page.onInitialized = function() {
    page.injectJs('js_lib/jquery.min.js');
    // page.includeJs('http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js');
    console.log('running document-start script.');
};

page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        // var title = page.evaluateJavaScript('$(title).text()');
        var title = page.evaluate(function() {
            return $("title").text();
        });
        console.log(title);
    }
    phantom.exit();
});

To achieve my purpose, need to use page.evaluateJavaScript('$("title").text()'); Because I'd like to pass {'url':somesite.com, 'js':'$("title").text()'} to this service.

Then I switch code to page.evaluateJavaScript:

page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        var title = page.evaluateJavaScript('$("title").text()');
        console.log(title);
    }
    phantom.exit();
});

got:

$ phantomjs test.js
running document-start script.
ReferenceError: Can't find variable: title

  phantomjs://webpage.evaluate():1 in global code
  :0 in evaluateJavaScript
  test.js:20
  :285 in _onPageOpenFinished
null

回答1:

I solve it!

Don't write as page.evaluateJavaScript('$(title).text()');

Need use function {} to wrap the code.

var webPage = require('webpage');
var page = webPage.create();

page.onInitialized = function() {
    page.injectJs('js_lib/jquery.min.js');
    // page.includeJs('http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js');
    console.log('running document-start script.');
};


page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        var title = page.evaluateJavaScript('function() { return $("title").text();}');
        console.log(title);
    }
    phantom.exit();
});