Consume Google Feed API with Phantomjs

580 views Asked by At

I am trying to translate this example of the google feeds api to work with Phantomjs. Following an example from Phantomjs I have the following:

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

page.onConsoleMessage = function(msg) {
    console.log(msg);
};

// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
  if (!result.error) {
    // Loop through the feeds, putting the titles onto the page.
    // Check out the result object for a list of properties returned in each entry.
    // http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON
    for (var i = 0; i < result.feed.entries.length; i++) {
      var entry = result.feed.entries[i];
      console.log(entry.title);
    }
  }
}


page.includeJs("http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0", function() {
    google.load("feeds", "1");
    var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
    feed.includeHistoricalEntries(); // tell the API we want to have old entries too
    feed.setNumEntries(250); // we want a maximum of 250 entries, if they exist

    // Calling load sends the request off.  It requires a callback function.
    feed.load(feedLoaded);

phantom.exit();
});

The output says:

ReferenceError: Can't find variable: google

I have tried defining var google; right after the include but no luck. I am new to Phantomjs and js in general. Any pointers much appreciated.

1

There are 1 answers

2
Detro On

So, there is an issue in the way you are using the callback from "includeJs".

That function you are assuming is executed in the context of the page: it's not. It's executed in the main context.

You have injected a library in a page: fine. Now, I suppose, you want to do "Stuff" within that page. You have to use the function:

page.evaluate(function, arg1, arg2, ...);

Also, I see that you want to receive the result of:

feed.load()

In a callback. That is fine, but you need to bridge the gap: a callback in the page context can't be called in the phantom context (yet!). You need to read a bit the doc and see how you want to come up with your solution.

Bare in mind: calls to

page.evaluate()

can return JSON and other JS simple types (strings, numbers, booleans): that should be your "door".