How to modify current url location in chrome via extensions

南楼画角 提交于 2019-12-28 04:49:19

问题


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
});

回答1:


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



回答2:


You can use chrome.tabs.query too

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



回答3:


The chrome.tabs.update method (at least, as of January 2017) will automatically run on the current active tab if no tab id is passed.

This has the added advantage of not requiring the tabs permission. Extensions with this permission warn the user that they can read the browsing history, so you should avoid asking for it if you don't need to.

Changing the current tab's URL is as simple as writing this:

chrome.tabs.update(undefined, {url: 'http://example.com'});

Or as mentionned by farwayer in the comments, you don't need to put two arguments at all.

chrome.tabs.update({url: 'http://example.com'});


来源:https://stackoverflow.com/questions/1891738/how-to-modify-current-url-location-in-chrome-via-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!