简体   繁体   中英

Use Cloudflare HTMLRewriter to modify multiple different element types

I'd like to use Cloudflare's HTMLRewriter to modify a <p> tag with some text, and modify an <img> tag with a different src.

I've read the docs here: https://developers.cloudflare.com/workers/runtime-apis/html-rewriter but I cannot find any examples addressing re-writing multiple different elements.

I'm using Cloudflare Pages Functions so as far as I can tell I do need to do all of this in the same file.

My code currently looks like this, to just do the re-write on the <p> tag. It works, but I'd like to update a weather icon as well in the menu bar.

// ./functions/index.js

export const onRequestGet = async ({ request, next }) => {

try{
  // Get the static asset response
  const response = await next()

  const { latitude, longitude, city, country, timezone } = request.cf

    let endpoint = "https://api.openweathermap.org/data/2.5/weather?"

    endpoint += "lat=" + latitude + "&lon=" + longitude + "&appid=APPID"

    const init = {
    headers: {
    //  "User-Agent" : "EMAIL",

    },
  }

  const responseWeather = await fetch(endpoint,init)
  const content = await responseWeather.json()

  const currd = new Date()


  var humanTime = currd.toLocaleTimeString('en-US', { timeZone: timezone })

  //Get the value from the object
  const currentTempC = content.main.temp
  const weatherDescription = content.weather[0].description
  const currentTempF = Math.round(((9/5)* (currentTempC - 273)) + 32)

  var currentTempLocal
  var degreesSymbol

  switch(country) {
    case "US":
    case "BS":
    case "KY":
    case "LR":
    case "PW":
    case "FM":
    case "MH":
      currentTempLocal = currentTempF
      degreesSymbol = "°F"
      break;
    default:
      currentTempLocal = currentTempC
      degreesSymbol = "°C"
      break;
  }


  // US BS KY LR PW FM MH

  const weatherString = "At " + humanTime + " in " + city + "there's " + weatherDescription + " and the temperature is " + currentTempLocal + degreesSymbol + "."

  // var errorReport = timezone + "\n" + humanTime + "\n" + JSON.stringify(context)

  // Find the placeholder in our static asset
  return new HTMLRewriter().on('#weather', {
    // And act on the element
    element(element) {
      // https://developers.cloudflare.com/workers/runtime-apis/html-rewriter#methods
      element.setInnerContent(weatherString, { html: true })
    }
  }).transform(response)
  } catch (thrown){
      return new Response(thrown);
  }
}

This should be as simple as chaining another .on method to your HTMLRewritter like so -

return new HTMLRewriter().on('#weather', {
element(element) {
  // first handler
}).on('img', {
element(element) {
  // second handler
}).transform(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