【Chrome扩展程序】利用 background 实现跨域请求
微wx笑
2022-10-29【前端开发】
305
0
0关键字:
在 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
1 2 3 4 5 6 7 8 9 | 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 中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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