'Origin is changed in Chrome Extension Service Worker Fetch Request
Hi I am developing chrome extension for social media marketing. I am using fetch in service_worker to send a request on facebook but but it is not working for me.
When I copy this request as fetch Request from network requests then paste it on facebook page, it works perfectly.
The difference is that origin-header is overridden in while sending this request in service-worker thats why it doesn't work for me.
I am using this code to change the headers but this is also not working for me.
await chrome.webRequest.onBeforeSendHeaders.addListener(
(details) => {
let { requestHeaders } = details;
const headerList = {};
for (let i = 0; i < requestHeaders.length; i += 1) {
if (requestHeaders[i].name === 'Origin') {
requestHeaders[i].value = 'https://m.facebook.com';
break;
}
}
headerList.requestHeaders = requestHeaders;
return headerList;
}, { urls: ["<all_urls>"] }, ["requestHeaders", "extraHeaders"])
Can you please elaborate how should I use webRequest.onbeforeSendHeaders to change headers. If I have to use declarativeNetRequest, how should I use it.
I am using Manivest Version 3 BTW.
Solution 1:[1]
I used chrome.declarativeNetRequest.updateDynamicRules to override the headers
Here is the code.
await chrome.declarativeNetRequest.updateDynamicRules(
{
addRules: [{
"id": 1,
"priority": 1,
"action": {
type: 'modifyHeaders',
requestHeaders: [
{ header: 'origin', operation: 'set', value: "https://www.facebook.com" }
],
},
"condition": { "urlFilter": "facebook.com", "resourceTypes": ["xmlhttprequest"] }
}
],
removeRuleIds: [1]
},
)
You also have to provide permissions to use declarativeNetRequest in manifest.json
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Muhammad Yasir |