javascript - 火狐/Chrome扩展程序: how to open link when new tab is created?

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

正在处理 Firefox WebExtension .

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

如何使用查询选择新标签页?
还有其他方法可以做到这一点吗?

/* 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.

关于javascript - 火狐/Chrome扩展程序: how to open link when new tab is created?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35645132/

相关文章:

CSS 显示 :flex align-items:baseline not working in Firefox

javascript - CSS/JavaScript 使用 Div 使页面部分变灰

javascript - es6 模块原生支持

javascript - 与lovefield连接 promise 的异常(exception)情况

google-chrome - 为什么工具栏图标从 Google Chrome 开发者工具中消失了?

firefox - 使用 Selenium webdriver 动态更改 Firefox 中的代理

javascript - FF mouseleave/mouseenter 事件

javascript - JSON 从 css 解析图像

google-chrome - 使用Typekit加载网页时加载会卡住计算机

javascript - 无法获取对现有窗口的引用