Have you considered building a Pluggable Widget instead? This would have access to the Context and you would have more flexibility hooking into page events.
https://docs.mendix.com/howto8/extensibility/create-a-pluggable-widget-one/
Just a thought.