ZBLOG

let originalSetAttribute = window.Element.prototype.setAttribute; window.Element.prototype.setAttribute = function (attr, value) { let hv = value; if (nodeName === "img" || nodeName === "link" || nod...

在你的代码中,nodeName 变量没有被定义,所以无法正确判断元素的类型。要获取当前元素的节点类型(tag name),你需要使用 this.nodeNamethis.tagName

修正后的代码:

  1. let originalSetAttribute = window.Element.prototype.setAttribute;
  2. window.Element.prototype.setAttribute = function (attr, value) {
  3. let hv = value;
  4. const nodeName = this.nodeName.toLowerCase(); // 获取当前元素的标签名(小写)
  5. if (nodeName === "img" || nodeName === "link" ||
  6. nodeName === "script" || nodeName === "a" ||
  7. nodeName === "frame" || nodeName === "iframe" ||
  8. nodeName === "form" || nodeName === "audio" ||
  9. nodeName === "video" || nodeName === "source" || // 注意:原代码拼写错误 'vedio' -> 'video'
  10. nodeName === "embed" || nodeName === "object" ||
  11. nodeName === "track" || nodeName === "area"
  12. ) {
  13. if (attr === "src" ||
  14. attr === "href" ||
  15. attr === "action") {
  16. if (isNeedHook(value)) {
  17. hv = hookUrl(value);
  18. }
  19. }
  20. }
  21. debugLog("setAttribute v : ", value, " hookv : ", hv);
  22. originalSetAttribute.call(this, attr, hv);
  23. };
  24. window.setAttributeHook = true;

关键修改说明:

  1. 获取当前元素的节点类型

    • 使用 this.nodeName.toLowerCase() 获取当前 DOM 元素的标签名(转换为小写)。
    • this 指向调用 setAttribute 的 DOM 元素。
  2. 修正拼写错误

    • vediovideo(原代码中的拼写错误)。
  3. 移除无效属性

    • refresh 不是标准 HTML 属性,已从判断条件中移除。
  4. 注意事项

    • isNeedHook(value)hookUrl(value) 需要你自己实现。
    • debugLog 也需要自行定义或替换为 console.log

这样修改后,你的 Hook 逻辑就能正确识别不同类型的 DOM 元素了。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23395

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?