I'm trying to have webRequest as an optional permission in my Google Chrome extension. So I want the backgorund script to only listen for webRequest events if that permission is given.
Trying to achieve that through this code:
chrome.permissions.contains({
origins: ["https://www.freelancer.com/projects/fileshare/*",
"https://freelancer-filestorage-pmb.s3.amazonaws.com/*"],
permissions: ["webRequest",
"webRequestBlocking"]
}, response => {
// only register the webRequest listener if there is this permission...
// I don't know if this is a valid way of doing this, but I don't have other ideas
if (response) {
chrome.webRequest.onHeadersReceived.addListener(details => {
console.log("went through the request");
return {responseHeaders: details.responseHeaders};
},
{ urls: ['https://freelancer-filestorage-pmb.s3.amazonaws.com/*'] },
['blocking', 'responseHeaders']
);
}
});
This does not seem to work, i.e. even when I give the permission, web requests are not intercepted.
I remember reading something in the documentation that adding an event listener inside of an asynchronous function (like I'm doing here) will not work properly. But how can I achieve what I need, then? Do not register listeners asynchronously, as they will not be properly triggered.
If I just put
chrome.webRequest.onHeadersReceived.addListener
in the background script, without checking for the permission, then I will get an error that webRequest is not defined.
EDIT: pasted more of the code
EDIT2: The chrome developer docs at https://developer.chrome.com/extensions/background_pages say this:
Do not register listeners asynchronously, as they will not be properly triggered.
I fixed my problem by setting up a message listener in the background script, which adds and removes a listener for webRequest, depending on whether the user set the permission or revoked it.
Something strange is still happening in about 5% of the cases, where after the permission is granted, for a while it still appears as non-granted and registering the listener fails.