a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="userName" type="text" />
<input id="passwords" type="password" />
<button id="btn">设置</button>
<button onclick="login()">传递cookie</button>
<button onclick="deletecookie()">删除</button>
</body>
<script>
//设置cookie
var setCookie = function (name, value, day) {
//当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除
var expires = day * 24 * 60 * 60 * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + expires);
document.cookie = name + "=" + value + ";expires=" + exp.toUTCString();
};
//删除cookie
var delCookie = function (name) {
setCookie(name, ' ', -1);
};
//传递cookie
function login() {
var name = document.getElementById("userName");
var pass = document.getElementById("passwords");
setCookie('userName', name.value, 7)
setCookie('password', pass.value, 7);
location.href = 'b.html'
}
function deletecookie() {
delCookie('userName', ' ', -1)
}
</script>
</html>
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="getcookie()">获取</button>
</body>
<script>
//获取cookie代码
var getCookie = function (name) {
var arr;
var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) {
return arr[2];
}
else
return null;
};
//点击获取按钮之后调用的函数
function getcookie() {
console.log(getCookie("userName"));
console.log(getCookie("password"))
}
</script>
</html>
发表回复