HTML5通知不工作在移动Chrome

HTML5 Notification not working in Mobile Chrome

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

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

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

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

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

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');
    });
  }
});

即使用ServiceWorkerRegistration»showNotification()而不是new Notification()

这应该可以在Android的Chrome和Firefox中工作,也可以在iOS的Safari中工作。

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

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

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

如果你已经注册了一个service worker,请使用:

navigator.serviceWorker.getRegistrations().then(function(registrations) {
  registrations[0].showNotification(title, options);
});

运行以下代码:

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

Chrome DevTools控制台显示此错误:

Uncaught TypeError: Failed to construct ' Notification ': Illegal构造函数。使用ServiceWorkerRegistration.showNotification()代替

一个更好的方法可能是:

function isNewNotificationSupported() {  
    if (!window.Notification || !Notification.requestPermission)  
        return false;  
    if (Notification.permission == 'granted')  
        throw new Error('You must only call this '*before'* calling 
Notification.requestPermission(), otherwise this feature detect would bug the 
user with an actual notification!');  
    try {  
        new Notification('');  
    } catch (e) {  
        if (e.name == 'TypeError')  
            return false;  
    }  
    return true;  
}

函数来源:HTML5Rocks

我在Windows Desktop上使用通知API没有任何问题。它甚至在Mobile FF上也没有任何问题。我找到了文档,似乎表明Android也支持Chrome,但它不适合我。我真的很想证明这个API可以在我当前(2019)版本的Android Chrome(70)上为我工作。经过大量调查,我很容易明白为什么许多人的结果好坏参半。当我将上面的答案粘贴到一个barebones页面时,它根本不适合我,但是我发现了原因。根据Chrome调试器,通知API只允许响应用户手势。这意味着不能在文档加载时简单地调用通知。相反,您必须调用代码来响应用户交互(如单击)。

所以,这里是一个基本的和完整的解决方案,证明你可以得到通知工作在当前(2019)Chrome for Android(注:我使用jQuery只是为了简洁):

<html>
<head>
<script type="text/javascript" src="libs/jquery/jquery-1.12.4.min.js"></script>
<script>
$( function()
{
    navigator.serviceWorker.register('sw.js');
    $( "#mynotify" ).click( function()
    {
        Notification.requestPermission().then( function( permission )
        {
            if ( permission != "granted" )
            {
                alert( "Notification failed!" );
                return;
            }
            navigator.serviceWorker.ready.then( function( registration )
            {
                registration.showNotification( "Hello world", { body:"Here is the body!" } );
            } );
        } );
    } );
} );
</script>
</head>
<body>
<input id="mynotify" type="button" value="Trigger Notification" />
</body>
</html>

总之,关于当前(2019)Chrome for Android的通知需要了解的重要事项:

  1. 必须使用HTTPS
  2. 必须使用通知API来响应用户交互
  3. 必须使用通知API请求通知权限
  4. 必须使用ServiceWorker API来触发实际的通知

new Notification('your arguments');
这种创建通知的方式只支持桌面浏览器,不支持移动浏览器。根据下面的链接。(向下滚动到兼容性部分)
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

对于移动浏览器,下面是创建通知的方法(这也适用于桌面浏览器)

navigator.serviceWorker.ready.then( reg => { reg.showNotification("your arguments goes here")});

在使用webkit引擎的浏览器上测试。

更多信息请访问以下链接:
https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notificationshttps://developers.google.com/web/fundamentals/push-notifications/display-a-notification