Hi Stephan,
I'd try to implement a local plugin. This type supports different callback methods called from the moodle setup.php.
https://docs.moodle.org/dev/Callbacks
This way you can check the context, the page actually runs and inject you javascript.
I hope this helps.
Best regards
Andreas