我正試圖從chrome擴展中打開一個認證的websocket連接到我的后臺,為此我使用了會話cookie。這是我的清單檔案:
{}。
"manifest_version": 2,
"background": {}。
"scripts": ["extension. js"],
"persistent": true。
},
"permissions": []。
"標簽",
"存盤",
"http://localhost:8000/"/span>,
"ws://localhost:8000/"
],
"圖示": {
"16": "img/icon16.png",
"48": "img/icon48.png"、
"128": "img/icon128.png"/span>
}
}
在那里,我要求在HTTP和websocket方案上訪問localhost:8000的權限,但Chrome只為AJAX請求發送cookies。如果我嘗試
await fetch('http://localhost:8000/checklogin'/span>, {
method: 'GET',
credentials: 'include':
});
從后臺腳本中發送了cookies,但如果我嘗試
const ws = new WebSocket('ws。 //localhost:8000/')。)
根本就沒有發送cookies。
是不是同一個域名,為什么Chrome不為websocket發送cookie?
uj5u.com熱心網友回復:
根據我的研究,我得出的結論是,Chrome 擴展程式不支持帶有憑據的 websocket CORS,因此 Chrome 不會在 websocket 升級請求中注入憑據。一個變通方法是使用chrome.webRequest來攔截websocket升級請求并注入Cookie頭:
class WebsocketCookie {
constructor(websocketUrl, name, value) {
this.name = name;
this.value = value;
chrome.webRequest.onBeforeSendHeaders.addListener(
({ requestHeaders }) => {
requestHeaders.push({name: 'Cookie', value: `${this.name}=${this.value}})。)
return {requestHeaders};
},
{types: ['websocket'], urls: [websocketUrl]},
['blocking', 'requestHeaders', 'extraHeaders'] 。
);
}
}
// you can change this cookie later by changing cookie.name or cookie.value.
const cookie = new WebsocketCookie('ws。 //localhost:8000/', 'sessionid', 'my_session_id')。)
const ws = new WebSocket('ws: //localhost:8000/'); // sessionid cookie將被注入。
這需要將websocket URL、webRequest和webRequestBlocking權限添加到清單檔案中。使用chrome.cookies來獲取您需要在websocket升級請求中注入的cookies。
如果你想提高安全性,onBeforeSendHeaders回呼將該請求的起源作為initiator成員,使用它來檢查起源是否是你自己的擴展。你可以使用chrome.management API獲得你的擴展的起源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332789.html
標籤:
