javascript - PhantomJS page.injectJs doesn't work -


i'm trying write page source code text file url. works well, want additionally inject javascript file. problem file not include properly. last pages loaded, others incomplete.

//phantomjs c:\phantomjs\script\test1.js  var fs = require('fs'); var numeroepisode = 0; var maxepisode = 10; var fichierlien = fs.read('c:\\phantomjs\\fichier\\lien.txt'); var listelien = fichierlien.split(/[\n]/);  var page = require('webpage').create();  function getpage() {     if (numeroepisode > maxepisode)      {          phantom.exit();     }     page.open(listelien[numeroepisode], function(status)     {         if(status !== 'success')         {             console.log('impossible de charger la page.');         }         else         {             console.log('url: '+listelien[numeroepisode]+'');             page.injectjs('http://mylink.com', function() { });             var path = 'c:\\phantomjs\\fichier\\episode_'+numeroepisode+'.html';             fs.write(path, page.content, 'w');             settimeout(getpage, 15000); // run again in 15 seconds             numeroepisode++;         }        }); } getpage(); 

don't mix page.injectjs() , page.includejs().

injectjs(filename): loads local javascript file page , evaluates synchronously.

includejs(url, callback): loads remote javascript file specified url , evaluates it. since has request remote resource, done asynchronously. passed callback called operation finished. if don't use callback, code run before remote javascript included. use callback:

page.includejs('http://mylink.com', function() {     var path = 'c:\\phantomjs\\fichier\\episode_'+numeroepisode+'.html';     fs.write(path, page.content, 'w');     numeroepisode++;     settimeout(getpage, 15000); // run again in 15 seconds }); 

since javascript load changes on page, need load after pages script have run. if javascript heavy page, need wait little. can wait static amount of time:

settimeout(function(){     page.includejs('http://mylink.com', function() {         //...     }); }, 5000); // 5 seconds 

or utilize waitfor wait until element appears denotes page loaded. can tricky sometimes.


if still want use injectjs() instead of includejs() (for example because of synchronous nature), need download external javascript file machine , can use injectjs().


Comments