Tamlyn
Tamlyn

Reputation: 23564

PhantomJS: setContent not working when HTML has assets

This script works:

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

var html = '<h1>Test</h1><img>'; //works with page.setContent and page.content
//var html = '<h1>Test</h1><img src=".">'; //only works with page.content

page.setContent(html, 'http://github.com');
//page.content = html;

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

but adding a src attribute to the img makes it fail silently (page.render returns false and no image is generated).

Setting page.content directly works in both cases but then relative URLs don't. The same thing happens with other tags that load a resource such as link. It doesn't matter whether the linked resource exists or not. Tested in 1.8.1 and 1.9.2.

Is this a bug or have I misunderstood the API?

Upvotes: 5

Views: 3147

Answers (1)

Kashyap Prajapati
Kashyap Prajapati

Reputation: 442

You can not render webpage if it is not fully loaded.

When you are setting link or src to <img>, It will try to load image asynchronously. So, it requires to wait for loading finished.

Try following code.

page.onLoadFinished = function(status) {
    page.render('test.png');
    phantom.exit();
};
page.setContent(html, 'http://github.com');

Upvotes: 4

Related Questions