火狐/Chrome扩展:创建新标签时如何打开链接

Firefox/Chrome extension: how to open link when new tab is created?

本文关键字:标签 链接 何打开 Chrome 扩展 新标签 创建 火狐      更新时间:2023-09-26

在 Firefox WebExtension 上工作。

当我打开一个新选项卡时,

下面的代码有效,但是当我单击链接时,它会更新任何当前选项卡。

如何使用query选择新选项卡?
有没有其他方法可以做到这一点?

/* Load Google when creates a new tab. */
function openMyPage() {
  //console.log("injecting");
   chrome.tabs.query({
     'currentWindow': true,
     'active': true
    // This will match all tabs to the pattern we specified
    }, function(tab) {
        // Go through all tabs that match the URL pattern
        for (var i = 0; i < tab.length; i++){
            // Update those tabs to point to the new URL
            chrome.tabs.update(
                tab[i].id, {
                    'url': 'http://google.com'
                }
            );
        }
    });
};
//Add openMyPage() as a listener when new tabs are created
chrome.tabs.onCreated.addListener(openMyPage);
tabs.onCreated

调提供了一个参数,该参数是一个Tab对象。您不应该查询以获取它,您已经拥有它。

function openMyPage(tab) {
    chrome.tabs.update(
        tab.id, {
            'url': 'http://google.com'
        }
    );
};

请注意,这将不分青红皂白地针对新选项卡 - 甚至是用户通过"在新选项卡中打开链接"打开的选项卡。如果这不是您想要的,则需要额外的逻辑来检测它是新标签页。

"tabs"权限下,tab对象将填充url属性。您可以使用它来过滤新选项卡。在Chrome中,这将是chrome://newtab/,在Firefox中应该是(我尚未测试)about:homeabout:newtab