Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phantomjs using a local file with page.includeJs?

I am using PhantomJS to screenshot a webpage. However the library calls to a hosted jQuery file to inject jQuery functionality in the page DOM to allow some manipulations. Seen here: http://phantomjs.org/api/webpage/method/include-js.html

The code looks like this:

if ( loaded ) {
page.includeJs("http://code.jquery.com/jquery-1.8.3.min.js", 
  function() { . . .

I don't want to make an external call for JS because (a) it's slower and (b) its not reliable. I would like to use a local copy and I set that path as such but it is NOT loading in.

page.includeJs("assets/javascript/jquery.min.js",
  function() { . . .

What is the problem here? Why is my path not working as I expect it to? Does this function page.includeJs not allow relative paths?

like image 540
MrPizzaFace Avatar asked Oct 19 '14 23:10

MrPizzaFace


1 Answers

According to the documentation this function includes the script from given URL which needs to be accessible from the hosted page. Obviously your local path is not accessible on remote host (relative nor absolute) so you need to inject the script with injectJs instead.

Edit: Here is the code I used for testing:

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

page.open("http://ipecho.net/", function(status) {
    if ( status === "success" ) {
        if (page.injectJs("jquery.min.js")) {
            var h1 = page.evaluate(function() {
                return $("h1:eq(0)").css({fontSize: 10, color: "red"}).text();
            });
            console.log(h1);
        }
    }
    page.render("test.png");
    phantom.exit();
});


The extra code can be also injected the same way as jquery and will work for sure. Remember about evaluate() limitations (but it is not really a big deal in this case):

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!


Edit: Also about your filepath problem: check what is your working directory. Using relative paths can be tricky because of that so I suggest you to use absolute. webpage.libraryPath is all you need. I hope I helped you now.

like image 96
ghost Avatar answered Sep 30 '22 23:09

ghost