chrome listens to cookie changes and assignments

  • 2021-11-29 23:03:42
  • OfStack

The following code introduces you to chrome listening for cookie changes. The code is as follows:


/**
*  Eavesdropping cookie Change 
*/
chrome.cookies.onChanged.addListener(function(changeInfo){
	// cookies.onChanged Listening is all cookie, So we need to filter only our own website cookie
	if(GhomepageDomain == changeInfo.cookie.domain){
		var cookieNameReg = /[A-Z]/;
		var cookieInfo = changeInfo.cookie;
		if(!cookieNameReg.test(cookieInfo.name)){
			// cookie Copy all lowercase names to plugin
			if(changeInfo.removed){
				//  Remove cookie
				chrome.cookies.remove({
					url : Gplugin,
					name : cookieInfo['name']
				},function(_cookie){
					// console.log(' Remove , Retrieve cookie',_cookie);
				 	// getUserInfo(1);
				});
			}else{
				//  Settings cookie
				chrome.cookies.set({
					url: Gplugin,
					name: cookieInfo['name'],
					path: '/',
					value: cookieInfo['value'],
					expirationDate: cookieInfo['expirationDate'],
					secure: true,
					sameSite: 'no_restriction', //  Do not block cross-domain cookie
				},function(_cookie){
					// console.log(' Settings , Retrieve cookie',_cookie);
					// getUserInfo(1);
				});
			}
		}
	}
});

ps: Let's take a look at the cookie listening and assignment problem in the CHROME Extension Note.

cookie listening and assignment operation requires permission declared in manifest file, cookie
The permissions are as follows:


{
	"permissions": [ "cookies", "*://*. To operate cookie Domain name of .com/*" ],
}

/**
*  Eavesdropping cookie Change 
*/
chrome.cookies.onChanged.addListener(function(changeInfo){
	// cookies.onChanged Listening is all cookie, So we need to filter only our own website cookie
	if(GhomepageDomain == changeInfo.cookie.domain){
		var cookieNameReg = /[A-Z]/;
		var cookieInfo = changeInfo.cookie;
		if(!cookieNameReg.test(cookieInfo.name)){
			// cookie Copy all lowercase names to plugin
			if(changeInfo.removed){
				//  Remove cookie
				chrome.cookies.remove({
					url : Gplugin,
					name : cookieInfo['name']
				},function(_cookie){
					// console.log(' Remove , Retrieve cookie',_cookie);
				 	// getUserInfo(1);
				});
			}else{
				//  Settings cookie
				chrome.cookies.set({
					url: Gplugin,
					name: cookieInfo['name'],
					path: '/',
					value: cookieInfo['value'],
					expirationDate: cookieInfo['expirationDate'],
					secure: true,
					sameSite: 'no_restriction', //  Do not block cross-domain cookie, If not secure And sameSite These two are so in chrome80 The above version will appear iframe Page unavailable cooke
				},function(_cookie){
					// console.log(' Settings , Retrieve cookie',_cookie);
					// getUserInfo(1);
				});
			}
		}
	}
});

Note: If you don't understand secure and sameSite, you can see the SameSite attribute of Liao Xuefeng's blog cookie


Related articles: