douyinWEB/extensions/tiktok-cookie-helper/background.js
eric 0815e05094 fix: TikTok 上传自动探测 tt-target-idc,避免 KeyError project
Cookie 有效但默认机房 useast2a 会导致 project/create 返回 status_code=8。上传前探测可用机房并写回 Cookie。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 11:22:56 -05:00

47 lines
1.3 KiB
JavaScript

const TIKTOK_URLS = [
"https://www.tiktok.com/",
"https://www.tiktok.com",
];
function cookieMap(cookies) {
const out = {};
for (const c of cookies || []) {
if (c && c.name) out[c.name] = c.value || "";
}
return out;
}
async function readTikTokCookies() {
const bags = await Promise.all(
TIKTOK_URLS.map((url) => chrome.cookies.getAll({ url }).catch(() => [])),
);
const byName = cookieMap(bags.flat());
const extra = await chrome.cookies.getAll({ domain: ".tiktok.com" }).catch(() => []);
Object.assign(byName, cookieMap(extra));
const sessionid = String(byName.sessionid || byName.sessionid_ss || "").trim();
const dc = String(byName["tt-target-idc"] || byName.tt_target_idc || "").trim();
const username = String(byName["uniqueid"] || byName.uniqueId || "").trim();
return {
ok: Boolean(sessionid),
sessionid,
dc_id: dc,
tiktok_username: username,
payload: {
sessionid,
dc_id: dc,
tiktok_username: username,
},
};
}
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg?.type === "GET_TIKTOK_COOKIES") {
readTikTokCookies()
.then(sendResponse)
.catch((err) => sendResponse({ ok: false, error: String(err) }));
return true;
}
return false;
});