简体   繁体   English

在JavaScript中访问原始全局变量和属性

[英]Access original globals and attributes in JavaScript

I'm working on code that is injected on web pages (using a browser add-on or with a script tag). 我正在研究注入网页的代码(使用浏览器插件或脚本标签)。

The problem is that we want to use global objects and variables like JSON , window.location , String.split , etc. and the implementation of these may have been changed by the web page. 问题是我们想要使用全局对象和变量,如JSONwindow.locationString.split等,并且这些实现可能已被网页更改。 This may make our code fail, and it is a security problem. 这可能会使我们的代码失败,这是一个安全问题。

Example: 例:

>>> String.prototype.split = function() { return 'foo'; };
function()
>>> 'a,b,c'.split(',');  // gives unexpected result
"foo"

So, is there a way to get access to the browser's default implementation of objects and functions as they were before they were changed? 那么,是否有办法访问浏览器的默认实现对象和函数,就像它们被更改之前一样? It does not have to be standard, I just want the functionality to exist. 它不一定是标准的,我只是希望功能存在。

Update 更新

Perhaps a more viable way would be to create an empty <iframe> dynamically. 也许更可行的方法是动态创建一个空的<iframe>

Here's an example that contaminates String.prototype.split in the parent window but gets a clean one from <iframe> . 这是一个在父窗口中污染String.prototype.split的示例,但从<iframe>获取一个干净的示例。

<html>
<head>
<script type="text/javascript">
    function onBodyLoad() {

        String.prototype.split = function() { return 'foo'; }; // contaminate original window
        console.log(String.prototype.split); // yeah, it's contaminated

        var acr = document.getElementById("accessor");
        acr.onclick = function ()
        {
            var dummyFrame = document.createElement("iframe");
            document.body.appendChild(dummyFrame); 
            console.log(dummyFrame.contentWindow.String.prototype.split); // uncontaminated
        }
    }
</script>
</head>
<body onload="onBodyLoad()">
    <a href="#" id="accessor">Access iframe Window object</a>
</body>
</html>

Not in the ordinary sense; 不是一般意义上的; although there might be some exotic hacks out there. 虽然那里可能有一些异国情调的黑客。

\n

The only way I could think of, was to make sure your code gets loaded before any other script. 我能想到的唯一方法是确保在任何其他脚本之前加载代码。 If that requirement if fulfilled, necessary global variables can be cloned into a safe location. 如果满足该要求,则可以将必要的全局变量克隆到安全位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM