Include js file with PhantomJS

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

Answers:

Answer

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);
}
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.