SimonD
SimonD

Reputation: 1547

Phantom is not working with JQuery

I'm trying a very simple example with Phantom + JQuery: I want to display a 'Top Questions' label of stackoverflow.com page in console. Here is my testphantom.js script:

var page = require('webpage').create();  
page.open('http://stackoverflow.com/', function() {
  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", function() {  
    page.evaluate(function() {
      var txt = $('#h-top-questions').text();    
      console.log('TEXT: ' + txt);    
    });
    phantom.exit();
  });
});

But it displays nothing:

>phantomjs testphantom.js
>

What's wrong here?

Upvotes: 0

Views: 851

Answers (2)

baljeet singh
baljeet singh

Reputation: 1

Your code does not work because you are trying to log a message from web page on phantom object while web page has no access to phantom object , let's take an example : you are developer of a browser and on your browser some web pages are running now imagine what will happen if a user running a web page have access to object of your browser. He can now control each and every thing. So that's why execution of web page and phantom object is sandboxed. Note : phantomjs is a headless browser.

See this : http://phantomjs.org/api/webpage/method/evaluate.html

Upvotes: 0

jantimon
jantimon

Reputation: 38142

You are logging the text in the browser context but actually you want to call console.log in the phantomjs context:

var page = require('webpage').create();  
page.open('http://stackoverflow.com/', function() {
  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", function() {  

    // Get the text value
    var txt = page.evaluate(function() {
      // Browser context
      return jQuery('#h-top-questions').text();   
    });

    // Log the text - phantomJS context
    console.log('TEXT: ' + txt);    

    phantom.exit();
  });
});

Upvotes: 2

Related Questions