Proxying Window Object To Detect Changes
Can I proxy the window object to detect changes? I tried the following without any luck:
Solution 1:
You have to reference the Proxy instance in your lower code, not the window
:
var handler = {
get: function(target, property) {
console.log("getting " + property + " for " + target);
return target[property];
},
set: function(target, property, value, receiver) {
console.log("setting " + property + " for " + target + " with value " + value);
target[property] = value;
returntrue;
},
};
var p = newProxy(window, handler);
setTimeout(() => {
p.a = 10; // <------------
}, 300);
setTimeout(() => {
p.c = 20; // <------------
}, 400);
If you can't change the code that references the window
, you could also name the proxy window
(and save a reference to the true window in another variable), but the code for that would look confusing.
If it's in a standalone script file, the above trick won't work, and you won't be able to use a Proxy
- you can't redefine the window object, after all. If you're looking for a change for a specific property on window
, you could use defineProperty
and have the setter overwrite the property descriptor with the new value when it gets assigned to:
Object.defineProperty(window, 'a', {
configurable: true,
set(value) {
console.log("setting with value " + value);
Object.defineProperty(window, 'a', { value });
}
});
setTimeout(() => {
window.a = 10;
console.log(window.a);
}, 300);
Post a Comment for "Proxying Window Object To Detect Changes"