47

How can I go about redirecting chrome in an extension when visiting a given URL?

For example: when I visit http://yahoo.com/ I want it to redirect to http://google.com/

NOTE: A former version of this question asked whether there is any Google chrome extension which automatically redirects the tab when it visits a certain URL. Accordingly, the (currently two) answers below address different questions.

balu
  • 3,500
  • 4
  • 34
  • 35
  • 1
    I thought I'd share this use-case which is close to this: I often right-click and copy project files and paste in the browser location to open the script. The result is something like `/var/www/path/to/project/script.php`, which then I have to change to `localhost/path/to/project/script.php` before hitting enter. I got tired of this and decided to write an extension to do the replacement for me. – Majid Fouladpour Mar 26 '16 at 00:24

4 Answers4

75

There are many options, the one more convoluted than the other.

  1. The webRequest API, specifically the onBeforeRequest event. (Even better, the upcoming declarativeWebRequest API).
  2. Content scripts. Inject location.replace('http://example.com') in a page.
  3. The tabs API. Use the onUpdated event to detect when a page has changed its location, and chrome.tabs.update to change its URL. Avoid an infinite loop though!

The first one is the best one, because it is activated before a page is even requested. The second one can be activated after the request has been fulfilled, but before the page is rendered ("run_at":"document_start") or after it's rendered ("run_at":"document_end"). I mentioned the last one for completeness, but you shouldn't use it, because the other options are way better.

Here's an example using the webRequest API, a simple extension which allows me to browse pages on the Pirate bay, even though the main hosts are taken down by my ISP (the actual list of URLs is much longer, but I have omitted them for the sake of the example).
See match patterns for an explanation on the URL formats.

manifest.json

{
  "name": "The Pirate Bay",
  "description": "Redirect The Pirate Bay to a different host",
  "version": "1.0",
  "manifest_version": 2,
  "background": {"scripts":["background.js"]},
  "permissions": [
    "webRequest",
    "*://thepiratebay.se/*",
    "*://www.thepiratebay.se/*",
    "webRequestBlocking"
  ]
}

background.js

var host = "http://tpb.pirateparty.org.uk";
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
         return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
    },
    {
        urls: [
            "*://piratebay.se/*",
            "*://www.piratebay.se/*"
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
    ["blocking"]
);
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • this works but when I try to change the host url and reload the extension, it doesn't pick up the new url... even deleting the extension and adding it back doesn't help. I have to move the extension to a different folder and install it again... :(( – davidhq Aug 11 '13 at 11:01
  • @DavidKrmpotic Did you add the permissions for the host to your manifest file? – Rob W Aug 11 '13 at 11:04
  • don't understand what do you mean... host (the url it will redirect to) doesn't have to be in the manifest... looks like a bug with reloading extensions. everything works with new code when I rename the folder and install the extension again. – davidhq Aug 11 '13 at 11:06
  • @DavidKrmpotic After adding new permissions to the manifest.json file, you have to reload the extension via the "Reload" link at `chrome://extensions/`. – Rob W Aug 11 '13 at 11:07
  • I'm not adding new permissions to the manifest.json, just changing the host in background.js... And then I try clicking the Reload link and doesn't work. As I wrote also deleting the extension and adding it back doesn't reload the background.js code.. it's cached somewhere.. the only way is to remove the extension, rename the folder and add it back. Then the script redirects to the new host. – davidhq Aug 11 '13 at 11:22
  • I solved the problem by restarting chrome :/ Now all the changes are visible after clicking the "Reload" link.. as it should be.. Small hint for the above script: if you need redirection for multiple domains that are not all known yet (for example user can add them in settings), you can use this "\u003Call_urls\u003E" permission instead of two lines "*://thepiratebay.se/*", "*://www.thepiratebay.se/*" – davidhq Aug 11 '13 at 13:29
  • This extension as is doesn't work unless you change everything to thepiratebay.sx – dmikalova Aug 17 '13 at 02:19
  • @dmikalova The code in my answer is merely a demo. I'm using a completely different extension for redirecting all hosts to an unblocked version of The Pirate Bay (pirateproxy.net at the moment), using the efficient `declarativeWebRequest` API (saves memory!). – Rob W Aug 17 '13 at 08:58
  • 3
    @Rob W I know, I was just confused for a small while why the demo wasn't working and wanted to warn future comers. Personally, I've modified it for a simple facebook redirect. – dmikalova Aug 19 '13 at 01:34
  • Small thing but option two doesn't seem to work if your redirecting to an extension page, it just gets sent to about:blank... https://plus.google.com/107103323982221586131/posts/dtXmSfLHDix ...so you seem to have to do it from a background/event page. – PAEz Sep 20 '14 at 12:32
  • @PAEz Redirecting to an extensions page does work; I have done it plenty of times. Have you listed the extension page in [`web_accessible_resources`](https://developer.chrome.com/extensions/manifest/web_accessible_resources)? – Rob W Sep 20 '14 at 12:45
  • No! hehe, derrrr, its been ages since Ive done any of this and it slipped my mind ;) Woulda been nice to have got an error instead of an about:blank page. Thanks Rob W, still schooling me :P – PAEz Sep 20 '14 at 16:22
  • @spelufo In response to [your edit](https://stackoverflow.com/review/suggested-edits/9129922): Redirection to file:// is blocked because web pages cannot refer to `file://` resources, for security reasons. – Rob W Aug 12 '15 at 10:12
  • I tried your solution: I want to redirect me to `http://xxx` every time I enter `_http://xxxx` url. However it seems that since `_http://xxx url ` is not valid chrome is redirecting me to google search page instead of firing my redirect (done by the extension). Is there I was to handle this? – dstronczak Oct 29 '15 at 12:46
  • @dstronczak Intercept the request to your default search engine (e.g. Google) and redirect to your custom URL. I've created such an extension (not published, for personal use) that allows me to e.g. type ".se [term]" so that I can search on `site:.stackexchange.com [term]`. – Rob W Oct 29 '15 at 13:33
  • @RobW - could you elaborate? I asked the question here: http://stackoverflow.com/questions/33417206/chrome-extension-that-captures-and-redirects-anything-typed-in-the-url-search-ba – dstronczak Oct 29 '15 at 14:38
  • @dmikalova I'm trying to follow this example to code the simplest extension ever: redirecting just the Facebook homepage (https://www.facebook.com/) to https://www.facebook.com/saved. I've been unable to get it to do anything. Should `permissions` be something other than `["webRequest", "https://www.facebook.com/", "webRequestBlocking"]`? And in `onBeforeRequest`, I have `urls: ["https://www.facebook.com/" ]`. Thanks! – Ryan Mar 30 '16 at 05:55
  • @Ryan Your definitions looks good to me. If you directly visit `https://www.facebook.com`, then you will indeed be redirected. But Facebook uses pushState-based navigation, so if you navigate to the home page via Facebook's UI, then it won't be intercepted. See any of the existing answers on intercepting `history.pushState`-based navigation in Chrome extensions for alternatives. – Rob W Mar 30 '16 at 08:49
  • @RobW thanks. I think visiting `https://www.facebook.com` directly still didn't trigger the redirect, but I haven't looked at it again today yet. And yeah I started seeing what looked like `history.pushState` activity. I'll keep trying to figure it out later. – Ryan Mar 31 '16 at 02:26
  • Unfortunately I still haven't been able to get any of these options to work. I'd love to have an extension that knows to redirect certain patterns, such as www.amazon.com/* to smile.amazon.com/*, facebook.com to facebook.com/saved, stackoverflow.com to my SO profile, etc. – Ryan Dec 17 '19 at 19:01
21

I know I am a bit late in the game to answer this question Still I would like to answer this for future readers. Have a look at

Requestly - A Chrome Extension to modify Network Requests.

Currently, You can setup rules for

  1. Redirect a request URL to another url.
  2. Block some requests.
  3. Replace some part in URL with another string
  4. Modify Headers (Add/Remove/Modify Request and Response Headers)

Screenshots for more understanding:

  • List of Rules

List of Rules

  • Rule Type Cards

Rule Type Cards

  • New Redirect Rule

Creating a Redirect Rule

  • Headers Modification Rule

Modify Headers

There are lot of things in roadmap to be covered in requestly like

  • Switching User Agents

.. and a lot more.

PS: I have created this So you can blame me if you do not find this helpful :)

Community
  • 1
  • 1
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 2
    (I'd suggest you link to GitHub from the Chrome Extensions page, i.e. from the Overview description to the right here: https://chrome.google.com/webstore/detail/requestly/mdnleldcmiljblolnjhpnblkcekpdkpa?hl=en to GitHub. That gives a good impression I think.) – KajMagnus Aug 17 '15 at 08:27
  • @KajMagnus Good Idea..Thanks..I will add a link to github next time I will upload a new version of chrome store. – Sachin Jain Aug 23 '15 at 01:40
  • 1
    This also solves the issue of redirecting https on youtube back to http so that we can use it through our iPrism proxy server. (And probably the best solution I have found in this regard.) – AdamsTips Feb 16 '16 at 19:37
  • Another important notification is **Requestly is available for Firefox now. Install from http://requestly.in** – Sachin Jain Jan 03 '17 at 09:04
  • It's good but it lacks one option (which author mentioned in his post) - redirect after some time (e.g. 10 seconds or 2 minutes) to another page. – Adam Staszak Jan 21 '17 at 14:45
  • 1
    @sachinjain024 The extension is very cool, I was wondering if the code is open-source? – QPTR Apr 09 '17 at 07:47
  • @QPTR Entire code is not open source. Initially code was open source but after some thoughts I moved to a private repo wondering if someone actually uses the code and produces another extension in chrome store. I have made several components open source though at https://github.com/requestly. Let me know if you have any particular use case. Reachout at requestly.extension@gmail.com – Sachin Jain Apr 10 '17 at 08:24
  • 13
    -1 The question was clearly programming-oriented, i.e. it was about how to implement redirection in one's own web extension, not about what extension to use. (Otherwise I'm sure this question would have been asked on superuser.com.) – balu Mar 16 '18 at 00:04
  • 1
    @balu I agree this answer is not programming-oriented. There is a difference in terms of timeline when this question was asked and when this answer was made - Roughly 2 years and webRequest API got matured in the meantime. This means a few chrome extensions started to exist which solve this problem. This answer helps a lot of users who are looking to setup redirects and find that a tool already exists so they don't have to write their own. Hope it helps! – Sachin Jain Feb 23 '19 at 09:55
  • 3
    @balu actually if you look at the question history, it started off as "is there an extension", now it no longer is like that of course – Cornelius Roemer Mar 24 '20 at 21:21
  • 1
    @CorneliusRoemer You are right, I take my comment (and downvote) back then! I find it surprising, though, that the very essence of the question was changed later on and the edit was approved… – balu Mar 25 '20 at 16:59
  • 1
    @balu Even stranger that the guy who edited made his own answer less relevant by editing the question. Mind boggling! – Cornelius Roemer Mar 25 '20 at 17:04
  • 1
    @CorneliusRoemer Thanks for pointing that out. I am the culprit here. In my defense, Here was the sequence of events. I answered this, At later point in time I visited this question, checked the accepted answer and thought question should be about how to write code for redirect and hence I modified and changed the essence of questions. But now I have edited again and brought the original essence back. Apologies for the confusion here. – Sachin Jain Mar 26 '20 at 09:54
  • 1
    @balu I have brought the original essence of the question back and also mentioned why did it happen. Can you please delete the comment which has already brought a lot of downvotes to my answer already. – Sachin Jain Mar 26 '20 at 09:56
  • @sachinjain024 I don't think it is a good idea to bring back the original question. (…which was somewhat off-topic for StackOverflow to begin with. Besides, no one looks at the edit history.) So instead I brought back the other version (which is more relevant to SO) and added a remark to the question. As for my comment, I think it's more sensible to preserve history and context here, as well, and not delete it. But how about you add a introductory remark to your answer, saying that it is an answer to the *original* question? I'm sure you won't be getting any more downvotes in the future then. – balu Mar 26 '20 at 20:15
0

Inssman

This chrome extension can easily redirect any URL with the simple UI

What you need is just add the URL that you want to be redirected and the URL where you want to redirect.

enter image description here

And this extension is open source https://github.com/vvmgev/Inssman Inssman also has features like

  1. Block URL
  2. Modify query parameters
  3. Modify headers of request and response
  4. Modify the response
  5. Inject the file to any web page
  6. Analyze HTTP header

enter image description here

MegaWm
  • 11
  • 2
-1

You could use my extension. Go to "Rewrite Rules" tab, click the "+" button and add a new rewrite rule. Note that the rewrite rule is actually an RegEx so characters like / must be escaped

https://chrome.google.com/webstore/detail/dev-helper/kbbgddcndpjnadfacanamniaomcohlcc?hl=en

BlueStory
  • 235
  • 2
  • 4