Proxy on window

Viewed 8460

I would like to set up a Proxy which warns me when a new property is defined on the window object. (Actually I'd like to catch all the global variable declarations)

let handler = {
    defineProperty(target, key, descriptor) {
        console.log('hey', key);
        return false;
    }
};
window = new Proxy(window, handler);
window.foo = 'bar';
// nothing happens

The code above works for any object but window:

let handler = {
    defineProperty(target, key, descriptor) {
        console.log('hey', key);
        return false;
    }
};
let target = {};
target = new Proxy(target, handler);
target.foo = 'bar';
// console: "hey  bar"

Is there any way to set up a Proxy on the window object, and if it's not possible, is there any tricky solution to achieve the same goal?

4 Answers

Yes window is unreplaceable, but you can wrap the tested code with a fake proxified window:

let handler = {
   defineProperty(target, key, descriptor) {
     console.log('hey', key);
     return false;
   }
 };

let proxyWindow = new Proxy(window, handler);

(function(window){
   
 //js
 window.foo = 'bar';

}.bind(proxyWindow,proxyWindow).call(proxyWindow));

If the tested code is not too complicated, this will be OK, as leaks to the actual window object may occur (ex: setTimeout etc) but these can be patched too.

Related