I want to redirect request to a data-url.
// background.js
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
const url = details.url
if(url == 'http://www.example.com') {
return {
redirectUrl: 'data:application/json; charset=utf-8,' + JSON.stringify({"a":1, "b": 2})
}
}
return {cancel: false}
},
{urls: ["<all_urls>"]},
["blocking"]
)
Now, I start a ajax in a page:
var xhr = new XMLHttpRequest()
// xhr.withCredentials = true
xhr.open('GET', 'http://www.example.com', true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status == 200) {
console.log(xhr.responseText)
}
}
}
It show's {"a":1, "b": 2}.
But, If I add withCredentials, it's error:
images content:
Fetch API cannot load data:application/json; charset=utf-8,{"a":1,"b":2}. The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. (index):1 Uncaught (in promise) TypeError: Failed to fetch
How to fix it?
I tried add Access-Control-Allow-Credentials header in onHeadersReceived, but it's no effect.
chrome.webRequest.onHeadersReceived.addListener(
function (details) {
if(details.url == 'http://www.example.com') {
details.responseHeaders.forEach(header => {
if(header.name == 'Access-Control-Allow-Origin') {
header.value = 'null'
}
})
details.responseHeaders.push({
name: 'Access-Control-Allow-Credentials',
value: 'true'
})
}
return {responseHeaders:details.responseHeaders};
},
{urls: ["<all_urls>"]},
["responseHeaders","blocking"]
)
