考えられるアプローチ:
1 つのアプローチは、すべてのページにコンテンツ スクリプトを挿入する拡張機能を構築することです。このコンテンツ スクリプトは 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
}]
}
content.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
});