Reputation: 544
How to pass the variable from outside to onResourceRequested
function?
I am not able to access the variable testvar
inside the callback function of onResourceRequested
property.
Any idea how to fix this issue?
Below is the sample code I used for testing
var phantom = require("phantom");
var _ph, _page, _outObj;
phantom.create().then(function(ph){
_ph = ph;
return _ph.createPage();
}).then(function(page){
_page = page;
var testvar = "WHY THIS IS NOT PRINTING";
_page.property('onResourceRequested', function (req, networkRequest) {
console.log("THIS LINE WORKS");
console.log(testvar); // THIS DOESNT WORK
});
_page.property('onResourceReceived', function (res) {
//console.log('received: ' + JSON.stringify(res, undefined, 4));
});
return _page.open('https://www.ammaus.com/', function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
_ph.exit();
});
}).then(function(status){
console.log(status);
return _page.property('content')
}).then(function(content){
_page.close();
_ph.exit();
}).catch(function(e){
console.log(e);
});
Upvotes: 0
Views: 35
Reputation: 359
Use arrow function (ES6) like this:
_page.property('onResourceRequested', (req, networkRequest) => {
console.log("THIS LINE WORKS");
console.log(testvar); // THIS DOESNT WORK
});
An arrow function does not newly define its own this
when it's being executed in the global context; instead, the this
value of the enclosing execution context is used, equivalent to treating this as closure value.
Upvotes: 1