Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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);
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda