QPTR QPTR - 1 year ago 156
Javascript Question

Unable to create an object of objects within phantomjs

I am using

to write a script which extracts some features of the requests and responses of a webpage. I have adaped the script from
example over here and the
example referenced in the page. To match the request with its particular response, I create an object of objects called page.resources indexed by means of the urls. The trouble is that the object is not being set in my code. My code is copy/pasted below.

Over here I first create a
object, and then on each call to
, I insert an object with certain attributes. When I try to access just after this inner object has been created, I am unable to do this. Also, when I try to access the same object in
I get no output. Could anyone please help? I have tried to debug this using
at different places of the code but I can't really figure out what could be going wrong.

"use strict";

var page = require('webpage').create(),
system = require('system'),

if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
} else {

address = system.args[1];
page.resources = {}
page.redirectedURLs = {}

page.onResourceRequested = function (req) {
console.log("Resource requested: " + req.url)

page.resources[req.url] = {

url: url,
redirected: null, //will be set in response
redirectedURL: null, //will be set in response
HSTS: null,
maxage: null,
includeSubdomains: null

//Can't access the object over here
console.log("accesing page resources" + page.resources[req.url].url);


page.onResourceReceived = function (res) {
//Can't access the object over here either
for (var key in page.resources) {
if (pageresources.hasOwnProperty(key)) {
console.log(key + " -> " + page.resources[key].url);

page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');


page.onLoadFinished = function(response) {



Answer Source

You have a typo:

page.resources[req.url] = {
        url: req.url, // was just "url" which was undefined
        redirected: null, 
        redirectedURL: null,
        HSTS: null,
        maxage: null,
        includeSubdomains: null
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download