Serviceworker Bug event.respondWith

Serviceworker Bug event.respondWith

本文关键字:respondWith event Bug Serviceworker      更新时间:2023-09-26

我的服务工作者的逻辑是,当发生获取事件时,首先它会获取一个包含一些布尔值(不是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))
  );
});

我不太明白你想用你的代码实现什么,但是多次获取,第一次影响第二次的行为,工作正常。