Phantomjs uses local file with page.includeJs?

I am using PhantomJS to take a screenshot of a webpage. However, the library accesses the hosted jQuery file to add jQuery functionality to the DOM page to allow some manipulation. Saw here: http://phantomjs.org/api/webpage/method/include-js.html

The code is as follows:

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

I do not want to make an external call for JS, because (a) it is slower and (b) its unreliable. I would like to use a local copy, and I set this path as such, but it does NOT load.

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

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

+6
source share
1 answer

According to the documentation, this function includes a script from the given URL, which should be accessible from the hosted page. Obviously, your local path is not available on the remote host (relative or absolute), so you need to enter injectJs script.

Change 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(); }); 


Extra code can also be entered in the same way as jquery, and will work just fine. Remember the limitations of evaluate() (but in this case it is not very important):

Note: The arguments and return value of the evaluation function should be a simple primitive object. Rule of thumb: if it can be serialized via JSON, then that's fine.

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


Change Also about your problem with file files: check what is your working directory . Because of this, using relative paths can be tricky, so I suggest you use absolute. webpage.libraryPath is all you need. I hope now I have helped you.

+3
source

Source: https://habr.com/ru/post/976951/


All Articles