要 hook 所有对 <base>
标签的 href
属性赋值操作,可以通过以下几种方式来实现:
- 使用
MutationObserver
监视 DOM 变化。 - 重写
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助手提供,问题来源于学员提问