0

I have started working in a small proof of concept which is using PhantomJS to take screenshots and I'll get all the necessary configurations as system arguments such as URL, timeout, isScreenshotReqd, isHarFileReqd, isHeadersReqd, username, password and some application related configs. Everything is working fine except customHeaders.

code I used is

if (system.args.length === 1) {
    console.log('Usage: phantom.js <some URL>');
    phantom.exit(1);
} else {
    assembleId = system.args[2];
    page.address = system.args[3];
    page.settings.resourceTimeout = system.args[4];
    isScreenshotReqd = system.args[5];
    isHeadersReqd = system.args[6];
    isHarFileReqd = system.args[7];
    page.settings.userName = system.args[8];
    page.settings.password = system.args[9];
    var key = "headerKey";//(or system.args[10])
    var value = "headerValue";//(or system.args[11])
    page.customHeaders = {key : value};
   //some operation
}

this sets the customHeader as

"headers": [{"name": "key","value": "headerValue"}]

You can see the value is set correctly but the key is not taken from initialized variable or system.args[x] instead it takes whatever variable I use.

though it works if I hardcode the customHeaders like

page.customHeaders = {"headerKey": "headerValue"};

gives expected output but the problem is I'll be having dynamic headers for various URLs. It means it's config driven and each customer will give different headers for each URL.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Zyber
  • 428
  • 4
  • 21
  • Its not a duplicate, In the context of phantomJs the solution from the link is not working, kindly check for yourself and enlighten me if I m wrong. – Zyber May 27 '16 at 05:20
  • Does `page.customHeaders = {}; page.customHeaders[key] = value;` work? – Artjom B. May 27 '16 at 15:10
  • page.customHeaders = {}; works but page.customHeaders[key] = value; does not work. – Zyber May 30 '16 at 05:11

1 Answers1

2

JavaScript does not permit the use of variables as object keys. You will have to set a variable key in this way:

var key = "some dynamic key";
var value = "some value"
var obj = {};
obj[key] = value;

The additional problem with PhantomJS' customHeaders is that it needs to be set as a whole. PhantomJS doesn't notice that the properties of the customHeaders object have changed. You can use it like this:

var key = "headerKey";
var value = "headerValue";
var customHeaders = {};
customHeaders[key] = value;
page.customHeaders = customHeaders;
Artjom B.
  • 61,146
  • 24
  • 125
  • 222