開發環境下用來自動獲取 cookie 的 chrome 插件。
輸入源站點和目標站點以及 cookieName,便可以自動獲取和監聽 cookie 的變化並實時更新。
A chrome plug-in used to automatically obtain cookies in the development environment. By entering the source site, target site and cookie name, you can automatically obtain and monitor the changes of cookies and update them in real time.
使用方法
- clone 本倉庫
git clone https://github.com/aMiing/chrome-extension-cookie.git
cd chrome-extension-cookie
npm install
npm run build
- 打包
- 打開 chrome 擴展程序設置
- 右上角打開開發模式
- 加載已解壓擴展程序(如果是 crx 壓縮文件,直接將文件拖入該設置界面)
- 瀏覽器右上角點擊擴展程序圖標,在彈出窗口中填入您需要設置的信息
cookieName: cookie 名稱; from: 源站點; to: 目標站點;
實現原理
chrome-extension
可以聲明權限並在擴展中使用相關權限的 api。 查看中文文檔
具體實現細節如下:
聲明permissions
在全局配置文件中聲明要使用的權限
// mainifest.json
"permissions": ["storage", "*://*/", "cookies"],
瀏覽器行為
- 配置瀏覽器行為
default_popup
是瀏覽器中點擊該擴展圖標需要展示的彈出頁面。
// mainifest.json
"browser_action": {
"default_icon": "sources/icon128.png",
"default_title": "解決Chrome瀏覽器Cookie跨域攜帶問題",
"default_popup": "index.html"
},
我們要在彈出頁面里面輸入相關的配置項,所以此處配置是必要的。 2. 彈出頁面
我們可以在彈出頁面中配置 cookieName: cookie 名稱; from: 源站點; to: 目標站點;
其核心邏輯就是添加和刪除時候,觸發修改 localstorage。
localStorage.setItem("domainList", JSON.stringify(domainList));
背景頁
- 配置背景頁
背景頁中可以使用在清單文件里面聲明的權限
// mainifest.json
"background": {
"scripts": ["background.js"],
"persistent": true
},
- 背景頁
- 首先是監聽
localStorage
的變化,觸發對 cookie 的修改邏輯
window.addEventListener("storage", ({ key, newValue, oldValue }) => {
if (key === "domainList") {
// 比較變化的數據,判斷是增添或者刪除
newValue = JSON.parse(newValue) || [];
oldValue = JSON.parse(oldValue) || [];
storageList = newValue;
if (newValue.length > oldValue.length) {
// 新增,最后一條為新增,僅取最后一條
init(newValue.slice(-1));
} else {
// 移除cookie
const deleteValue = oldValue.find(e => !newValue.some(n => n === e));
console.log("deleteValue", deleteValue);
chrome.cookies.remove({
url: "https://" + deleteValue.to,
name: deleteValue.name,
});
}
}
});
- 當配置了監聽的 cookie 發生變化后,相對應的
to
domain 的 cookie 也要跟隨變化 - 上面一步我們保存了變化后的
storageList
// 獲取了所有cookie的變化
chrome.cookies.onChanged.addListener(function (changeInfo) {
const fromList = storageList.map(e => e.from);
// 過濾出設置了監聽的cookie
if (fromList.includes(changeInfo.cookie.domain)) {
const target = storageList.find(e => e.from === changeInfo.cookie.domain);
// 移除
if (changeInfo.removed) {
chrome.cookies.remove({
url: "https://" + target.to,
name: changeInfo.cookie["name"],
});
}
// 設置或更新
else {
chrome.cookies.set({
url: "https://" + target.to,
name: changeInfo.cookie["name"],
path: "/",
value: changeInfo.cookie["value"],
expirationDate: changeInfo.cookie["expirationDate"],
secure: true,
sameSite: "no_restriction", // 不阻止跨域cookie
});
}
}
});
總結
chrome擴展的存在能夠突破瀏覽器的安全限制,獲取到很多js腳本中無法拿到的權限。更加靈活高效。
日常開發中遇到難以實現的需求,不妨試試chrome-extension
大法。
沒有什么自行車是造不出來的,大不了把流水線拆了重裝。