PhantomJs: Can I access relative assets from a page with dynamically set content?

javascript, phantomjs, relative-path

Solution

There is an issue about this on GitHub. It seems that there is no option to pass the base directory to PhantomJS. However, you can set the base url with the HTML base tag.

Problem

Given the following file structure: ``` project-folder |- images/ | |- foo.png | |- script.js ``` And something like the following Phantom script: ``` var page1 = require("webpage").create(), page2 = require("webpage").create(); page1.content = "<img src='images/foo.png'/>"; page2.content = "<img src='file:///path/to/project-folder/images/foo.png'/>"; // give the images some time to load setTimeout(function () { page1.render("pdf1.pdf"); page2.render("pdf2.pdf"); phantom.exit(); }, 10); ``` After running this, `foo.png` displays correctly in `pdf2.pdf` but not in `pdf1.pdf`. I need to render a large HTML file that has a number of images with relative paths, as in page1. While it's possible to go through the markup using some kind of crazy regex and change all the image src attributes manually to the script's working folder before setting the content, I'd rather avoid it. Is there some other option I'm missing?

Original source