3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

igataをPWA化する4

Posted at

はじめに

結局今回もアプリの中身には入らずにプッシュ通知の実装をしました。

参照

以下のサイトを参考に進めました。

内容

プッシュ通知はGoogleChromeのDevToolsを使って試しました。
スクリーンショット 2020-02-25 10.23.18.png
写真のPushというボタンを押したら
スクリーンショット 2020-02-25 10.27.38.png
こんな感じでメッセージを受信できるようにします。

template.htmlを拡張

template.html<script>を拡張してpushメッセージを受信できるようにします。

src/assets/html/template.html
<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
      .register('sw.js')
      .then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope)
        registration.pushManager.subscribe({userVisibleOnly: true})
      })
      .catch(function(err) {
        console.log('ServiceWorker registration failed: ', err)
      })
  }
</script>

加えたのはregistration.pushManager.subscribe({userVisibleOnly: true})だけです。

webpack.common.jsを改造

WorkboxWebpackPlugin.generateSWをやめてWorkboxWebpackPlugin.InjectManifestを使うようにします。プッシュ通知のロジックをsw.js(自動生成されるServiceWorkerのスクリプト)に付け足す必要があるからです。pluginsをこんな感じで書き換えます。

webpack.common.js
const plugins = [
  new HtmlWebpackPlugin({
    favicon: param.faviconPath,
    templateParameters: { title: param.title },
    template: param.templatePath,
  }),
  new MiniCssExtractPlugin({
    filename: '[name].css',
    chunkFilename: '[id].css',
  }),
  new WorkboxWebpackPlugin.InjectManifest({
    swSrc: param.swSrcPath,
    swDest: 'sw.js',
  }),
  new CopyWebpackPlugin(['src/assets/manifest/manifest.webmanifest']),
]

このswSrcのパスで指定したスクリプトを土台にsw.jsを自動生成します。土台となるスクリプトをこんな感じで実装します。

src/assets/javascript/sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js')

workbox.core.skipWaiting()
workbox.core.clientsClaim()

self.addEventListener('push', event => {
  const title = 'Get Started With Workbox'
  const options = {
    body: event.data.text(),
  }
  event.waitUntil(self.registration.showNotification(title, options))
})

workbox.precaching.precacheAndRoute(self.__WB_MANIFEST)

さいごに

また今回もアプリ開発をしませんでしたが、気楽に進めて行きたいと思います。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?