【问题标题】:Firefox/Chrome extension: how to open link when new tab is created?Firefox/Chrome 扩展:创建新标签时如何打开链接?
【发布时间】:2016-02-26 06:38:46
【问题描述】:

处理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);

【问题讨论】:

    标签: javascript google-chrome firefox google-chrome-extension firefox-addon-webextensions


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2013-05-06
      • 2011-06-26
      • 2015-05-17
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2016-03-28
      相关资源
      最近更新 更多