Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 586
Martin Vilcans Avatar asked Oct 07 '22 13:10

Martin Vilcans


1 Answers

Update

Perhaps a more viable way would be to create an empty <iframe> dynamically.

Here's an example that contaminates String.prototype.split in the parent window but gets a clean one from <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.

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.

like image 174
Saul Avatar answered Oct 12 '22 23:10

Saul