gpt4 book ai didi

javascript - 如何通过扩展修改 chrome 中的当前 url 位置

转载 作者:IT王子 更新时间:2023-10-29 03:10:48 24 4
gpt4 key购买 nike

我想创建一个扩展程序,如果用户点击扩展程序按钮,它会将用户重定向到另一个网站。到目前为止,我只见过为每次点击创建一个新选项卡的扩展程序。

是否可以使用事件标签将用户重定向到另一个网站?

我试过这样的:

chrome.browserAction.onClicked.addListener(function(tab) {
var url = "https://www.mipanga.com/Content/Submit?url="
+ encodeURIComponent(tab.url)
+ "&title=" + encodeURIComponent(tab.title);

document.location.href = url; // <-- this does not work
});

最佳答案

Attention: If you develop cross-browser extensions (I hope you do!), I recommend that you use chrome.tabs.query(). Please see Jean-Marc Amon's answer for more information. This answer still works in both Firefox and Chrome, but query() is more commonly used, has more options, and works in background pages and popup views.

来自chrome.tabs API,你可以使用getCurrent() , query() , 或 update() .

现在,我更喜欢 update(),因为它允许您更新当前选项卡而无需执行其他操作。
注意:您不能在内容脚本中使用 update()

如果需要从内容脚本更新 url,那么您应该改用 query。让-马克·阿蒙的 answer提供了一个很好的示例,说明如何在这种情况下获取事件选项卡(不要忘记给他投票!)。

更新()

let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
chrome.tabs.update(undefined, { url: myNewUrl });

在这里,我们将更新的第一个参数设置为未定义。这是您要更新的选项卡 ID。如果未定义,Chrome 将更新当前窗口中的当前选项卡。

请参阅Domino's answer有关 update 的更多信息,同时请注意 undefined 不是必需的。同样,如果您觉得有用,请不要忘记给他们的答案点赞。

getCurrent()

getCurrent 也不能从非选项卡上下文(例如背景页面或弹出 View )调用。

获得当前选项卡后,只需传递 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 });
});

注意:为了使用此功能,您必须确保您拥有选项卡 permission在您的 manifest.json 中启用文件:

"permissions": [
"tabs"
],

关于javascript - 如何通过扩展修改 chrome 中的当前 url 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1891738/

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