HTML5通知与服务工作者在Chrome移动不工作

HTML5 Notifications with Service Workers on Chrome Mobile not working

本文关键字:Chrome 移动 工作 工作者 通知 服务 服务工作 HTML5      更新时间:2023-09-26

我在我的应用程序中使用HTML5桌面通知。但我有一个问题与谷歌Chrome手机。据我所知,我需要使用Service Workers在Chrome Mobile上创建一个新的通知,因为浏览器对它们的处理方式不同(HTML5通知不适用于移动Chrome)。我试图整合的例子(和一些更多的变化)以下堆栈溢出问题,但我不能让它运行。他从来没有到达serviceWorker中的. shownotification方法。我以前从来没有和服务工作者一起工作过,所以我不知道我需要做什么,才能让他们工作。我需要把这个sw.js文件在项目的某个地方吗?我的应用程序是一个Java Spring项目,我不知道我将不得不把这个。js文件。我将它放在项目的根目录中,并将其放在包含此代码的文件所在的同一目录中,但没有区别。如果有人能帮我,那就太好了。如果需要更多的代码或项目结构来回答问题,我可以提供更多。

if (!("Notification" in window)) {
  //
} else if (Notification.permission === "granted") {
  var localUserSettings = new LocalUserSettings(loggedInUser);
  if (localUserSettings.notificationRights == "granted") {
    try {
      var notification = new Notification(s, {
        body: t,
        icon: "/image/" + id,
        lang: "de",
        tag: notificationId
      });
      setTimeout(function () {
        notification.close();
      }, 10000);
    } catch (e) {
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js').then(function (registration) {
          registration.showNotification(s, {
            body: t,
            icon: "/image/" + id,
            vibrate: [200, 100, 200, 100, 200, 100, 200],
            tag: notificationId
          });
        });
      }
    }
  }
}

谢谢:)

编辑:是的,我从一个安全的来源(https)运行代码

确保首先通过在Notification对象上调用requestPermission()来请求权限,如下所示:

Notification.requestPermission();