Home > Blockchain >  Custom window object property with reference to original
Custom window object property with reference to original

Time:02-11

I am trying to develop an extension in Chrome that will allow me to intercept access to the window object. Lets say I want to return double window.innerHeight, I tried setting it as follows:

Object.defineProperty(window, 'innerHeight', {
  get : () => window.innerHeight * 2,
});

But this obviously leads into infinite recursion. How can I redefine a window property while maintaining a reference to the original property? Doing something like let windowOld = Object.assign({}, window); will just capture the window properties at that static moment, and not actually maintain a reference to the original properties.

CodePudding user response:

Usually, in this situation, you'd just save the existing property in a variable first - but a complication is that window.innerHeight is a getter/setter, not a standard property. So, save the existing getter/setter, then define the property again (as a getter/setter, again, to maintain consistency).

const { get, set } = Object.getOwnPropertyDescriptor(window, 'innerHeight');
Object.defineProperty(
  window,
  'innerHeight',
  {
    get: () => get.call(window) * 2,
    set: (newVal) => set.call(window, newVal),
  }
);
  • Related