ZBLOG

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

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

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

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

方法 1:使用 MutationObserver

// 创建一个观察者实例
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
            if (node.tagName === 'BASE') {
                // 当 base 标签被添加时,记录 href 的设置
                console.log(`Base tag added: ${node.href}`);
            }
        });
        
        // 如果属性发生了变化,检查是否是 href 属性
        if (mutation.type === 'attributes' && mutation.attributeName === 'href') {
            const baseTag = mutation.target;
            console.log(`Base href changed to: ${baseTag.href}`);
        }
    });
});

// 配置观察者选项
const config = { attributes: true, childList: true, subtree: true };

// 启动观察器并监视文档
observer.observe(document, config);

// 如果页面上已经存在 <base> 标签,手动触发一次检测
const existingBaseTags = document.getElementsByTagName('base');
for (let i = 0; i < existingBaseTags.length; i++) {
    console.log(`Existing base href: ${existingBaseTags[i].href}`);
}

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

(function() {
    const originalSetAttribute = HTMLBaseElement.prototype.setAttribute;
    
    HTMLBaseElement.prototype.setAttribute = function(name, value) {
        if (name.toLowerCase() === 'href') {
            console.log(`Setting base href to: ${value}`);
        }
        
        return originalSetAttribute.call(this, name, value);
    };

    // 检查当前页面是否已有 <base> 标签并记录其 href 属性
    const existingBaseTags = document.getElementsByTagName('base');
    for (let i = 0; i < existingBaseTags.length; i++) {
        console.log(`Existing base href: ${existingBaseTags[i].href}`);
    }
})();

总结:

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?