ZBLOG

js hook所有给base标签的href属性赋值的操作

要 hook 所有对 <base> 标签的 href 属性赋值操作,可以通过以下几种方式来实现:

  1. 使用 MutationObserver 监视 DOM 变化
  2. 重写 setAttribute 方法

下面是这两种方法的示例代码。

方法 1:使用 MutationObserver

  1. // 创建一个观察者实例
  2. const observer = new MutationObserver((mutations) => {
  3. mutations.forEach((mutation) => {
  4. mutation.addedNodes.forEach((node) => {
  5. if (node.tagName === 'BASE') {
  6. // 当 base 标签被添加时,记录 href 的设置
  7. console.log(`Base tag added: ${node.href}`);
  8. }
  9. });
  10. // 如果属性发生了变化,检查是否是 href 属性
  11. if (mutation.type === 'attributes' && mutation.attributeName === 'href') {
  12. const baseTag = mutation.target;
  13. console.log(`Base href changed to: ${baseTag.href}`);
  14. }
  15. });
  16. });
  17. // 配置观察者选项
  18. const config = { attributes: true, childList: true, subtree: true };
  19. // 启动观察器并监视文档
  20. observer.observe(document, config);
  21. // 如果页面上已经存在 <base> 标签,手动触发一次检测
  22. const existingBaseTags = document.getElementsByTagName('base');
  23. for (let i = 0; i < existingBaseTags.length; i++) {
  24. console.log(`Existing base href: ${existingBaseTags[i].href}`);
  25. }

方法 2:重写 setAttribute 和属性访问

  1. (function() {
  2. const originalSetAttribute = HTMLBaseElement.prototype.setAttribute;
  3. HTMLBaseElement.prototype.setAttribute = function(name, value) {
  4. if (name.toLowerCase() === 'href') {
  5. console.log(`Setting base href to: ${value}`);
  6. }
  7. return originalSetAttribute.call(this, name, value);
  8. };
  9. // 检查当前页面是否已有 <base> 标签并记录其 href 属性
  10. const existingBaseTags = document.getElementsByTagName('base');
  11. for (let i = 0; i < existingBaseTags.length; i++) {
  12. console.log(`Existing base href: ${existingBaseTags[i].href}`);
  13. }
  14. })();

总结:

  • MutationObserver 方法可以监控任何对 DOM 的变化,包括元素的添加和属性的修改,这样即使是在异步情况下也能捕捉到 <base> 标签的更改。
  • 重写 setAttribute 方法则可以直接拦截所有通过 JavaScript 修改属性的操作。

你可以根据需要选择适合的方法来实现你的功能。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?