How to add a service worker to Nextcloud? / Inject JavaScript file on every page

Hey their,

does anybody know how I could add a JavaScript file on every (internal) page of a NextCloud? I like to speed up my NextCloud instance with my own service worker and therefore I have to put it on every possible (internal) page of NextCloud. I found something like emit_script_loading_tags($_) in e.g. core/templates/layout.user.php but it seems to be legacy.

But is there any newer option and how can I add my own scripts there?

Thanks a lot!

AFAIK @skjnldsv uses service workers in the Viewer app: https://github.com/nextcloud/viewer/

Hey there, thank you for your answer. I quick-checked the repository and could not find any use of a service worker there, unfortunately. Since you develop the main app of NextCloud, any other ideas how I could add a script on every page in NextCloud?

Yes, you can use the \OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent event for this. Are you familiar with the event dispatcher? Here’s the docs: Events — Nextcloud latest Developer Manual latest documentation

1 Like

Thanks again, and yes, I am familiar with the event dispatcher, kind of. But I am not familiar with code inject outside of any app. Now I don’t know where to fire the BeforeTemplateRenderedEvent. Or can I write an app with the only reason to exist, that it fires the event? Can I do this?

Sorry for my dumb questions, but NextCloud development is kind of a riddle for me, because it’s a very complex codebase.

No worries.

You don’t have to fire the event. But you listen to it and in your listener you include the script that loads the service worker with \OCP\Util::addScript. Is that now what you were asking for?

2 Likes

You know what? I just try it myself and if I reach a point where new questions arise I will come back. Thanks so far!

2 Likes

Sorry for the delay
We use it in photos, not viewer

2 Likes

As I planed to do the same thing and newer got to a working version:

Did you manage to get it working?
I think it would be perfect do be able to do some work in the clients of the users with a little app.

If you found this thread and look for an answer: