0

Just like the title says, i'm using an proxy to modify WebSocket but, for some reason the toString function(of the WebSocket proxy) is returning different values even though the proxy's get handler is returning target[p].. here's the code i'm using.

// ==UserScript==
// @name         proxy test
// @namespace    idk
// @version      0.1
// @description  testing proxy.
// @author       miniscripter
// @match        https://www.google.com
// @grant        unsafeWindow
// @run-at       document-start
// ==/UserScript==
console.clear();
console.log(WebSocket.toString());
unsafeWindow.WebSocket = new Proxy(WebSocket, {
    get(target, p, receiver) {
        console.log(target);
        return target[p]; //should return the target's property...
    }
});
console.log(unsafeWindow.WebSocket.toString());

enter image description here

As you can see, instead of returning the same toString value, it is returning an different value which seems to be the toString value of the proxy, why is this happening?

The new toString should return the same value as the original seeing that the Proxy retuns the original one..

1 Answers1

1

You're returning the toString by itself, so when you call that, the this is all "messed up" (see this for a complete overview of how this works). You need to bind it back to target so that the this inside still points to WebSocket:

console.log(WebSocket.toString());

WebSocket = new Proxy(WebSocket, {
    get(target, p, receiver) {
        return target[p].bind(target);
    }
});

console.log(WebSocket.toString());

Also, consider using Reflect.get(target, p, receiver) instead of target[p], depending on what you want to do (see this question for details).

kelsny
  • 23,009
  • 3
  • 19
  • 48