简体   繁体   中英

Get only HTML in single fetch request in service worker

I'm using Cloudflare service workers and I want on every request to:

  1. request only the HTML (therefore count as only 1 request)
  2. search the response for a string
  3. Purge that page's cache if the message exists

I've solved points #2 and #3. Can't figure out if #1 is feasible or possible at all.

I need it as only one request because there is a limit per day on the number of free requests. Otherwise I have about 50-60 requests per page.

My current attempt for #1, which doesn't work right:

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))
});

You can't request "only the html", the worker will act on any request that matches the route that it is deployed at. If you only care about the html, you will need to set up your worker path to filter to only the endpoints that you want to run the worker on.

Alternatively you can use the worker on every request and only do your logic if the response Content-Type is one that you care about. This would be something along these lines:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM