gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:18:07 24 4
gpt4 key购买 nike

正在处理 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com