You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Cloudflare HTMLRewriter修改p、img等多种不同类型HTML元素

实现方案

Cloudflare HTMLRewriter 支持链式调用多个 .on() 方法,每个方法可绑定不同的元素选择器和对应的处理逻辑,你可以直接在现有代码基础上追加需要处理的元素规则即可,所有逻辑无需拆分,符合Pages Functions单文件实现要求。

修改后的完整代码

// ./functions/index.js
export const onRequestGet = async ({ request, next }) => {
  try{
    // 获取静态资源响应
    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()
    const humanTime = currd.toLocaleTimeString('en-US', { timeZone: timezone })

    // 提取天气接口返回字段
    const currentTempC = content.main.temp
    const weatherDescription = content.weather[0].description
    const weatherIcon = content.weather[0].icon // 新增:获取天气图标编码
    const currentTempF = Math.round(((9/5)* (currentTempC - 273)) + 32)

    let currentTempLocal
    let 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
    }

    // 拼接天气展示文本
    const weatherString = "At " + humanTime + " in " + city + " there's " + weatherDescription + " and the temperature is " + currentTempLocal + degreesSymbol + "."
    // 拼接天气图标地址,可根据你的业务规则替换为自定义图标源
    const weatherIconSrc = `/static/weather/${weatherIcon}.png`

    // 单HTMLRewriter实例绑定多元素处理规则
    return new HTMLRewriter()
      // 原有逻辑:修改id为weather的p标签内容
      .on('#weather', {
        element(element) {
          element.setInnerContent(weatherString, { html: true })
        }
      })
      // 新增逻辑:修改天气图标img的src,假设你的天气图标元素id为weather-icon,可替换为实际的CSS选择器
      .on('#weather-icon', {
        element(element) {
          element.setAttribute('src', weatherIconSrc)
          element.setAttribute('alt', weatherDescription)
        }
      })
      // 新增逻辑:修改包含指定文本的p标签,将下方`目标匹配文本`替换为你要识别的p标签内容
      .on('p', {
        text(textChunk) {
          if (textChunk.text.includes('目标匹配文本')) {
            textChunk.replace('你要替换的p标签新内容', { html: false })
          }
        }
      })
      .transform(response)
  } catch (thrown){
    return new Response(thrown);
  }
}

注意事项

  • 天气图标选择器可根据你的页面实际结构调整,支持所有标准CSS选择器,比如层级选择器.menu-bar .weather-area img
  • 如果需要修改的p标签文本被拆分为多个textChunk,可通过变量拼接完整文本后再做匹配判断
  • 所有元素修改规则都在同一个HTMLRewriter实例中链式添加即可,不需要额外拆分实例或文件

内容的提问来源于stack exchange,提问作者cfn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:57:01