user1930254
user1930254

Reputation: 1321

Getting the title of the page in PhantomJS

I'm experimenting with PhantomJS. Here is a simple code which does not work as expected. After running it I can see in the console success and foo but the document's title is an empty string.

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

page.open('https://www.google.com', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    console.log("foo");
    console.log(document.title);
    phantom.exit();
  }
});

Upvotes: 1

Views: 788

Answers (1)

Artjom B.
Artjom B.

Reputation: 61932

The easy way to get the title is to use page.title.

The reason document.title doesn't give you anything is because PhantomJS has two distinct contexts. Only the page context (inside of page.evaluate()) has access to the DOM and therefore the document object. The outer context also has a document object, but it doesn't do anything and is therefore only a dummy object. The same goes for window.

So the other way to get the page title is to use:

console.log(page.evaluate(function(){
    return document.title;
}));

Upvotes: 4

Related Questions