问题
In a PhantomJS script, I am trying to load a local JavaScript file that defines an array:
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
I'd expect the myCodes array to be available. Yet I receive
injected codes.js
ReferenceError: Can't find variable: myCodes
回答1:
Found the answer. Had to import the file with phantom.injectJs, not page.injectJs.
filename = './codes.js';
injected = phantom.injectJs(filename);
if (injected) {
console.log('injected codes.js');
console.log('myCodes data:', myCodes);
}
回答2:
I guess you have to export your array in required file, like: exports.myCodes= { whateverinarray };
and then reach it in main file, like injected.myCodes
来源:https://stackoverflow.com/questions/35339217/include-js-file-with-phantomjs