前端开发工具之cookie-copy
问题背景:
单点登录应用中台的时候,开发子应用往往没有单独的登录入口,需要去测试环境登录之后粘贴token。如果是多个token每次粘贴会比较耗时
工具使用:
-
谷歌拓展加载加载成功之后将拓展钉在谷歌头部,
-
登录测试环境,点击拓展点击复制
-
回到dev环境点击粘贴。测试环境的所有cookie会被一键复制过来。
注:gitee地址:gitee.com/zeng-zhiyao…
工具实现核心代码
获取cookie列表
// 首先获取当前活动标签页的 URL
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const currentUrl:string = tab.url as string;
// 确保有有效的 URL
if (!currentUrl) {
console.error('无法获取当前标签页 URL');
return;
}
// 使用 chrome.cookies.getAll 并传入包含 url 的 details 对象
const cookies = await chrome.cookies.getAll({
url: currentUrl,
});
cookiesList.value = cookies.map((item) => {
return { name: item.name, value: item.value }
})
localStorage.setItem('cookiesList', JSON.stringify(cookiesList.value));
chrome.notifications.create({
type: 'basic',
title: '提示信息',
message: '复制cookie成功',
priority: 1,
iconUrl: "../../../public/logo.png"
});
// 后续处理 cookies...
粘贴cookie列表
chrome.cookies.set(
{
url: currentUrl as any, // 必须:与此 Cookie 关联的 URL
name: key, // 必须:Cookie 的名称
value: Value, // 必须:Cookie 的值
path: "/", // 可选:路径,默认为 "/"
secure: true, // 可选:是否仅通过 HTTPS 发送,默认为 false
httpOnly: false, // 可选:是否仅限 HTTP 访问(JS 不可读),默认为 false
expirationDate: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // 可选:过期时间(Unix 时间戳)。如果未设置,则为会话 Cookie。
// sameSite: "no_restriction" // 可选:SameSite 策略 ("no_restriction", "lax", "strict")
},
function (cookie) {
// 这是一个可选的回调函数
//public\logo.png
if (cookie) {
chrome.notifications.create({
type: 'basic',
title: '提示信息',
message: 'Cookie 设置成功',
priority: 1,
iconUrl: "../../../public/logo.png"
});
} else {
console.error("设置 Cookie 失败!");
}
}
);
注:此工具只能获取secure为true的cookie,谷歌cokie的限制