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

07-24 19:19
查看更多