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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With