Skip to content

Instantly share code, notes, and snippets.

@Checksum
Last active June 1, 2024 23:42
Show Gist options
  • Save Checksum/27867c20fa371014cf2a93eafb7e0204 to your computer and use it in GitHub Desktop.
Save Checksum/27867c20fa371014cf2a93eafb7e0204 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
};
@alpgul
Copy link

alpgul commented Jun 5, 2021

How do we override the websocket of the created 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