簡體   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