eli*_*nti 4 php json push-notification google-cloud-messaging service-worker
我正在尝试在chrome上创建推送通知系统.我有一个从mysql获取数据并回显JSON的php,现在我想调用一个函数getJsonCode(),它在推送通知到达时被激活并读取JSON数据.
在我的服务工作者中,我创建了标准函数.问题是,当我使用XMLHttpRequest创建getJsonCode时,它告诉我它没有定义
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
console.log('Activated', event);
});
self.addEventListener('push', function(event) {
console.log('Push message', event);
getJsonCode();
);
})
getJsonCode() {
codeRequest= new XMLHttpRequest();
codeRequest.open('get', 'myfileWithJson.php', true);
codeRequest.send();
dataJSON = codeRequest.responseText;
console.log('rispostaJSON');
}
Run Code Online (Sandbox Code Playgroud)
是否可以在服务工作者中调用这样的外部文件,或者是否存在某些限制?因为我不知道为什么这不起作用
XMLHttpRequest您可以使用新的Fetch API代替.XMLHttpRequest已弃用,在服务工作者范围内不可用.
这个ServiceWorker Cookbook配方中有一个确切想要实现的示例.
您可以使用 fetch() 而不是 XHR,因为 fetch() 是一个新的 API,它允许您发出类似于 XHR 的请求,但具有更简单/友好的 API。在此处阅读有关 fetch 的更多信息。尝试这个:-
self.addEventListener('push', function(event) {
console.log('Push message', event);
event.waitUntil(
fetch('/myfileWithJson.php').then(function(response){
return response.json();
}).then(function(data){console.log(data);
return self.registration.showNotification(data.title, {
body: data.body,
icon: 'images/icon.png',
tag: data.url
});
}));
});
Run Code Online (Sandbox Code Playgroud)