单个浏览器限制网站打开指定的个数

单个浏览器限制网站打开指定的个数

如果需要再一个自己的网站中实现:
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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值