yuvi
yuvi

Reputation: 18457

phantomjs - running render after loading the page, but loading never fires

I'm trying to create a graph-to-png converter with phantomjs, but having a hard time getting it to work. Almost every example I see out there uses some external URL as if all you ever do with it is scraping, and the documentation is terribly lacking.

To test out things, I created a very simple d3 function that adds an <svg> tag and a blue circle inside. Looking at other questions on SO and examples, I hooked it to onLoadFinish but that event never triggers.

I'm guessing I need to open the page, but open only uses a url, which isn't relevant for me (and again, the docs are completely lacking in information. Even when I see something I think might be relevant, my only choice is guesswork. This is ridiculous )

Here's my code:

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

var content = '<html>';
content += '<body>';
content += '<h1> test title </h1>';
content += '<div id="graph">';
content += '</div>';
content += '</body></html>';    

page.content = content; 

page.injectJs('lib/d3/d3.min.js');
page.onLoadFinish = function(status) {
    console.log('loading finished'); // this never happens!
    var svg = d3.select('#graph')
                .append('svg')
                .attr({'width': 100, 'height': 100});   

    var circle = svg
        .append('circle')
        .attr({ 'cx': 10, 'cy': 10, 'r': 10, 'fill': 'blue' });   

    page.render('test.png');
    phantom.exit();
};

Any suggestions?

Upvotes: 1

Views: 623

Answers (1)

yuvi
yuvi

Reputation: 18457

It's evaluate. That was the function I was looking for. It "evaluates the given function in the context of the web page".

Finally, it's working:

page.content = content; 
page.injectJs('lib/d3/d3.min.js');
page.evaluate(function() {
    var svg = d3.select('#graph')
                .append('svg')
                .attr({'width': 100, 'height': 100});   

    var circle = svg
        .append('circle')
        .attr({ 'cx': 10, 'cy': 10, 'r': 10, 'fill': 'blue' });   

    page.render('test.png');
    phantom.exit();
};

Upvotes: 1

Related Questions