Search code examples
javascriptgoogle-chrome-extension

How do you redirect a custom generated URL in javascript?


I'm trying to write an extension for personal use. Background.js file where I want to take a url - detect an integer from within it - redirect it to a new URL with the string concatenated in between. But it doesn't seem to work (I'm new). This is a very specific case for personal use. Here is my example code so far (of course the URLs are sample):

const abc = "https://www.google.com/anc/wddsd/";
const xyz = "/tracking/file/subsystem";
var res = url.split('/')[4];  //can I even access the URL before the function begins?

Say there is a Numeric Digit that occurs just after /wddsd/ and I want to extract it from the original URL and place it in the redirected URL.

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {

      return {
        redirectUrl: 
        abc + res + xyz
    };
    },

    {
      urls: [
        "*//www.google.com/*"
      ],
      types: [
        "main_frame",
        "sub_frame",
        "stylesheet",
        "script",
        "image",
        "object",
        "xmlhttprequest",
        "other"
      ]
    },
    ["blocking"]
  );

update: The permissions of my manifest.json are:

"permissions": ["webRequest", "webRequestBlocking", "*://google.com/*"]

Solution

  • Hey to anyone stumbling upon this in the future, I fixed it myself by essentially replacing

    var res = url.split('/')[4];
    

    with

    var res = details.url.split('/')[4];
    

    and putting it inside the function. Hooray.