Include js file with PhantomJS

本秂侑毒 提交于 2019-12-02 04:33:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!