簡體   English   中英

在服務工作者的單個提取請求中僅獲取 HTML

[英]Get only HTML in single fetch request in service worker

我正在使用 Cloudflare 服務人員,我希望在每個請求中:

  1. 僅請求 HTML (因此僅計為 1 個請求)
  2. 在響應中搜索字符串
  3. 如果消息存在,則清除該頁面的緩存

我已經解決了第 2 點和第 3 點。 無法弄清楚#1是否可行或可能。

我只需要一個請求,因為每天的免費請求數量是有限制的。 否則我每頁大約有 50-60 個請求。

我目前對 #1 的嘗試,但不能正常工作:

async function handleRequest(request) {
  const init = {
    headers: {
      'content-type': 'text/html;charset=UTF-8',
    },
  };
  const response = await fetch(request);
  await fetch(request.url, init).then(function(response) {
    response.text().then(function(text) {
    console.log(text);
})
  }).catch(function(err) {
      // There was an error
      console.warn('Something went wrong.', err);
    });
return response;
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
});

您不能請求“僅 html”,工作人員將對與其部署的路線匹配的任何請求采取行動。 如果您只關心 html,您將需要設置您的工作程序路徑以僅過濾到您想要運行工作程序的端點。

或者,您可以在每個請求上使用工作人員,並且僅在響應 Content-Type 是您關心的內容時才執行您的邏輯。 這將是這樣的:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
})

async function handleRequest(request) {
  let response = await fetch(request);

  let type = response.headers.get("Content-Type") || "";
  if (type.startsWith("text/")) {
    //this is where your custom logic goes
  }
  return response;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM