Search code examples
javascriptnode.jsphantomjsrect

phantom-node not passing return value from page.evaluate function


I am trying to extract a specific element of a webpage, and save it as an image locally.

node.js code, using phantom-node:

var phantom = require('phantom');

phantom.create().then(function(ph) {

  ph.createPage().then(function(page) {

    page.property('viewportSize', {width: 1600, height: 900});
    page.open('http://stackoverflow.com/questions/37570827/saving-element-of-webpage-as-an-image-using-js').then(function(status) {

        if (status == 'success') {
            page.evaluate(function() {
                return document.getElementById("sidebar").getBoundingClientRect(); 

            }).then(function(rect){
                console.log(rect);
                page.property('clipRect', rect);
                page.render("question2.png"); 
            });   
        }
        page.close();
        ph.exit();
    });
  });
});

console.log(rect) prints different values every time I run it. I don't see why that would be the case, but either way, I guess my return statement of the sidebar bounding rect isn't working. Is there something wrong with the code?

Edit: actually, after further debugging, it seems that the rect is being returned properly, but not being set to clipRect..


Solution

  • The problem was that the page.render call did not have enough time to finish before page.close() occurred.

    This code solves the problem:

    var phantom = require('phantom');
    
    phantom.create().then(function(ph) {
    
        ph.createPage().then(function(page) {
    
            page.open('http://stackoverflow.com/questions/37570827/saving-element-of-webpage-as-an-image-using-js').then(function(status) {
    
                if (status == 'success') {
                    page.evaluate(function() {
                        return document.getElementById("sidebar").getBoundingClientRect();
                    }).then(function(rect){
                        page.property('clipRect', rect);
                        page.render("question.png").then(function(){
                            page.close();
                            ph.exit();
                        });
                    });
                }
            });
        });
    });