Is it possible to use ES6 Proxies to track changes of location.pathname?
As far as I know, Proxies can be used for objects, and location.pathname is an object, right?
If the answer is yes, can someone help me understand how to achieve this?
The only working thing I managed to create is the following code:
const handler = {
get(target, key) {
console.log(`Reading value from ${key}`)
return target[key];
},
};
const p = new Proxy(location, handler);
console.log(p.pathname);
But the above code will only show once the current URL is in the browser's tab.
How can I make it work to keep tracking the changes?
window.location is a nonconfigurable getter/setter, which means that it can't be replaced:
console.log(Object.getOwnPropertyDescriptor(window, 'location'));
The same is true for the .pathname property of the object returned by the getter:
console.log(Object.getOwnPropertyDescriptor(window.location, 'pathname'));
And a location variable can't be declared on the top level:
const location = { newObject: 'foo' };
Which means that there's no way to intercept changes to it by replacing it with a Proxy - any references or assignments in the existing code to window.location.pathname will necessarily invoke the browser's built-in implementation.