我的代码每5秒检查一次新邮件。当新消息到达时,它会发出推送通知。然而,这次推送仅在我访问Android手机中的页面后几分钟工作(我使用谷歌浏览器)。如果我访问该页面并且有人在10分钟后发送消息,那么在我再次手动进入该网站之前,我不会收到任何通知。任何想法如何在一段时间后获得推送通知?
<script>
function function_update(){
var text='hello world';
$.ajax({
type: "GET",
url: 'jquery_get_data.php',
data: { keyword : text },
success: function(data) {
/* alert(data);*/
if (data.trim()) {
$("#texterna").append(data);
window.scrollTo(0, 10000000);
////Notification start
navigator.serviceWorker.register('sw.js');
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('New message', {
body: 'A new message has been made!',
icon: '/logos/ico_png.png',
badge: '/logos/ico_png.png',
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: 'vibration-sample',
target: 'https://www.example.com/'
});
});
}
});
////Notification ends
}
}
});
}
$(document).ready(function() {
setInterval("function_update()",5000); //call function every 5 seconds.
});
</script>
以下是服务工作者文件的内容&#39; sw.js&#39;
self.addEventListener('notificationclick', function(event) {
let url = 'index.php';
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});