javascriptfunctionuserscriptses6-proxy

Proxy returning different value from expected


Just as mentioned in the title, I am using a proxy to hook a WebSocket but, the toString function(accessed using a WebSocket proxy) is returning different values even though the proxy is returning what seems to be the correct function...

Here's an example:

console.log(WebSocket.toString());
unsafeWindow.WebSocket = new Proxy(WebSocket, {
    get(target, p, receiver) {
        console.log(target);
        return target[p]; //supposedly correct
    }
});
console.log(unsafeWindow.WebSocket.toString());

what are you looking at hah

As you can see, instead of returning the original toString value, it is returning what seems to be the toString value of the proxy instead, why is this happening?


Solution

  • 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).