While tools like Sentry or Datadog are amazing to track performance issues of HTML, CSS, JavaScript, and XHR requests, they often don’t provide the best tools when it comes to WebSockets. WebSocket connections themselves may be logged, but the messages/errors sent over them are not captured by these tools.
This solution may not be the cleanest, but to the best of my knowledge, there is no other way to achieve this functionality. The approach involves creating a custom patch of the global WebSocket object, allowing us to hook into WebSocket events and capture the messages sent over them.
Here’s an example:
How does it work?
By overriding the global WebSocket object, you gain control over all WebSocket instances createdAt on the page — including those instantiated by third-party libraries. The key is that this script must run as early as possible in the page’s lifecycle, ideally as the first or one of the first lines of JavaScript executed.
After this, you can create the listeners you want, and even customize them to suit your specific needs.
Examples
Here are a few examples showing how you can monitor WebSocket activity. You can further tailor these examples to suit your specific needs.