How do I redirect to a URL using a Google Chrome Extension & Content Script?

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 ?

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

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/*"
  ],
  ...
}

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 …


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Webpack5 Automatic publicPath is not supported in this browser

Similar Posts