You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// background.js
console . log ( '✅ background.js 已加载' ) ;
console . log ( '✅ chrome 对象' , chrome ) ;
chrome . runtime . onMessage . addListener ( ( request , sender , sendResponse ) => {
console . log ( '📬 收到消息:' , request ) ;
if ( request . action === 'injectCookies' ) {
const { cookies , tabId } = request ;
// 使用异步方式执行脚本
chrome . scripting
. executeScript ( {
target : { tabId : tabId } ,
func : function ( cookies ) {
// Cookie注入函数
const cookiePairs = cookies . split ( ';' ) . map ( ( pair ) => pair . trim ( ) ) ;
const cookieObj = { } ;
cookiePairs . forEach ( ( pair ) => {
const [ key , value ] = pair . split ( '=' ) ;
if ( key && value ) {
cookieObj [ key ] = value ;
}
} ) ;
// 逐个设置 Cookie
Object . keys ( cookieObj ) . forEach ( ( key ) => {
document . cookie = ` ${ key } = ${ cookieObj [ key ] } ; path=/ ` ;
} ) ;
console . log ( '✅ Cookie 注入完成:' , cookieObj ) ;
} ,
args : [ cookies ] ,
} )
. then ( ( ) => {
// 成功执行后的响应
sendResponse ( { success : true , message : '注入成功' } ) ;
} )
. catch ( ( error ) => {
// 错误处理
console . error ( '注入失败:' , error ) ;
sendResponse ( { success : false , message : error . message || '未知错误' } ) ;
} ) ;
// 返回true表示异步响应
return true ;
}
// 对于非injectCookies消息, 返回false
return false ;
} ) ;