HTML5 通知在移动 Chrome 中不起作用 [英] HTML5 Notification not working in Mobile Chrome

查看:30
本文介绍了HTML5 通知在移动 Chrome 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HTML5 通知 API 来通知Chrome 或 Firefox 中的用户.在桌面浏览器上,它可以工作.但是,在 Android 版 Chrome 42 中,会请求权限,但不会显示通知本身.

I'm using the HTML5 notification API to notify the user in Chrome or Firefox. On desktop browsers, it works. However in Chrome 42 for Android, the permission is requested but the notification itself is not displayed.

请求代码,适用于所有设备:

The request code, works on all devices:

if ('Notification' in window) {
  Notification.requestPermission();
}

发送代码,适用于桌面浏览器,但不适用于移动设备:

The sending code, works on desktop browser but not on mobile:

if ('Notification' in window) {
  new Notification('Notify you');
}

推荐答案

尝试以下操作:

navigator.serviceWorker.register('sw.js');
Notification.requestPermission(function(result) {
  if (result === 'granted') {
    navigator.serviceWorker.ready.then(function(registration) {
      registration.showNotification('Notification with ServiceWorker');
    });
  }
});

这应该适用于 Android 的 Chrome 和 Firefox(以及 iOS 的 Safari).

That should work on Android both in Chrome and in Firefox (and on iOS in Safari, too).

(sw.js 文件可以是一个零字节文件.)

(The sw.js file can just be a zero-byte file.)

一个警告是,您必须从安全来源(https URL,而不是 http URL)运行它.

One caveat is that you must run it from a secure origin (an https URL, not an http URL).

参见 https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification.

这篇关于HTML5 通知在移动 Chrome 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆