如何禁止chrome打开“新窗口”和“标签”?

2024-04-06

他们是否可以通过 Chrome 浏览器设置将互联网上的所有页面保留在一个窗口中?或者我可以用一个插件/插件来做到这一点?

当我单击某些链接时,我不希望在新选项卡和/或新窗口中打开网页。

如果有人有任何建议请告诉我!谢谢!

        <a href="http://www.bing.com" target="_blank">Opens a New Tab!</a>

        <i>Thtats not what i want..., I want this link to stay in same url bar.</i>

        <p>Like this!</p>
        <a class="click" href="http://www.bing.com">Click Here</a>

可能的方法:

一种方法可能是构建一个扩展来注入内容脚本 http://developer.chrome.com/extensions/content_scripts.html在每一页中。此内容脚本将解析 DOM 并 删除所有内容target锚元素的属性并设置所有target锚元素的属性_self.

Caveats:

  1. 许多页面上都有动态插入的元素(包括锚元素)。
  2. 某些页面上存在动态变化的元素(包括锚元素)。
  3. 并非所有页面/选项卡都是通过链接打开的(例如某些页面可以使用window.open() https://developer.mozilla.org/en-US/docs/Web/API/Window.open).

解决方案:

你可以使用变异观察者 https://developer.mozilla.org/en-US/docs/Web/API/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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何禁止chrome打开“新窗口”和“标签”? 的相关文章

随机推荐