Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I pass or post params to sevirce worker on register or install? #1441

Closed
mkkeck opened this issue Jun 23, 2019 · 3 comments
Closed

Comments

@mkkeck
Copy link

mkkeck commented Jun 23, 2019

Hi all,
I have a multi lingual website and my assets (js, css, fonts) are versioned (e.g. js-3.1.7/lib/file.js).
I've tried to use after serviceWorker.register to postMessage({comand:"install",version:"3.1.7", language:"en"}), and in sw.js to add an event listener for message. In that event I check for the comand. Then I try in the event listener for install to build my assets to cache, e.g.

  • js-{version}/lib/file.js
  • js-{version}/locale/locale-{language}
    and my cache name should become
  • "cache-{version}" for the cacheApi.

But it won't work. I think the event listener for message is not fired when install /register is fired?

How can I fix this. URL-Searchparams may be not a good alternative, because with search params I may register new sw on each language change?

Many thanks.
Michael

@jakearchibald
Copy link
Contributor

How about this:

HTML:

<!DOCTYPE html>
<h1>See console</h1>
<script>
  navigator.serviceWorker.register('sw.js').then(reg => {
    reg.installing.postMessage({ type: 'install-data', value: 'hello!' });
  });
</script>

sw.js:

addEventListener('install', event => {
  event.waitUntil(async function() {
    const value = await installData;
    console.log('Service worker saw data:', value);
  }());
});

const installData = new Promise(resolve => {
  addEventListener('message', (event) => {
    if ('type' in event.data && event.data.type === 'install-data') {
      resolve(event.data.value);
    }
  });
});

Live example: https://static-misc.glitch.me/sw-postmessage-install/

Please reopen if this doesn't help.

@mkkeck
Copy link
Author

mkkeck commented Jun 24, 2019

Okay, I see and it worked. Thanks a lot.
But how can I rewrite your sw.js that it is not using async/await? I get errors with uglify.js. Or have I to modify my uglify.js-configs?
Many thanks.

@mkkeck
Copy link
Author

mkkeck commented Jun 24, 2019

Solved.
Many thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants