Last active
September 28, 2024 17:31
-
-
Save Checksum/27867c20fa371014cf2a93eafb7e0204 to your computer and use it in GitHub Desktop.
Intercepting WebSockets in the browser using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WebSocketProxy = new Proxy(window.WebSocket, { | |
construct(target, args) { | |
console.log("Proxying WebSocket connection", ...args); | |
const ws = new target(...args); | |
// Configurable hooks | |
ws.hooks = { | |
beforeSend: () => null, | |
beforeReceive: () => null | |
}; | |
// Intercept send | |
const sendProxy = new Proxy(ws.send, { | |
apply(target, thisArg, args) { | |
if (ws.hooks.beforeSend(args) === false) { | |
return; | |
} | |
return target.apply(thisArg, args); | |
} | |
}); | |
ws.send = sendProxy; | |
// Intercept events | |
const addEventListenerProxy = new Proxy(ws.addEventListener, { | |
apply(target, thisArg, args) { | |
if (args[0] === "message" && ws.hooks.beforeReceive(args) === false) { | |
return; | |
} | |
return target.apply(thisArg, args); | |
} | |
}); | |
ws.addEventListener = addEventListenerProxy; | |
Object.defineProperty(ws, "onmessage", { | |
set(func) { | |
const onmessage = function onMessageProxy(event) { | |
if (ws.hooks.beforeReceive(event) === false) { | |
return; | |
} | |
func.call(this, event); | |
}; | |
return addEventListenerProxy.apply(this, [ | |
"message", | |
onmessage, | |
false | |
]); | |
} | |
}); | |
// Save reference | |
window._websockets = window._websockets || []; | |
window._websockets.push(ws); | |
return ws; | |
} | |
}); | |
window.WebSocket = WebSocketProxy; | |
// Usage | |
// After a websocket connection has been created: | |
window._websockets[0].hooks = { | |
// Just log the outgoing request | |
beforeSend: data => console.log(data), | |
// Return false to prevent the on message callback from being invoked | |
beforeReceive: data => false | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do we override the websocket of the created iframe?