如何通过扩展修改chrome中的当前url位置 [英] How to modify current url location in chrome via extensions
问题描述
我想创建一个扩展名,如果用户点击了扩展按钮,就可以将用户重定向到另一个网站。到目前为止,我只看到了为每次点击创建新标签的扩展名。
是否可以使用活动标签将用户重定向到其他网站?
我试过这样的事情:
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; //< - 这不起作用
});
从 chrome.tabs
API,您可以使用 getCurrent()
或 query()
。
我更喜欢 getCurrent
,但不能从非选项卡上下文(例如后台页面或弹出视图)中调用。如果这对您是个问题,您应该考虑使用 query
来代替。 Jean-Marc Amon的 answer 下面提供了一个很好的例子,说明如何在这种情况下获得活动标签(请不要忘记)。
//下面的代码...
var tabUrl = encodeURIComponent(tab.url);
var tabTitle = encodeURIComponent(tab .title);
var myNewUrl =https://www.mipanga.com/Content/Submit?url=+ tabUrl +& title =+ tabTitle;
/ /更新网址。
chrome.tabs.update(tab.id,{url:myNewUrl});
});
注意:要使用此功能,必须确保您的 manifest.json
文件中已启用标签
权限:
permissions:[
标签
,
I want to create an extension that redirects the user to another website if he clicks on the extension button. So far I have only seen extensions which create a new tab for each click.
Is it possible to redirect the user to another website using the active tab?
I tried something like this:
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
});
From the chrome.tabs
API, you can use getCurrent()
or query()
.
I prefer getCurrent
but it cannot be called from a non-tab context (eg a background page or popup view). If this is a problem for you, you should look to use query
instead. Jean-Marc Amon's answer below provides a wonderful example of how to get the active tab in this case (don't forget to upvote him!).
Once you have the current tab, simply pass update()
.
chrome.tabs.getCurrent(function (tab) {
//Your code below...
var tabUrl = encodeURIComponent(tab.url);
var tabTitle = encodeURIComponent(tab.title);
var myNewUrl = "https://www.mipanga.com/Content/Submit?url=" + tabUrl + "&title=" + tabTitle;
//Update the url here.
chrome.tabs.update(tab.id, {url: myNewUrl});
});
NB: In order to use this this functionality, you must ensure that you have the tabs
permission enabled in your manifest.json
file:
"permissions": [
"tabs"
],
这篇关于如何通过扩展修改chrome中的当前url位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!