gpt4 book ai didi

javascript - 有什么方法可以防止在单例实例中覆盖/覆盖函数/变量?

转载 作者:可可西里 更新时间:2023-11-01 01:26:13 26 4
gpt4 key购买 nike

考虑这个伪代码:

(function(window){
var options = { /*where everything goes */ };

var instance = (function(options){
for (var i in options){
if (options.hasOwnProperty(i)){
this[i] = options[i];
}
}
})(options);

instance.callbacks = function(cb){
//...
}

instance.is_allowed = function()
//... checks, return boolean
}

window.instance = instance;
})(this);

如果有人想操纵这段代码(例如恶意用户),他会用他自己的代码重写 is_allowed 函数,例如,使用地址栏(他没有 Firebug , 谁知道)。

javascript:(function(){ window.instance.is_allowed = function(){ return true; } })();

这是一个天真的例子,但这就是重点,Javascript 中的任何内容都可以被覆盖。

我知道在 es5 中我们有 Object.defineProperty 所以你可以设置:

// being explicit
Object.defineProperty(instance, "is_allowed", {
enumerable: false,
configurable: false,
writable: false,
value: function(){
// do checks
}
});

实际上,从这个意义上说,最好的方法是使用 Object.freeze(instance)Object.seal(instance) 而不是 Object.defineProperty,因为后者可以用 writable: false 再次调用(愚蠢吧?)

有什么方法可以让它在旧浏览器(即 IE6-8)中工作而不会太麻烦?如果这是不可能的,那我就耸耸肩继续前进。

最佳答案

If anyone ever wanted to manipulate this code (a malicious user for example), he would rewrite the is_allowed function with his own

他可以重写您的整个 javascript 代码,甚至可以不使用浏览器而是模拟对您的服务器的“无浏览器”请求。

Is there ANY way that it work in old browsers (namely IE6-8) without too much hassle?

没有。您全局公开的任何内容都可以被用户更改,这取决于浏览器限制 javascript: 行为以避免用户被愚弄访问预先制作的链接。 Firefox 最近对 javascript URL 协议(protocol)进行了某种更改。

如本文所述:http://survey-remover.com/blog/javascript-protocol-dangers/

As of Chrome v13, Firefox v6 and IE 9, the browser developers have taken notice to the dangers of the "javascript:" protocol and have subsequently disallowed code ... In the case of Chrome and IE, the "javascript:" substring is stripped when the code is pasted, whereas Firefox no longer executes the script within the scope of the active page.

所以...

If it's impossible, then I'll just shrug and move on.

你应该。

关于javascript - 有什么方法可以防止在单例实例中覆盖/覆盖函数/变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14671332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com