可能的方法:
一种方法可能是构建一个在每个页面中注入内容脚本的扩展。此内容脚本将解析 DOM 并删除锚元素的所有target
属性并将锚元素的所有属性设置target
为_self
.
注意事项:
- 许多页面上有动态插入的元素(包括锚元素)。
- 某些页面上有动态变化的元素(包括锚元素)。
- 并非所有页面/选项卡都通过链接打开(例如,某些页面可以使用
window.open()
)。
解决方案:
您可以使用MutationObserver 监视插入的锚元素或修改其target
属性并进行适当的调整。
如果它对您非常重要,您仍然需要注意通过其他方式打开的选项卡(例如window.open()
)(但这些情况应该非常少,因此可能不值得麻烦)。
示例代码:
清单.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"content_scripts": [{
"matches": ["*://*/*"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}]
}
内容.js:
/* Define helper functions */
var processAnchor = function(a) {
//if (a.hasAttribute('target')) {
// a.removeAttribute('target');
//}
a.setAttribute('target', '_self');
};
/* Define the observer for watching over inserted elements */
var insertedObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(m) {
var inserted = [].slice.call(m.addedNodes);
while (inserted.length > 0) {
var elem = inserted.shift();
[].slice.call(elem.children || []).forEach(function(el) {
inserted.push(el);
});
if (elem.nodeName === 'A') {
processAnchor(elem);
}
}
});
});
/* Define the observer for watching over
* modified attributes of anchor elements */
var modifiedObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(m) {
if ((m.type === 'attributes') && (m.target.nodeName === 'A')) {
processAnchor(m.target);
}
});
});
/* Start observing */
insertedObserver.observe(document.documentElement, {
childList: true,
subtree: true
});
modifiedObserver.observe(document.documentElement, {
attributes: true,
substree: true
});