Skip to content

Instantly share code, notes, and snippets.

@sefgit
Forked from Checksum/websocket_proxy.js
Created June 22, 2025 02:35
Show Gist options
  • Save sefgit/f8a7e1ab210707ebb17f224a49dda0af to your computer and use it in GitHub Desktop.
Save sefgit/f8a7e1ab210707ebb17f224a49dda0af to your computer and use it in GitHub Desktop.
Intercepting WebSockets in the browser using JavaScript
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
};
@sefgit
Copy link
Author

sefgit commented Jul 30, 2025

for iframe:

var iframe=document.createElement('iframe');

document.body.append(iframe);

new iframe.contentWindow.WebSocket(...);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment