为了将来参考,任何使用 socket.io-client 并遇到相同问题的人,您可以通过创建一个小型 Web 扩展来解决此问题,然后将其添加到您的浏览器中。您当然必须将此添加为您的应用的安装条件。
在内容脚本和后台脚本中,添加拦截请求事件处理程序。处理程序可以将源头值更新为当前选项卡源源或其他任何内容。
- content-script.js
(async () => {
await browser.runtime.sendMessage({action: "setActiveTabOrigin"})
})();
- background.js
browser.runtime.onMessage.addListener(async (params) => {
if (params.action == "setActiveTabOrigin") {
window.origin = await browser.tabs.query({currentWindow: true})
.then((tabs) => {
for (var tab of tabs) {
if (tab.active) {
const url = new URL(tab.url)
return url.origin
}
}
})
}
});
function rewriteWSHeaders(e) {
for (var header of e.requestHeaders) {
if (header.name.toLowerCase() == "origin") {
if (header.value == "null") {
console.log("!!! Setting request origin to the active tab url origin : ", window.origin)
header.value = window.origin
}
}
}
return {requestHeaders: e.requestHeaders};
}
// For the API details, refer to [mozilla's docs][1]
browser.webRequest.onBeforeSendHeaders.addListener(
rewriteWSHeaders,
{urls:["ws://<socket.io-server.host>/*"], types:["websocket"]},
["blocking", "requestHeaders"]
);
部分网络扩展 manifest.json :
"background": {
"scripts": ["background.js"]
}
"content_scripts": [
{
"matches": ["<remoteHost>/*"],
"js": ["content-script.js"],
"runAt": "document_start"
}
]
"permissions": [
"<all_urls>",
"webRequest",
"webRequestBlocking",
"tabs"
],
其他未解释但很容易查找的先决条件
-
此选项仅在以已知远程主机为目标时有用,因为必须将远程主机添加到“cors allowed origins”列表中,作为 python-socket.io 构造参数传入。
-
网络扩展源也必须传递给这个列表
websock = socketio.AsyncServer(
async_mode='asgi',
logger=logger,
cors_allowed_origins=[extOrigin, <remoteHost>])