我正试图在chrome上创建一个推送通知系统。我有一个php,它从mysql中获取数据并返回JSON,现在我想调用一个函数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');
}
是否可以在服务工作者中调用这样的外部文件,或者是否存在某种限制?因为我不明白为什么不起作用
您可以使用新的Fetch API来代替XMLHttpRequest
。XMLHttpRequest
已被弃用,在服务工作者作用域中不可用。
在这个ServiceWorker食谱中有一个你想要实现的目标的例子。
您可以使用fetch()代替XHR,因为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
});
}));
});