How to modify current url location in chrome via extensions

后端 未结 3 1702
春和景丽
春和景丽 2020-12-04 11:43

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

3条回答
  •  鱼传尺愫
    2020-12-04 12:07

    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.

    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"
    ],
    

提交回复
热议问题