私の意見では、通知はWebサイトをアプリから分離する主要な機能の1つであり、特にプログレッシブWebアプリケーション(PWA)が大流行している今ではなおさらです。 したがって、通知が表示されると、サイトはネイティブアプリのように感じられます。

NotificationsAPIのインターフェースはJavaScriptを介しています Notification 多くのプロパティを持つオブジェクト。 ビジュアルプログラマティック、単なるメタデータ、オーディオセンサーなどがあります。

視覚的なプロパティは次のとおりです。

const notificationsProperties = {
  "title": "Picture Time",
  "body": "Time to look at some random pictures",
  "icon": "https://picsum.photos/200",
  "image": "https://picsum.photos/400",
  // A badge is an image we display
  // when there is not enough space to display the notification
  "badge": "https://picsum.photos/300/200",
  // Direction decides if the notification goes
  // from left to right, right to left or let the browser decide
  "dir": "ltr",
  // As part of the direct user experience we also have 
  // Audio- ....
  "silent": ""
  // ... sensorial
  "vibrate": [200, 100, 200],
}

title, body, icon, imagebadge 使用しているオペレーティングシステムによって、すべての外観が異なります。 Windows10での表示は次のとおりです。


それでは、よりプログラム的なプロパティを見てみましょう(私の分類については、私もあまり満足していません🤓を批判してください)。

{
  //...
  onshow: () => console.log("We are showing a Notification"),
  onerror: () => console.log("There was an error showing a Notification"),
  onclose: () => console.log("Closing the Notification"),
  // Informs the user if a notification replaced a previous one
  renotify: null,
  // If set to true the notification will stick to the screen until the user interacts with it
  requireInteraction: true,
  // We'll get into actions later
  actions: []
}

ここでは、メタデータを使用して何ができるかについては説明しません。 しかし、ここではそれらは適切な測定のためのものです:

{
  "lang": "",
  "tag": "",
  "timestamp": 1581390179474,
  "data": null
}

通知の作成

通知の内容がわかったところで、通知を作成する方法を見てみましょう。

const notification = new Notification('Stop Working', notificationsProperties);

終わり! とても簡単です。 しかし、2つの重要なことがあります。

  • 最初のものはそれほど重要ではありません。 スクリーンショットで、通知のタイトルが StopWorkingであることに気付いたかもしれません。 しかし、私たちのオプションでは、次のように設定します。 "title": "Picture Time". これは、タイトルは、「StopWorking」として設定した通知コンストラクターでのみ設定できるためです。
  • 2番目に重要なこと。 ユーザーに通知を強制することはできません。 最初に彼らの許可を得る必要があります。 パーミッションについて詳しく知りたい場合は、(パーミッションAPI)[/ js /permits-api/]に関する記事を確認してください。

許可を求めることに対処するための短いスニペットは次のとおりです。

// Checking if we already have permission to send notifications
const notificationsAllowed = await navigator.permissions.query({name: 'notifications'});

if (notificationsAllowed.state !== 'granted'){
  // Requesting permission
  const permission = await Notification.requestPermission();

  // If the permission is not granted the application won't work
  if (permission !== 'granted') {
    // I am a very sour developer so I replace all of my page with an error message
    // DON'T DO LIKE ME AND BE A FRIENDLY DEV INSTEAD!
    document.body.innerHTML = '<h1> This app can\'t work without notification bye </h1>';
    return;
  }
}
// Then you can continue with your notification driven code

次のコマンドを実行して、通知ステータスを取得することもできます。

const notificationsAllowed = Notification.permission;

行動

アクションは、通知の下部にある小さなボタンです。 それらを次のように定義できます。

actions: [{
  title: 'Show More',
  action: () => {console.log('code to show more images');}
},{
  title: 'Close',
  action: () => { console.log('Bye bye');}
}]

ただし、以前のように通知オプションにアクションを追加することはできません。 サービスワーカーにのみ登録できます。

モジュール:main.js
if('serviceWorker' in navigator) {
  // First we need to register our service worker
  navigator.serviceWorker.register('serviceWorker.js', { scope: './' })
    .then(async () => {
      //... check if notifications are allowed
      // ... define notificationsProperties with actions
      const serviceWorkerRegistration = navigator.serviceWorker.ready
      // This will show the notification with the actions
      serviceWorkerRegistration.showNotification('Stop Working', notificationsProperties);
    });
}

そして、オフラインでも機能する通知があります。


Service Worker内で、イベントリスナーを登録して、ユーザーが通知をどのように操作するかを確認できます。

モジュール:serviceWorker.js
self.addEventListener('notificationclick', (event) => {
    console.log('our user clicked on the notification!')
    // Send user data analytics 🔥 🔥 🔥
}, false);

そして、あなたはそこにいます! あなたがいくつかのトリックを学び、ネイティブな感じのいくつかの派手なウェブサイト/ウェブアプリを開発することを願っています✨。