简体   繁体   English

HTML5 通知在移动 Chrome 中不起作用

[英]HTML5 Notification not working in Mobile Chrome

I'm using the HTML5 notification API to notify the user in Chrome or Firefox.我正在使用HTML5 通知 API在 Chrome 或 Firefox 中通知用户。 On desktop browsers, it works.在桌面浏览器上,它可以工作。 However in Chrome 42 for Android, the permission is requested but the notification itself is not displayed.但是在 Android 的 Chrome 42 中,请求了权限,但不显示通知本身。

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

Try the following: 请尝试以下方法:

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

That should work on Android both in Chrome and in Firefox (and on iOS in Safari, too). 这应该适用于Android的Chrome和Firefox(以及Safari中的iOS)。

(The sw.js file can just be a zero-byte file.) sw.js文件只能是一个零字节文件。)

One caveat is that you must run it from a secure origin (an https URL, not an http URL). 需要注意的是,您必须从安全的来源( https URL,而不是http URL)运行它。

See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification . 请参阅https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification

Running this code: 运行此代码:

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

Console in Chrome DevTools shows this error: Chrome DevTools中的控制台显示以下错误:

Uncaught TypeError: Failed to construct 'Notification': Illegal constructor. 未捕获的TypeError:无法构造“通知”:非法构造函数。 Use ServiceWorkerRegistration.showNotification() instead 请改用ServiceWorkerRegistration.showNotification()

A better approach might be: 更好的方法可能是:

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

Function Source: HTML5Rocks 功能来源: HTML5Rocks

I had no trouble with the Notification API on Windows Desktop. 我在Windows桌面上使用Notification API没有遇到任何问题。 It even worked without issues on Mobile FF. 它甚至在Mobile FF上没有问题。 I found documentation that seemed to indicate Chrome for Android was supported too, but it didn't work for me. 我发现文档似乎表明Chrome for Android也受支持,但它对我不起作用。 I really wanted to prove the API could work for me on my current (2019) version of Chrome (70) for Android. 我真的想证明API可以在我目前的(2019)版Chrome(70)for Android上使用。 After much investigation, I can easily see why many people have had mixed results. 经过多次调查,我很容易看出为什么很多人的结果好坏参半。 The answer above simply didn't work for me when I pasted it into a barebones page, but I discovered why. 当我将它粘贴到准系统页面时,上面的答案对我来说根本不起作用,但我发现了原因。 According to the Chrome debugger, the Notification API is only allowed in response to a user gesture. 根据Chrome调试程序,仅允许Notification API响应用户手势。 That means that you can't simply invoke the notification when the document loads. 这意味着您无法在文档加载时简单地调用通知。 Rather, you have to invoke the code in response to user interactivity like a click. 相反,您必须调用代码以响应用户交互,如点击。

So, here is a barebones and complete solution proving that you can get notifications to work on current (2019) Chrome for Android (Note: I used jQuery simply for brevity): 所以,这里有一个准系统和完整的解决方案,证明你可以获得通知工作当前(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>

In summary, the important things to know about notifications on current (2019) Chrome for Android: 总之,关于当前(2019)Chrome for Android的通知需要了解的重要事项:

  1. Must be using HTTPS 必须使用HTTPS
  2. Must use Notification API in response to user interactivity 必须使用Notification API来响应用户交互性
  3. Must use Notification API to request permission for notifications 必须使用Notification API来请求通知权限
  4. Must use ServiceWorker API to trigger the actual notification 必须使用ServiceWorker API来触发实际通知

If you already have a service worker registered, use this: 如果您已经注册了服务工作者,请使用以下命令:

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

new Notification('your arguments');
This way of creating notification is only supported on desktop browsers, not on mobile browsers.仅桌面浏览器支持这种创建通知的方式,移动浏览器不支持。 According to the link below.根据下面的链接。 (scroll down to the compatibility part) (向下滚动到兼容性部分)
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

For mobile browsers below is the way you create a notification (this also works on desktop browsers)对于移动浏览器,以下是您创建通知的方式(这也适用于桌面浏览器)

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

Tested on browsers using webkit engine.在使用 webkit 引擎的浏览器上测试。

For more information please visit below links:欲了解更多信息,请访问以下链接:
https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications https://developers.google.com/web/fundamentals/push-notifications/display-a-notification https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications https://developers.google.com/web/fundamentals/push-notifications/display-a -通知

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM