前端jq通过IP校验页面权限

最近需要给页面限制IP查看权限。网上解决方案和自己得归纳整理下笔记吧。

说明都有,以下完整的js代码,主要是通过,动态加载jq的cdn和sohu获取ip的jq库,实现只引入本js,动态控制页面ip限制

/*****
Ip权限判断 

界面引入
    <script src="validateIP.js"></script>
界面增加ip地址input,id为ipArray,value为ip地址,|分割
     <input type="hidden" value="127.0.0.1|127.0.0.1" id="ipArray"/>
***/

//load jquery
var script = document.createElement('script');
script.src = "https://cdn.staticfile.org/jquery/3.4.1/jquery.js";

document.getElementsByTagName('head')[0].appendChild(script);

//load getip jqlib
var script1 = document.createElement('script');
script1.src = "http://pv.sohu.com/cityjson?ie=utf-8";
document.getElementsByTagName('head')[0].appendChild(script1);

//有跨域,localhost无效
setInterval(function () {
    var ip = returnCitySN["cip"];
    var allowIP = $('#ipArray').val().split('|');
    if ($.inArray(ip, allowIP) < 0) {
        alert("您无权限访问该页面。");
        closePage();
    }
}, 3000);

//关闭页面,直接写window.close()在非跳转打开页面,无法关闭。
function closePage() { 
    if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1) {
        window.location.href = "about:blank";
        window.close();
    } else {
        window.opener = null;
        window.open("", "_self");
        window.close();
    }
}
validate

 

若使用,请注明来源,不喜勿喷,谢谢

 

posted @ 2020-05-22 16:12  寒空孤鹰  阅读(628)  评论(0)    收藏  举报