سؤال

I just ran into something new today. I wanted to use phantomjs in node and was setting up phantom npm module npm link. The question lies in how you get "document.title". Please take a look at the example code they have on the site.

How did they get document injected into the callback function? Normally it would have been passed as a parameter in the callback, but somehow document is available without it being passed through the callback parameters.

Can someone explain how this is done? Also an explanation to why someone would do this and not just pass through the parameter?

var phantom;

phantom = require('phantom');

phantom.create(function(ph) {
  return ph.createPage(function(page) {
    return page.open("http://www.google.com", function(status) {
      console.log("opened google? ", status);
      return page.evaluate((function() {
        return document.title;
      }), function(result) {
        console.log('Page title is ' + result);
        return ph.exit();
      });
    });
  });
});
هل كانت مفيدة؟

المحلول

Perhaps as explained in this question and answer, PhantomJS has a special feature where it puts (creates) the window and document objects in the global scope.

Generally this is done by assigning something to a variable without using the var keyword.

Example

var test = function(cb){
    document = 'test';
    cb();
}

test( function(){
    console.log(document);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top