I'm working on my first extension for Google Chrome. I want to add a custom header to (all) http(s) requests based on options that the user can select on the options page of my extension.
I managed the following successfully:
- Manually add custom headers to all http requests
- Create an options page
- Save and restore options in chrome.storage.sync
Now I'm struggling to combine the above. Here's what I tried:
chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
var demoOptions = new Array();
var demoHeader = '';
var bkg = chrome.extension.getBackgroundPage(); // for debugging
chrome.storage.sync.get({
demoOption: true,
}, function(items) {
if(items.demoOption){
demoOptions.push('demo-header-1');
}
demoHeader = demoOptions.join();
details.requestHeaders.push({
name: 'X-Demo-Header',
value: demoHeader //this is not showing up in the http headers
});
bkg.console.log('demoHeader:' + demoHeader); //this is putting the correct value to the debugging console
bkg.console.log(details.requestHeaders); //this is putting the headers to the debugging console, incl. x-demo-header1 and x-demo-header2 (see below)
});
details.requestHeaders.push({
name: 'X-Demo-Header2',
value: 'Demo-Header-2' //this is correctly added to the headers and included in the request
});
return { requestHeaders: details.requestHeaders };
},
{urls: [ "*://*/*" ]},['requestHeaders','blocking']);
Observations:
- X-Demo-Header2 is correctly inserted (visible in Chrome header inspection and n the debigging console)
- x-demo-header1 is not part of the header sent to the site, but it is visible in the debugging output
- x-demo-header2 is in the header before X-Demo-Header1 in the header array in the console (see screenshot)
Assumption: function(items) to fetch my options is executed asynchronyously and requestHeaders are returned before the headers from my options are inserted.
Can I avoid this? Is there a better option to add headers based on options?
Screenshot:
