【Chrome扩展程序】利用 background 实现跨域请求
在 Manifest V3 中,后台页面不支持 XMLHttpRequest(由 Service Workers 提供)。请考虑使用其现代替代品 fetch()。
在 Manifest V3 中,后台页面不支持 XMLHttpRequest(由 Service Workers 提供)。请考虑使用其现代替代品 fetch()。
在 background.js 中调用 var xhr = new XMLHttpRequest(); 将会返回下面的错误:
Error in event handler: ReferenceError: XMLHttpRequest is not defined
需要在 content_scripts 中使用 chrome.runtime.sendMessage
function GM_xmlhttpRequest(option){
chrome.runtime.sendMessage({event: "xhr", data:option }, function (res) {
//option.onload(res);
console.log(res);
if (res.event == "xhr" && !res.err){
option.onload(res);
}
});
}在 background.js 中使用:
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.url) {
//console.log(message.url);
chrome.downloads.download({
url: message.url.replace("/mw690/", "/large/"), //"http://d2u2.com/get.php?url=" + encodeURIComponent(message.url)
conflictAction: 'uniquify',
saveAs: false,
headers:[
//{ name:"referer", value: "https://photo.weibo.com/"}
//{ name:"Authorization", value: "Basic dGZzYnVdfssdfzZ29ysdfVFJBVQ=="}
]
});
sendResponse({url:url});
return true;
}
if (message.event == "copy") {
//alert("copy detected");
}
if (message.event == "xhr") {
var option = message.data;
// 监听状态
let fetchOptions = {
method: option.method, // *GET, POST, PUT, DELETE, etc.
// mode: 'no-cors', // no-cors, *cors, same-origin
cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, *same-origin, omit
headers: option.headers,
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer-when-downgrade' // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
};
if (option.method.toUpperCase() !== "GET" && option.method.toUpperCase() !== "HEAD") {
fetchOptions.body = _data;
}
fetch(option.url)
.then(response => response.text())
.then(text => sendResponse({event: "xhr", data:text }))
.catch(error => sendResponse({event: "xhr", err:error }));
return true; // Will respond asynchronously.
}
sendResponse({});
return true;
});本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2022-10-29/1551.html
2022-10-29
0
0


