假设a站想往b站写cookie,那么目前有两种方案,参考如下:
第一种(使用jsonp):
a站js代码如下:
1 $.ajax({ 2 url: 'http://www.b.com/jsonp.jsp?domain=.b.com&value=123', 3 async: false, 4 dataType: 'jsonp', 5 jsonp:'callback', 6 jsonpCallback:"success_jsonpCallback", 7 success: function(result){ 8 console.log('result======' + result.info); 9 }, 10 error: function(result){ 11 console.log('fail'); 12 } 13 });
b站jsp代码如下:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import="java.net.*" %> 4 <% 5 String domain = request.getParameter("domain"); 6 String value = request.getParameter("value"); 7 String callback = request.getParameter("callback"); 8 // 设置 name 和 url cookie 9 Cookie name = new Cookie("test", value); 10 11 // 设置cookie过期时间为24小时。 12 name.setMaxAge(60*60*24); 13 name.setPath("/"); 14 name.setDomain(domain); 15 // 在响应头部添加cookie 16 response.addCookie( name ); 17 out.write( callback + "({"info":"success"})"); 18 %>
第二种方案:
a站页面代码:
1 <html> 2 <head> 3 <meta charset="utf-8"> 4 <title>a站页面</title> 5 </head> 6 <body> 7 <div> 8 <div> 9 <button id = "set_cookie_btn" type="button" >写cookie</button> 10 </div> 11 <div> 12 <button id = "syn_cookie_btn" type="button" >同步cookie</button> 13 </div> 14 <div id="cookie_iframe"> 15 </div> 16 <script src="jquery-3.2.1.min.js"></script> 17 <script> 18 (function(){ 19 function init(){ 20 console.log(window.location); 21 $('#set_cookie_btn').click(setCookie); 22 $('#syn_cookie_btn').click(synCookie); 23 } 24 25 /** 26 * 写测试cookie 27 */ 28 function setCookie(){ 29 document.cookie= "test=123;path=/;domain=.b.com"; 30 } 31 32 function synCookie(){ 33 //<iframe src='http://www.b.com/setCookies.html?p=123' width='100' height='100' style="display:none"></iframe> 34 var value = getCookie("test"); 35 var src = "http://www.b.com/setCookies.html?test="+value; 36 var iframeInfo = "<iframe src= "+src+" width='100' height='100' style='display:none'></iframe>"; 37 $('#cookie_iframe').html(iframeInfo); 38 } 39 40 function getCookie(cname){ 41 var _cookies = document.cookie.split(";"); 42 var _ran = ""; 43 for (var i = 0; i < _cookies.length; i++) { 44 var _cookie = _cookies[i]; 45 if (_cookie.split("=")[0].trim() == cname) { 46 _ran = _cookie.substring(_cookie.indexOf("=")+1).trim(); 47 break; 48 } 49 } 50 return _ran; 51 } 52 init(); 53 })(); 54 </script> 55 56 </body> 57 </html>
b站页面代码:
1 <html> 2 <head> 3 <meta charset="utf-8"> 4 <title>b站页面</title> 5 </head> 6 <body> 7 <script src="jquery-3.2.1.min.js"></script> 8 <script> 9 var url = location.href; 10 var get = url.substring(url.indexOf("test"));//获取变量和变量值 11 var idx = get.indexOf("=");//获取变量名长度 12 if (idx != -1) { 13 var name = get.substring(0, idx);//获取变量名 14 var val = get.substring(idx + 1);//获取变量值 15 setCookie(name, val,".b.com");//创建Cookie 16 } 17 </script> 18 </body> 19 </html>