检查是否已在JavaScript中覆盖全局属性/函数 [英] Check if a global property/function has been overwritten in JavaScript

查看:100
本文介绍了检查是否已在JavaScript中覆盖全局属性/函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript可以轻松覆盖全局对象的属性和功能。我想找到一种方法来检查全局属性的原始版本是否已被替换。

JavaScript makes it easy to overwrite properties and functions of the global object. I'd like to find a way to check if the original version of a global property has been replaced.

考虑有人将其放入HTML:

Consider someone putting this in their HTML:

<script type="text/javascript">
    window.encodeURIComponent = eval;
</script>
<script type="text/javascript" src="myscript.js"></script>

如果myscript.js在某处调用encodeURIComponent函数,它现在将表现得不可预测。那么,如果有人在我使用之前覆盖了该函数,我可以检查一下myscript.js吗?

If myscript.js calls the encodeURIComponent function somewhere, it will now behave unpredictably. So is there a way I can check inside myscript.js if someone has overwritten that function before I use it?

推荐答案

唯一我所知道的是一种直接的方法,分析函数的字符串表示。通常,代码

The only thing I know is a straightforward approach with analysis of string representation of the function. Normally, the code

window.encodeURIComponent.toString()

应该产生这样的东西:

function encodeURIComponent() { [native code] }

可以很容易地解析密钥信息 function encodeURIComponent

which can be easily parsed for key info function encodeURIComponent.

如果函数被 eval 覆盖,就像在你的例子中一样,你' ll get:

If the function was overwritten by eval, as in your example, you'll get:

function eval() { [native code] }

通常,对于检查窗口属性,您可以创建一个假的iframe并比较 window。[property] .toString() with iframe.contentWindow。[property] .toString()。如果比较为 false ,则该属性已更改。

In general, for checking window properties, you can create a fake iframe and compare window.[property].toString() with iframe.contentWindow.[property].toString(). If the comparison gives false, the property has been changed.

这篇关于检查是否已在JavaScript中覆盖全局属性/函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆