单个浏览器限制网站打开指定的个数
如果需要再一个自己的网站中实现:
1、在同源、同浏览器的情况下限制一个网页打开指定的个数之后不能再打开新的页面,或者打开之后关闭;
2、为了兼容部分浏览器版本问题,页面直接重定向到指定的空白页。
可以通过window.localStorage来实现网页打开计数器,可以自行调整limitPageCount 控制网页最多允许打开多少个。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>测试页面控制只能打开3个</title>
</head>
<body style="display: flex; justify-content: center; align-items: center; height: 100vh">
<div style="width: 300px; height: 300px; background-color: #0c82b7">
</div>
</body>
</html>
<script>
//页面限制显示的个数
let limitPageCount = 3
//页面的销毁方法是否被执行过
let poerflag = false
window.addEventListener('load', e => {
//每一个页面获取一个唯一的码
let romCode = getRomCode();
console.log("romCode", romCode)
//递增计数加1
increase(limitPageCount)
loadPreData()
});
// 页面关闭时,计数减1
window.addEventListener('unload', e => {
console.log("页面关闭")
decrease()
unloadPostData()
});
/**
* 卸载数据,页面销毁的时候执行
*/
function unloadPostData() {
console.log("卸载数据")
// todo ..
}
/**
* 加载预前必要数据
*/
function loadPreData() {
console.log("加载一些数据")
// todo ....
}
/**
* 每个页面获取一个唯一码
*/
function getRomCode() {
//模拟
let str = new Date().getTime().toString()
return str.substring(str.length - 4, str.length)
}
/**
* 页面计数加1
*/
function increase(limitPageCount) {
//限制页面只能打开3个
let count = +window.localStorage.getItem('count');
if (isNaN(count) || count <= 0) {
count = 1;
} else {
count++;
}
window.localStorage.setItem('count', count.toString());
console.log("navigator.userAgent", navigator.userAgent)
if (count > limitPageCount) {
alert("页面超出限制,页面即将关闭")
window.location.href = "about:blank";
decrease()
window.close()
}
}
/**
* 页面计数减一
*/
function decrease() {
//页面的销毁方法没有被执行过就执行一次,否则不执行
if (!poerflag) {
let count = +window.localStorage.getItem('count');
if (isNaN(count) || count <= 0) {
count = 0;
} else {
count--;
}
window.localStorage.setItem('count', JSON.stringify(count));
}
poerflag = true
}
</script>