Service Worker 中的 XMLHttpRequest
XMLHttpRequest within service worker
我正在尝试在 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');
}
是否可以在 service worker 中调用这样的外部文件,或者是否存在某种限制?因为我不明白为什么这不起作用
您可以使用新的 Fetch API 而不是 XMLHttpRequest
。 XMLHttpRequest
已被弃用,在服务工作者范围内不可用。
中有一个您想要实现的确切示例
您可以使用 fetch() 而不是 XHR,因为 fetch() 是一个新的 API,它允许您发出类似于 XHR 的请求,但更简单/友好 API.Read获取 here。试试这个:-
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
});
}));
});
我正在尝试在 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');
}
是否可以在 service worker 中调用这样的外部文件,或者是否存在某种限制?因为我不明白为什么这不起作用
您可以使用新的 Fetch API 而不是 XMLHttpRequest
。 XMLHttpRequest
已被弃用,在服务工作者范围内不可用。
您可以使用 fetch() 而不是 XHR,因为 fetch() 是一个新的 API,它允许您发出类似于 XHR 的请求,但更简单/友好 API.Read获取 here。试试这个:-
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
});
}));
});