过去几个小时我一直在阅读推送通知API和Web通知API。我还发现谷歌和苹果分别通过GCM和APNS提供免费的推送通知服务。
我正在尝试了解我们是否可以使用桌面通知实现浏览器推送通知,我相信这是Web通知API所做的。我看到了一个谷歌文档关于如何为Chrome在这里和这里。
现在我还不明白的是:
我们是否可以使用GCM/APNS向包括Firefox和Safari在内的所有Web浏览器发送推送通知?
如果不通过GCM,我们可以有自己的后端来做同样的事情吗?
我相信所有这些答案都可以帮助很多有类似困惑的人。
我可以重新定义你的问题如下吗
我们可以有自己的后端发送推送通知Chrome, Firefox, Opera和Safari?
是的。到今天(2017/05),您可以使用相同的客户端和服务器端实现来处理Chrome, Firefox和Opera(没有Safari)。因为他们以同样的方式实现了web推送通知。这是W3C的Push API协议。但是Safari有自己的旧架构。我们需要单独维护Safari。
参考browser-push repo指南线实现web推送通知你的web应用程序与你自己的后端。它通过示例解释了如何在没有任何第三方服务的情况下为您的web应用程序添加web推送通知支持。
我可以重新定义你的问题如下吗
我们可以有自己的后端发送推送通知Chrome, Firefox, Opera和Safari?
是的。到今天(2017/05),您可以使用相同的客户端和服务器端实现来处理Chrome, Firefox和Opera(没有Safari)。因为他们以同样的方式实现了web推送通知。这是W3C的Push API协议。但是Safari有自己的旧架构。我们需要单独维护Safari。
参考browser-push repo指南线实现web推送通知你的web应用程序与你自己的后端。它通过示例解释了如何在没有任何第三方服务的情况下为您的web应用程序添加web推送通知支持。
这里有一个完整的html工作示例。
只需要替换图像,文本,就可以了!
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="icon" href="favicon.ico" type="image/png">
<title>Push</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="centrado">
<div class="card text-center shadow">
<div class="card-header">
Push Notifications
</div>
<div class="card-body">
<h5 class="card-title">Test for Push Notifications</h5>
<p class="card-text">Click twice, first for the permission</p>
<button class="btn btn-danger" id="btn-show-notification">Notify</button>
</div>
<div class="card-footer text-muted">
aledc7
</div>
</div>
</div>
</body>
<script>
$(document).ready(function () {
$(document).on('DOMContentLoaded', function () {
// Request desktop notifications permission on page load
if (!Notification) {
console.log('Notification is not compatible');
return;
}
if (Notification.permission !== 'granted') {
Notification.requestPermission();
}
});
function showNotification() {
if (Notification.permission !== 'granted') {
Notification.requestPermission();
} else {
const options = {
body: 'Your text for the Notification,
dir: 'ltr',
image: 'your_image.png' //must be 728x360px
};
const notification = new Notification('Title Notification', options);
notification.onclick = function () {
window.open('https://stackoverflow.com/users/10220740/ale-dc');
};
}
}
$('#btn-show-notification').on('click', showNotification);
});
</script>
<style>
.centrado{
/* Centrado Horizontal */
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
/* Centrado Vertical */
margin: 0;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
.shadow{
filter: drop-shadow(2px 4px 8px #585858);
}
</style>
</html>