Created
June 22, 2025 10:42
-
-
Save sefgit/92a76835138b043ff868a10c037083bc to your computer and use it in GitHub Desktop.
websocket hook
This file contains hidden or 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
// | |
// https://stackoverflow.com/questions/70205816/intercept-websocket-messages | |
// | |
function listen(fn){ | |
fn = fn || console.log; | |
let property = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data"); | |
const data = property.get; | |
// wrapper that replaces getter | |
function lookAtMessage() { | |
let socket = this.currentTarget instanceof WebSocket; | |
if (!socket) { | |
return data.call(this); | |
} | |
let msg = data.call(this); | |
Object.defineProperty(this, "data", { value: msg } ); //anti-loop | |
fn({ data: msg, socket:this.currentTarget, event:this }); | |
return msg; | |
} | |
property.get = lookAtMessage; | |
Object.defineProperty(MessageEvent.prototype, "data", property); | |
} | |
listen( ({data}) => console.log(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment