Service Worker 和 AJAX
Posted
技术标签:
【中文标题】Service Worker 和 AJAX【英文标题】:Service Worker and AJAX 【发布时间】:2016-07-15 09:53:23 【问题描述】:我正在尝试使用 AJAX 来检索我想在用户端显示的推送通知的详细信息,但它还不起作用。
/*
*
* Push Notifications codelab
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
// Version 0.1
//'use strict';
console.log('Started', self);
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);
var title = 'Push message';
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://www.domain.nl/devtest/1.php", false);
xhttp.send();
title = xhttp.responseText;
event.waitUntil(
self.registration.showNotification(data,
'body': 'The Message',
'icon': 'images/icon.png'
)
);
);
当我使用 GCM 向客户端发送推送通知时,Chrome 会在 service worker 上显示此错误:
sw.js:39 Uncaught ReferenceError: XMLHttpRequest is not defined
【问题讨论】:
XMLHttpRequest within service worker的可能重复 【参考方案1】:XMLHttpRequest
已被弃用,并且在 Service Worker 范围内不可用。您可以使用Fetch API
,而不是XMLHttpRequest
。
【讨论】:
他们认真地从 service worker 中移除了常规的 ajax?怎么回事?看来我不会用很久了。 @MichaelHanon,是的,这是唯一的方法。另见***.com/a/46727718/632951 fxsitecompat.com/en-CA/docs/2015/… Fetch API 因本地主机上的自签名 SSL 失败 (lol)【参考方案2】:为此,我们可以在 fetch() 选项中设置方法和主体参数。
fetch(url,
method: 'post',
headers:
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
,
body: 'foo=bar&lorem=ipsum'
)
.then(json)
.then(function (data)
console.log('Request succeeded with JSON response', data);
)
.catch(function (error)
console.log('Request failed', error);
);
如果您想使用 cookie 等凭据发出获取请求,则应将请求的凭据设置为“包含”。
fetch(url,
credentials: 'include'
)
【讨论】:
有没有办法添加类似于 Ajax 的不记名令牌,您可以在其中添加此 beforeSend:function (xhr) xhr.setRequestHeader('Authorization', 'Bearer' + apiAuthToken); ,以上是关于Service Worker 和 AJAX的主要内容,如果未能解决你的问题,请参考以下文章