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
相关产品推荐
相关产品推荐

