【谷歌插件开发】获取当前网站COOKIE并上报HTTP-API

一 背景

由于本人每天需要登录网站查看数据并分析统计汇总,而每次机械式地搜索和简单计算,十分繁琐。我们可以写个定时任务,每天根据cookie获取网站数据并遍历统计。

脚本得以成功执行的关键是需要获取到COOKIE

故,写了个谷歌插件用来上报COOKIE

二 代码总目录

三 上代码

  • manifest.json
    {
      "manifest_version": 3,
      "name": "Get Cookie",
      "description": "get cookie",
      "version": "1.0.0.1",
      "action": {
        "default_popup": "index.html",
        "default_icon": "images/icon.png"
      },
      "host_permissions": [
    	  "http://*/*",
    	  "https://*/*"
      ],
      "permissions": [
    	  "cookies",
    	  "tabs"
      ]
    
    }
  • index.html
    <html>
    	<head>
    		<meta http-equiv="content-type" content="text/html;charset=utf-8">
    		<link rel="stylesheet" type="text/css" href="mystyle.css">
    	</head>
    	<body>
    		<div id="container">
    			
    			
    			 <div class="sub">
    			    <div class="card">
    					<form action="#">
    						<textarea id="cookie" required readonly name="cookie" value="" placeholder="cookie"></textarea> <br>
    						<br>
    						<textarea id="hostnm" required readonly name="hostnm" value="" placeholder="host name"></textarea> <br>
    						<br>
    						<input id="username" type="text" required name="username" value="" class="username" style="height:30px;font-size: 15px;line-height:30px;" placeholder="请输入投放账户ID" autocomplete="on"> <br>
    						<br>
    						<input id="password" type="password" required name="password" value="" class="password"style="height:30px;font-size: 15px;line-height:30px;"placeholder="请输入密码"><br>
    						<br>
    						<label>环境:</label>
    						<input type="radio" name="env" value="2" checked /> 正式
    						<input type="radio" name="env" value="1" /> 测试
    						<br><br>
    						<input type="button" id="btn" style="background-color: #b3d4fc;width: 60%;height: 30px" value="验证上传">
    					</form>
    			    </div>
    			  </div> 
    		</div>
    		<script src="script.js"></script>
    	</body>
    </html>
  • mystyle.css
    #container {
      width: 250px;
      word-break: break-all;
    }
    .login{
      margin: 0 auto;
      position: relative;
      top: 100px;
      height: 500px;
      width: 400px;
      border-color: aqua;
    }
    .card{
      width: 75%;
      margin: auto;
    }
    

     

  • script.js
    const $container = document.getElementById('container')
    document.addEventListener('DOMContentLoaded', () => {
    	chrome.tabs.query({ 'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT },
    		function (tabs) {
    			var url = new URL(tabs[0].url)
    			document.getElementById("hostnm").value = url.host
    			var hostarr = url.host.split('.')
    			hostarr.shift()
    			var curhost = hostarr.join(".");
    			console.log(curhost)
    			
    			chrome.cookies.getAll({
    				domain: curhost
    			}, (cookies) => {
    				console.dir(cookies);
    				cookies.map((c) => {
    					document.getElementById("cookie").value += c.name + "=" + c.value+"; "
    				})
    			})
    			
    			var btn=document.getElementById("btn");
    			btn.onclick=function () {
    				var username=document.getElementById("username").value;//获取用户名input的value
    				var password=document.getElementById("password").value;
    				var cookie=document.getElementById("cookie").value;
    				var hostnm=document.getElementById("hostnm").value;
    				var env = 2;
    				var obj = document.getElementsByName("env")
    				for (var i = 0; i < obj.length; i++) {
    					if (obj[i].checked) {
    						env = obj[i].value;                   
    					}
    				}
    				console.log("env: " + env)
    				console.log("username: " + username)
    				console.log("password: " + password)
    				console.log("cookie: " + cookie)
    				console.log("hostnm: " + hostnm)
    				if(username == undefined || username.trim() == ''){
    					alert("请输入 投放账户ID")
    					return false;
    				}
    				if(password == undefined || password.trim() == ''){
    					alert("请输入 密码")
    					return false;
    				}
    				if(cookie == undefined || cookie.trim() == ''){
    					alert("获取COOKIE失败")
    					return false;
    				}
    				if(hostnm == undefined || hostnm.trim() == ''){
    					alert("获取域名失败")
    					return false;
    				}
    				if(hostnm.trim().indexOf('你想抓去的页面域名') == -1){
    					alert("非需要抓取页面")
    					return false;
    				}
    				username = username.trim();
    				password = password.trim();
    				cookie = cookie.trim();
    				hostnm = hostnm.trim();
    				var data= {
    					'username':username,'password':password,'env':env,'cookie':cookie,'hostnm':hostnm
    				}
    				console.log(data)
    				var stringData=JSON.stringify(data);
    				var querydData = Object.keys(data).map(key => key + '=' + data[key]).join('&');
    				var ajax=null;
    				if(window.XMLHttpRequest) {
    					ajax=new XMLHttpRequest();
    				}else {
    					ajax=new ActiveXObject("Microsoft.XMLHTTP");
    				}
    				var posturl = "http://测试域名/api/upcookie";
    				if(env == 2){
    					posturl = "https://正式域名/api/upcookie"
    				}
    			    ajax.open("POST",posturl,true);
    				// ajax.open("GET",posturl+'?'+querydData,true);
    				ajax.onreadystatechange=function () {
    					if(ajax.readyState==4){
    						if(ajax.status==200){
    							var demo=ajax.responseText;
    							var demojson = JSON.parse(demo); 
    							if(demojson.success){
    								alert("上传成功")
    							}else{
    								alert(demojson.msg)
    							}
    						}else{
    							alert("服务器繁忙,请稍后重试")
    						}
    					};
    				}
    				ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    				ajax.send(querydData);
    			}
    		}
    	);
    })

四 效果演示

 

 

五 补充说明

  • 需要填写用户名密码的意义在于服务安全,防止拓展被乱用,我可以在api的后台随时配置随时删除。当然你使用jwt或更高级的更好。
  • cookie是有几级域名限制的,我们经常涉及到sso的场景,一般用类似于baidu.com来抓去baidu的cookie,而非fanyi.baidu.com。

热门相关:超武穿梭   豪门闪婚:帝少的神秘冷妻   天启预报   夫人你马甲又掉了   最强装逼打脸系统