23

I'm currently building a Google Chrome extension which tests for certain patterns and if found, redirects them to a new URL.

I've gotten the pattern checking done via a content script, and now I'm not sure how can I proceed with getting the redirect done. Any suggestions ?

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
  • 5
    @jmort `window.location` doesn't work since content scripts are unprivileged. Further more, `window.location.href` returns the current location, but it is not a method so I cannot overwrite it. – Sathyajith Bhat Feb 01 '11 at 07:08

3 Answers3

42

Send redirect url from a content script to a background page:

chrome.runtime.sendMessage({redirect: "http://redirect"});

In a background page update tab's url which would cause redirect:

chrome.runtime.onMessage.addListener(function(request, sender) {
    chrome.tabs.update(sender.tab.id, {url: request.redirect});
});
calvin
  • 75
  • 5
serg
  • 109,619
  • 77
  • 317
  • 330
  • Perfect, thanks! Found this as well -> http://code.google.com/chrome/extensions/extension.html#event-onRequest & the video over here -> http://code.google.com/chrome/extensions/content_scripts.html – Sathyajith Bhat Feb 01 '11 at 07:32
  • Hi Calvin. I know this is an old post but I appreciate your suggestion and I see it work if i try to redirect to "yahoo.com", but if I send a specific URL (which I confirmed is correct with console.log), Chrome redirects me to the URL with the extensionID prepended to the URL. Any ideas how to resolve this? So URL ends up being something like: chrome-extension://injepfpghgbmjnecbgiokedggknlmige/mywantedurl.hmtl – Ed Landau Nov 11 '18 at 18:23
  • This seemed to have no effect for me. – Ryan Dec 17 '19 at 18:55
2

If you want to access a file inside your WebExtension, you can add the file and its prerequisites to web_accessible_resources in manifest.json, as in

{
  ...
  "web_accessible_resources": [
    "images/*.png",
    "style/double-rainbow.css",
    "script/double-rainbow.js",
    "script/main.js",
    "templates/*"
  ],
  ...
}
serv-inc
  • 35,772
  • 9
  • 166
  • 188
-3

Ive not worked with Google Chrome extensions... but you may be able to use one of these ways.

As I understand, these extension APIs allow you to inject javascript into the page... after that its simple manipulation of window.location ...

sajal
  • 776
  • 1
  • 6
  • 23