在 JavaScript 中,可以通过重写 document.createElement
和 HTMLAnchorElement.prototype.setAttribute
方法来拦截和 hook 所有对 <base>
标签的设置。以下是一个示例代码,展示了如何实现这一点:
// 保存原始方法
const originalCreateElement = document.createElement;
const originalSetAttribute = HTMLBaseElement.prototype.setAttribute;
// Hook document.createElement
document.createElement = function(tagName) {
const element = originalCreateElement.call(document, tagName);
// 如果创建的是 base 元素,则添加自定义逻辑
if (tagName.toLowerCase() === 'base') {
const originalSetAttr = element.setAttribute.bind(element);
element.setAttribute = function(name, value) {
console.log(`Setting base href to: ${value}`);
// 在这里可以添加更多自定义逻辑
// 调用原始 setAttribute 方法
return originalSetAttr(name, value);
};
}
return element;
};
// Hook HTMLBaseElement.prototype.setAttribute
HTMLBaseElement.prototype.setAttribute = function(name, value) {
if (name.toLowerCase() === 'href') {
console.log(`Setting base href to: ${value}`);
// 在这里可以添加更多自定义逻辑
}
// 调用原始 setAttribute 方法
return originalSetAttribute.call(this, name, value);
};
// 现在所有的 base href 设置都会被记录到控制台中
说明:
- 重写
document.createElement
:当创建<base>
元素时,增加额外的逻辑以拦截对setAttribute
的调用。 - 重写
setAttribute
方法:直接重写HTMLBaseElement.prototype.setAttribute
来捕捉对href
属性的设置。这允许你在任何地方使用该方法时进行监控。
注意事项:
- 确保这些 hook 代码在页面加载的早期执行,以便能捕获所有相关调用。
- 对于其他可能会影响
<base>
标签的方法(例如某些库或框架可能会修改 DOM),请根据需要进一步增强代码。
内容由零声教学AI助手提供,问题来源于学员提问