jack
jack

Reputation: 11

loading DOM using phantomjs

My html webpage has javascript that loads and applies stylesheets dynamically. All the content and rendering happens inside a div tag. This is not loading the contents of the div tag, which has the id = 'tagid'. Do you know what is wrong here? I am using jquery function to ensure that the page is loaded. But is seems page.evaluate is not even called.

I am writing unit tests using phantomjs. New to the phantomjs. Refer to the code snippet below.

page.open(address, function(status){
    console.log('status '+status)
    if(status=='success'){
        console.log('inside status if ')
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
            console.log('after include js ')
            page.evaluate(function(){
                console.log('inside evlaute ')
                $(window).load(function(){
                    console.log(document.getElementById("tagid").innerHTML)

                });
            });

            setTimeout(function(){phantom.exit()},18000)
        })
    }
})

Upvotes: 1

Views: 2217

Answers (2)

austin665
austin665

Reputation: 91

You could try by giving some timeout before you call evaluate.

window.setTimeout(function () {
    page.evaluate(function() {
         console.log(document.getElementById("tagid").innerHTML)
    });
}, 1000 // adjust the time here

To check what content is being rendered in phantomjs, you can use page.content and check there if your "tagid" element is indeed present.

Upvotes: 0

ngasull
ngasull

Reputation: 4216

Your code is correct, but the console.log call does not have any effect by default as it happens in the PhantomJS page's context.

You can either use the return value of the evaluate call as follows:

page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
  console.log('after include js ')
  var tagid = page.evaluate(function(){
    console.log('inside evlaute ')
    return document.getElementById("tagid").innerHTML;
  });

  console.log('Got tag ID: ' + tagId)
  setTimeout(function(){phantom.exit()},18000)
})

Or you can choose to display messages that are logged in the page by using onConsoleMessage (more complicated setup):

page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('PAGE CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

An important note is that PhantomJS and page's context are separate: inside evaluate calls, you can't access variables from outside. In fact, under the hood, the callback given to evaluate is converted to a string before being given to the page. This is a very confusing part of PhantomJS that must be considered.

Upvotes: 1

Related Questions