You may find it easier to write a Pluggable Widget to do this.
You’ll need to add the event listener when the widget is mounted so you know it’s visible on the current page. You’ll also want to remove the event listener when the widget is unmounted, as this means it no longer available on the current page.
https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets
Hope this helps