Serviceworker Bug event.respondWith
Serviceworker Bug event.respondWith
我的服务工作者的逻辑是,当发生获取事件时,首先它会获取一个包含一些布尔值(不是event.request.url)的端点,并根据我为当前获取事件调用event.respondWith()的值检查值,我正在从缓存中提供响应。但是我收到以下错误,
未捕获(在承诺中)DOMException:无法在 上执行"响应"。 "FetchEvent":已响应 fetch 事件
我在这里检查了当m_state不等于初始时会抛出此错误
if (m_state != Initial) {
exceptionState.throwDOMException(InvalidStateError, "The fetch event has already been responded to.");
return;
}
我怀疑由于我有一个额外的获取事件,它以某种方式消耗了以前的获取事件,它正在更改m_state变量,尽管我没有获取事件 URL。我不确定可能是什么原因以及解决方案是什么。但为什么这么说
我正在下面粘贴我的代码片段。
function fetchEvt(event) {
check().then(function (status) {
if (status === 0) {
handleRequest(event);
}
});
}
function checkHash() {
return new Promise(function (resolve) {
fetch(endpoint, { credentials: 'include' }).then(function (response) {
return response.text();
}).then(function (text) {
resolve(text);
});
}
}
function handleRequest(event) {
event.respondWith(caches.match(event.request.url).then(function (Response) {
if (Response) {
return Response;
}
return fetch(event.reuqest);
}));
}
event.respondWith 部分正在抛出错误。请建议如何解决此问题。
编辑:
function handleRequest(event) {
event.respondWith(checkHash().then(function (status) {
if (status === true) {
caches.match(event.request.url).then(function (Response) {
if (Response) {
return Response;
}
return fetch(event.reuqest);
});
} else if (status === false) return fetch(event.reuqest);
}));
处理事件时需要同步调用event.respondWith
fetch
。如果您不这样做,浏览器会认为它应该继续处理请求。这就是为什么当你在代码中调用respondWith
时,请求已经处理,并且你看到 fetch 事件已经响应异常。
换句话说:试着在handleRequest
内打电话给你的checkHash
,而不是相反。
Re "因为我有一个额外的获取事件,它以某种方式消耗了以前的获取事件"这应该不是问题; 您可以从fetch
事件处理程序中fetch()
,事情会很好:
self.addEventListener("fetch", e => {
e.respondWith(
fetch("https://fonts.googleapis.com/css?family=Open+Sans")
.then(_ => fetch(e.request))
);
});
我不太明白你想用你的代码实现什么,但是多次获取,第一次影响第二次的行为,工作正常。
相关文章:
- issue with FB.Event.subscribe
- Angularjs :$routeChangeStart event
- event.prventDefault()持续多久
- <text区域>在我的html中包含event.keycode==13之后,wrap就不起作用了
- KeyDown event for CKeditor
- Javascript events: window.event vs argument reference (funct
- 动态填充Bootstrap选择选择器:change event dos'不起作用
- <td> focusin event .addclass
- event.preventDefault阻止ajax调用
- google.maps.event.addDomListener(window, 'load', fun
- jQuery event.target is_a_child_of(element)
- event.stopPropagation()在firefox javascript中不起作用
- asp.net text onkeyup event
- 如何从ondragend获取正确的event.pageX
- 面料:“;鼠标:向下”;在event.target中未返回对象
- 使用event.target.classlist区分按钮颜色
- event.keycode vs event.which
- 将字符串作为参数传递给函数onclick event jquery
- 当使用Jasmine在JS中测试AJAX调用时,.andReturn(..)和.respondWith(
- Serviceworker Bug event.respondWith