2016-04-26 54 views
0

我幾天前開始使用PhantomJS與NodeJS。 我正在使用此庫與之集成:https://github.com/amir20/phantomjs-node。 一切都很完美,但是當我試圖在頁面加載(從回調)後繼續我的applcation的流程時,出現了問題。從PhantomJS調用函數onLoadFinished回調

function doStuff() 
{ 
    page.open("http://stackoverflow.com/") 
     .then(function (status) { 
       function responseHandler(status) { 
        console.log("loaded"); 
        iAmHere(); 
        console.log("Here Again"); 
       } 

       function loginAction() { 
        var btn = document.querySelector("#button"); 
        btn.click(); 
       } 

       page.property('onLoadFinished', responseHandler); 
       page.evaluate(loginAction) 
      } 
    ); 
} 


function iAmHere(){ 
    console.log("iAmHere"); 
} 

的#鍵件觸發一些網頁加載時,ResponseHandler所函數被調用,其輸出是:

信息:裝載

和功能iAmHere不會被調用根本沒有任何跟蹤呼叫的日誌。 我做錯了什麼?

謝謝!

回答

3

iAmHere()onLoadFinished事件觸發是因爲您所提供的功能,responseHandler,實際上是由PhantomJS JavaScript引擎執行不被調用,而不是Node.js的原因

因此,它無法訪問您在Node.js腳本中定義的iAmHere()函數。

你可以,而是要當頁面加載完成這樣的通知:

var phantom = require('phantom'); 

var sitepage = null; 
var phInstance = null; 
phantom.create() 
    .then(instance => { 
     phInstance = instance; 
     return instance.createPage(); 
    }) 
    .then(page => { 
     sitepage = page; 
     return page.open('https://stackoverflow.com/'); 
    }) 
    .then(status => { 
     console.log(status); 

     // Page loaded, do something with it 

     return sitepage.property('content'); 
    }) 
    .then(content => { 
     console.log(content); 
     sitepage.close(); 
     phInstance.exit(); 
    }) 
    .catch(error => { 
     console.log(error); 
     phInstance.exit(); 
    }); 
+0

謝謝!爲我工作 – maryum375