繁体   English   中英

使用 Cloudflare HTMLRewriter 修改多种不同的元素类型

[英]Use Cloudflare HTMLRewriter to modify multiple different element types

我想使用 Cloudflare 的 HTMLRewriter 修改带有一些文本的 <p> 标签,并使用不同的 src 修改 <img> 标签。

我在这里阅读了文档: https://developers.cloudflare.com/workers/runtime-apis/html-rewriter但我找不到任何解决重写多个不同元素的示例。

据我所知,我正在使用 Cloudflare Pages Functions,我确实需要在同一个文件中执行所有这些操作。

我的代码目前看起来像这样,只需在 <p> 标记上进行重写。 它可以工作,但我也想在菜单栏中更新天气图标。

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

这应该就像将另一个.on方法链接到您的HTMLRewritter一样简单,如下所示 -

return new HTMLRewriter().on('#weather', {
element(element) {
  // first handler
}).on('img', {
element(element) {
  // second handler
}).transform(response)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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