2016-02-11 129 views
1

在PhantomJS腳本文件,我試圖加載定義陣列的本地JavaScript文件:包括JS與PhantomJS

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

injected = page.injectJs('./codes.js'); 
if (injected) { 
    console.log('injected codes.js'); 
    console.log(myCodes); 
} 
phantom.exit(); 

codes.js

myCodes = new Array(); 
myCodes[0] = { "stuff": "here" }; 
// more like this 

我會希望myCodes數組可用。 然而,我收到

injected codes.js

ReferenceError: Can't find variable: myCodes

回答

0

我想你有你的陣列導出所需的文件,如:exports.myCodes= { whateverinarray };,然後在主文件達到它,就像injected.myCodes

5

找到了答案。必須使用phantom.injectJs導入文件,而不是page.injectJs。

filename = './codes.js'; 
injected = phantom.injectJs(filename); 
if (injected) { 
    console.log('injected codes.js'); 
    console.log('myCodes data:', myCodes); 
}