注意:如果您开发跨浏览器扩展(希望您这样做!),我建议您使用chrome.tabs.query()。请参阅Jean-Marc Amon's answer 了解更多信息。这个答案在 Firefox 和 Chrome 中仍然有效,但 query() 更常用,有更多选项,并且适用于背景页面和弹出视图。
通过chrome.tabs API,您可以使用getCurrent()、query() 或update()。
目前,我更喜欢update(),因为它允许您更新当前选项卡,而无需执行其他操作。
注意:您不能在内容脚本中使用update()。
如果需要从内容脚本更新 url,那么您应该改用 query。 Jean-Marc Amon 的answer 提供了一个很好的例子,说明如何在这种情况下获得活动标签(不要忘记给他投票!)。
update()
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
chrome.tabs.update(undefined, { url: myNewUrl });
在这里,我们将 update 的第一个参数设置为 undefined。这是您要更新的选项卡 ID。如果未定义,Chrome 将更新当前窗口中的当前选项卡。
有关update 的更多信息,请参阅Domino's answer,并注意不需要undefined。同样,如果您觉得有用,请不要忘记也为他们的回答点赞。
getCurrent()
getCurrent 也不能从非选项卡上下文(例如背景页面或弹出视图)中调用。
获得当前标签后,只需传递update()。
chrome.tabs.getCurrent(function (tab) {
//Your code below...
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
//Update the url here.
chrome.tabs.update(tab.id, { url: myNewUrl });
});
注意:要使用此功能,您必须确保在您的 manifest.json 文件中启用了tabs permission: p>
"permissions": [
"tabs"
],