让jquery代码只能在指定域名下运行的三种方法

web前端 57 4周前 (05-18)

Base64方法一:

对整个字符串进行Base64编码,要确保在编码和解码过程中,域名列表始终是有效的JSON格式。这样可以避免JSON.parse()抛出语法错误。

const encodedDomains = 'WyJsb2NhbGhvc3QiLCIxMjcuMC4wLjEiXQ==';//localhost、127.0.0.1
const decodedDomainList = JSON.parse(atob(encodedDomains));
const currentDomain = window.location.hostname;
if (decodedDomainList.includes(currentDomain)) {
    $(function(){
        //jQuery代码段...
        $('body').append('<p>看到此内容代表在允许的域名中且运行完毕</p>');
    });
}

Base64方法二:

对单独的域名进行Base64编码。

var allowedDomains = ['bG9jYWxob3N0','MTI3LjAuMC4x']; //localhost, 127.0.0.1
var currentDomain = window.location.hostname;
var isAllowed = false;

for (var i = 0; i < allowedDomains.length; i++) {
    var decodedDomain = atob(allowedDomains[i]);
    if (currentDomain.endsWith(decodedDomain)) {
        isAllowed = true;
        break;
    }
}
if (isAllowed) {
    $(function(){
        //jQuery代码段...
        $('body').append('<p>看到此内容代表在允许的域名中且运行完毕</p>');
    });
}

16进制方法:

const hexEncodedDomains = '5b226c6f63616c686f7374222c223132372e302e302e31225d';//localhost、127.0.0.1
const hexToArray = hexEncodedDomains.match(/.{1,2}/g);
const decodedDomainList = String.fromCharCode(...hexToArray.map(byte => parseInt(byte, 16)));
const domainList = JSON.parse(decodedDomainList);
const currentDomain = window.location.hostname;
if (domainList.includes(currentDomain)) {
    $(function(){
        //jQuery代码段...
        $('body').append('<p>看到此内容代表在允许的域名中且运行完毕</p>');
    });
}

以上三种方法均以localhost和127.0.0.1为例,无论是Base64还是16进制法,都可被轻易的解码,可使用更复杂的AES算法。

分享给朋友: