如何通过扩展名修改Chrome中的当前网址位置

40 javascript google-chrome google-chrome-extension

我想创建一个扩展程序,如果用户单击扩展按钮,则会将用户重定向到另一个网站.到目前为止,我只看到了为每次点击创建新标签的扩展程序.

是否可以使用活动选项卡将用户重定向到另一个网站?

我试过这样的事情:

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
});
Run Code Online (Sandbox Code Playgroud)

Dan*_*son 67

chrome.tabs.query()API,您可以使用query()chrome.tabs.

我更喜欢getCurrent()但不能从非标签上下文(例如背景页面或弹出视图)调用它.如果这对您来说是个问题,您应该选择使用query().Jean-Marc Amon在下面的回答提供了一个很好的例子,说明如何在这种情况下获得活动标签(不要忘记向他投票!).

获得当前选项卡后,只需传递即可getCurrent.

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});
});
Run Code Online (Sandbox Code Playgroud)

注意:要使用此功能,您必须确保queryupdate()文件中启用了权限:

"permissions": [
  "tabs"
],
Run Code Online (Sandbox Code Playgroud)

  • 我对chrome.tabs.getCurrent(function(tab){})有同样的问题,我使用了chrome.tabs.getSelected(null,function(tab){})而且它工作正常 (2认同)

Jea*_*mon 36

您也可以使用chrome.tabs.query

chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
      chrome.tabs.update(tab.id, {url: your_new_url});
});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.'getSelected'已被弃用 (4认同)
  • @Jean-Marc Amon `tab` 参数实际上是一个数组类型,所以它应该是 `tabs[0].id` (2认同)

Dom*_*ino 8

chrome.tabs.update如果没有传递选项卡ID,则该方法(至少自2017年1月起)将自动在当前活动选项卡上运行.

这具有不需要tabs许可的附加优点.具有此权限的扩展程序会警告用户他们可以阅读浏览历史记录,因此如果您不需要,则应避免询问它.

更改当前选项卡的URL就像写这个一样简单:

chrome.tabs.update(undefined, {url: 'http://example.com'});
Run Code Online (Sandbox Code Playgroud)

或者如评论中提到的那样,你不需要放两个参数.

chrome.tabs.update({url: 'http://example.com'});
Run Code Online (Sandbox Code Playgroud)

  • 你甚至可以跳过第一个参数`chrome.tabs.update({url:'http:// http://example.com'});` (2认同)