I guess that many people will consider that proposing restrictions for a PWA to be downloaded could not be a good strategic idea but in this concrete project I would need to been able to accomplish exactly that.
I would like to be sure that the user has registered before downloading the PWA and I think the way to go would be to automatically prevent ‘service worker’ to be downloaded and, when detecting user has been registered, allow it to be downloaded.
I would need to block the service worker registering process form a different file that the one that handles it. While I’m using wordpress and SuperPWA plugin I don’t want to change code inside the plugin
I supose my goal would be to block somehow this function
navigator.serviceWorker.register(superpwa_sw.url)
Due to the wordpress specifications it seems that the .js files of the PWA plugin is loaded before the file from where I would like to write the blocking function.
Any clue that could point me in the right direction would be very welcome, thanks!
3
Answers
I found a solution that seems to work.
Unregistering the service worker from another .js file is possible once you re-register it. This way you can get the result of the registering function and use it onwards for unregistering it. Then I can register it again when I check the user is registered and the pwa turns downloable according to it.
You can probably prevent the sendout of the PWA in php, in a little bit of code, with wp_dequeue_script().
The wp_print_scripts action fires just before sending enqueued scripts to the browser page. This code removes the PWA script from the queue.
This is a good approach: it won’t allow your PWA script to go to any not-logged-in visitor, so those visitors won’t have any access to it.
I also tried the solution of @O.jones and it works perfectly. As he says in his comment, this solution seems to be more secure. I changed the function a bit, now it doesn’t only de-register it, but it also registers the script when needed, so I call the function in the header.php and again once detected the user is logged in.