Proxy server

I would like to set up Proxythat warns me when a new property is defined in the object window. (Actually, I would like to catch all declarations of global variables)

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 except the 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 a way to tune Proxyto an object window, and if that is not possible, is there any difficult solution to achieve the same goal?

+6
source share
3 answers

- . - . , . , . , , .

. , - Watch.JS , ,

watch(window, ['list', 'of', 'vars'], (prop, action, newVal, oldVal) => {
    console.log('Property changed', prop, action, newVal, oldVal);
}, 1);

let props = Object.keys(window);
const check = () => {
    const currentProps = Object.keys(window);
    const newProps = currentProps.filter(item => props.indexOf(item) === -1);
    if (newProps.length) {
        console.log('Added these properties', newProps);
        props = currentProps;
    }
    requestAnimationFrame(check);
};
requestAnimationFrame(check);

, , , , . , . . : profile data

unwatch Watch.JS , ,

+1

Proxy , window , , .

window , , .

Proxy, window, watch Firefox, , Firefox (, ), . V8- Object.observe window , Chrome V8.

, window:

let oldProps;

setInterval(() => {
  console.time('Polling window');
  let newProps = Object.getOwnPropertyNames(window);

  if (oldProps) {
    let addedProps = newProps.filter(prop => oldProps.indexOf(prop) < 0 );
    console.log('Added props', addedProps);
  }
  oldProps = newProps;
  console.timeEnd('Polling window');
}, 500);

, , filter , indexOf , .

Raw for while - :

let oldProps;

setInterval(() => {
  console.time('Polling window');
  let newProps = Object.getOwnPropertyNames(window).sort();

  if (oldProps) {
    for (let oldI = 0, newI = 0; oldI < oldProps.length || newI < newProps.length; oldI++, newI++) {
      let oldProp = oldProps[oldI];
      let newProp = newProps[newI];

      if (newProp > oldProp || newProp === undefined) {
        newI--;
        console.log('Removed prop', oldProp);
      } else if (newProp < oldProp || oldProp === undefined) {
        oldI--;
        console.log('Added prop', newProp);
      }
    }
  }
  oldProps = newProps;
  console.timeEnd('Polling window');
}, 500);
+3

You are not actually trying to start a window proxy. You need to do:

let proxy = new Proxy(window, handler);
proxy.foo = 'bar';

And no, you cannot

window = new Proxy(window, handler);

since the window cannot be replaced.

0
source

All Articles