_original_send = BaseComm.send
def _patched_send(self, data=None, metadata=None, buffers=None):
widget = widget_module._instances.get(self.comm_id)
widget_type = type(widget).__name__ if widget else "Unknown"
print(f"Comm message sent by {widget_type} ({self.comm_id}): {data}")
_original_send(self, data, metadata, buffers)
BaseComm.send = _patched_send # type: ignoreComm
Exploring Comm API to intersept their messages
Ipykernel employs the Comm class for facilitating communication between the front-end and back-end. It builds on a base Comm implementation, which includes a send function for messaging the front-end. Monkey-patching this send function presents a direct approach to intercept Comm communications.
Testing
The following cells displays ipywidgets and solara example of monitoring state changes. Interact with the following widgets to intercept its state changes.
slider = widgets.IntSlider(value=7, min=0, max=10, step=1, description='Test Slider:')
display(slider)int_value = solara.reactive(42)
solara.SliderInt("Another Test Slider:", value=int_value, min=-10, max=120)