网站更新内容:请访问: https://bigdata.ministep.cn/

Chrome Extension 筆記(07)針對 cookie 進行讀寫

當使用 xhr 在網路上抓資料時,
若遇上需要登入的部份, 就可能需要對 cookie 進行操作,
如果再配合上一篇介紹的 Storage,
想做一個能'在同個網站做多重帳戶切換'的擴充功能就不是難事.

manifest.json

{
   "manifest_version": 2,
   "name": "ironman6",
   "version": "1.0",
   "browser_action": {
      "default_popup": "index.html"
   },
	"permissions": [
		"cookies",
		"http://ithelp.ithome.com.tw/*"
	]
}

index.html

		<title>ironman6</title>
		<style>body {width: 500px ;} li {white-space: nowrap;}</style>
	
	
		<input type="text" id="cname" placeholder="name"/>
		<input type="text" id="cvalue" placeholder="value"/>
		<button id="setcookie">SetCookie</button>
		<div id="content"></div>
		<script src="app.js"></script>
	

app.js

document.addEventListener('DOMContentLoaded', function () {
	document.querySelector('#setcookie').addEventListener('click', setCookie);
	getCookie();
});

var content = document.querySelector('#content');
var cname   = document.querySelector('#cname');
var cvalue  = document.querySelector('#cvalue');

function setCookie() {
	chrome.cookies.set({
		url  : 'http://ithelp.ithome.com.tw/',
		name : cname.value,
		value : cvalue.value
	}, function(msg){
		console.dir(msg);
		getCookie();
	});
}

function getCookie() {
	var output = [];
	chrome.cookies.getAll({
		url  : 'http://ithelp.ithome.com.tw/'
	}, function(cookies){
		for (var i = 0; i < cookies.length; i++) {
			var name   = cookies[i].name;
			var value  = cookies[i].value;
            output.push('<li>' + name + ' : ' + value + '</li>');
		}
		content.innerHTML = output.join('');
	});
}

function delCookie(name) {
	chrome.cookies.remove({
		url  : 'http://ithelp.ithome.com.tw/',
		name : name
	}, function(msg){
		console.dir(msg);
		getCookie();
	});
}

要注意的是
cookie 的操作必須配合 主機權限(host-permissions)一起使用,
像上面的例子僅聲明了 "http://ithelp.ithome.com.tw/\*" 的權限,
所以若再去要求 "http://www.google.com/" 的 cookie,
則會出現錯誤.

 

[Chrome Extension 筆記(07)針對 cookie 進行讀寫 - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天](https://ithelp.ithome.com.tw/articles/10128585 )]

posted @ 2021-11-18 15:29  ministep88  阅读(59)  评论(0编辑  收藏  举报
网站更新内容:请访问:https://bigdata.ministep.cn/