chrome-extensions-samples
chrome-extensions-samples copied to clipboard
MV3 declarativeNetRequest how to redirect to a url create by "createObjectURL"
how can I use declarativeNetRequest to redirect to a url create by "createObjectURL"?
I try to make an extension to mock json data for some axios.get api.I use the code below to insert a function into page and form a url like "blob:http://xxxx/xxxx'
//in popup.js
const generateUrl=()=>{
const o = { name: 'test', age: '18' }
const s = JSON.stringify(o);
const b = new Blob([s], { type: 'application/json' })
const u = window.URL.createObjectURL(b);
chrome.runtime.sendMessage({type:'ENABLE_PROXY', data: u }, (response) => {});
}
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: generateUrl
})
then I update rules in background.js
//in background.js
const updateRules = (proxyUrl) => {
const rules = {
removeRuleIds: [1, 2],
addRules: [
{
id: 1,
priority: 1,
condition: {
urlFilter: 'your_origin_url_info',
resourceTypes: ["xmlhttprequest"],
},
action: {
type: "redirect",
"redirect": { "url": proxyUrl }
}
}
]
};
chrome.declarativeNetRequest.updateDynamicRules(rules, () => {
chrome.declarativeNetRequest.getDynamicRules(rules => console.log(rules))
})
}
//listen to msg and upgrade rules
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
console.log(msg)
const {type,data}=msg;
updateRules(data)
return true;
})
however it doesn't make sense——I original use 'axios.get('http://127.0.0.1:8881') in a react-app,and it dose redirect the url create by 'createObjectURL' but can't recieve response correctly.
then I tried to send a xhr in chrome-dev-console,it recieved the json object
then I try to modify requestHead and responseHead by declarativeNetRequest,also can't solve this problem.
I notice in blog https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-ModifyHeaderInfo it says that
I 'm not sure whether that means it is not support to run like my code
how can I use declarativeNetRequest to redirect to a url create by "createObjectURL"?
If you open a URL in the extension you can use onfetch
to catch the Request
and serve a Response
with respondWith()
.