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

Chrome扩展开发:如何提取SVG use标签的href属性值?

解决思路与代码实现

核心步骤

  • 定位目标<use>元素:通过类选择器.eventMsg锁定消息容器,再嵌套选择其中的svg use元素
  • 提取href属性值:使用DOM元素的getAttribute('href')方法直接获取属性值,或通过SVG元素专属的href.baseVal属性读取
  • 清理结果:移除属性值开头的#符号,得到最终的建造类型标识

TypeScript代码示例(Chrome扩展内容脚本中)

// 定位目标use元素
const useElement = document.querySelector<SVGUseElement>('.eventMsg svg use');

if (useElement) {
  // 方法1:使用getAttribute获取属性值
  const hrefAttr = useElement.getAttribute('href');
  if (hrefAttr) {
    const buildingId = hrefAttr.replace(/^#/, '');
    console.log('玩家建造的内容:', buildingId); // 输出 settlement-def-red
  }

  // 方法2:使用SVG元素的DOM属性href.baseVal
  const hrefDomValue = useElement.href.baseVal;
  if (hrefDomValue) {
    const buildingId = hrefDomValue.replace(/^#/, '');
    console.log('玩家建造的内容:', buildingId); // 输出 settlement-def-red
  }
}

注意事项

  • 若页面为动态渲染,需通过MutationObserver监听DOM变化,确保代码在目标元素加载完成后执行
  • TypeScript中使用querySelector<SVGUseElement>可获得类型提示,避免类型错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:15:58