You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测并阻止浏览器控制台中尝试执行的特定JavaScript命令?

检测并阻止控制台执行特定风险JavaScript代码的实现方案

核心思路:重写目标函数实现拦截

要阻止控制台执行xor.decode(password)并输出指定搞笑消息,最直接的方案是重写xor.decode方法,在函数内部加入检测逻辑,拦截风险调用。

代码实现

基础拦截版本

如果xor已经是全局对象,直接重写其decode方法:

// 保存原始的decode方法
const originalXorDecode = xor.decode;

// 重写decode方法
xor.decode = function(input) {
    // 检测是否是针对password的解密调用
    if (input === password || (typeof input === 'string' && input.includes('password'))) {
        // 输出搞笑消息到控制台
        console.log('jajajaja you tried, L bozo!');
        // 阻止原解密逻辑执行,返回空值
        return null;
    }
    // 非风险调用,执行原始解密逻辑
    return originalXorDecode.call(this, input);
};

安全封装版本(推荐)

把密码、加密解密逻辑和拦截逻辑封装在闭包里,避免password直接暴露在全局作用域:

(function() {
    // 内部私有密码变量,外部无法直接访问
    const userPassword = 'user-input-password';
    // 自定义XOR密钥
    const xorKey = 'your-secret-key';

    // 原始XOR加密解密逻辑
    const xor = {
        encode: function(str) {
            return str.split('').map((char, idx) => 
                String.fromCharCode(char.charCodeAt(0) ^ xorKey.charCodeAt(idx % xorKey.length))
            ).join('');
        },
        decode: function(str) {
            return str.split('').map((char, idx) => 
                String.fromCharCode(char.charCodeAt(0) ^ xorKey.charCodeAt(idx % xorKey.length))
            ).join('');
        }
    };

    // 重写decode方法加入拦截
    const originalDecode = xor.decode;
    xor.decode = function(input) {
        // 检测是否是尝试解密原始密码或加密后的密码
        if (input === userPassword || input === xor.encode(userPassword)) {
            console.log('jajajaja you tried, L bozo!');
            return null;
        }
        return originalDecode.call(this, input);
    };

    // 将xor对象暴露到全局(如果需要外部调用加密功能)
    window.xor = xor;
})();

注意事项

  • 该方案只能拦截直接调用xor.decode的操作,如果有人直接复制XOR解密逻辑到控制台执行,无法拦截,但对于你的场景(低安全性需求的Web OS)已经足够。
  • 既然你暂时用XOR加密过渡,这个拦截方案完全适配你的需求,后续更换加密方式时,只需要同步更新拦截逻辑即可。

内容的提问来源于stack exchange,提问作者Snoot Man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:06:43