Search code examples
javascriptgreasemonkey

Redirect URLs that the website requests to my own URL


I wonder if I can redirect the JSON, .jpg, .mp3 or any other file URLs that the website requests to my own URL with Greasemonkey?

Example:

If the website requests https://example.com/example.json, I want it to be redirected to https://mywebsite.com/myjson.json. There are some other file URLs that I want to redirect so I don't want everything to get redirected, just some specific files.


Solution

  • You can write a userscript that runs at document-start (before any scripts on the page run) to overwrite XMLHttpRequest.prototype.open with your own method which replaces the second parameter's example.com with mywebsite.com. Something along the lines of:

    // ==UserScript==
    // @name         Redirect
    // @include      /https?://example\.com/
    // @run-at       document-start
    // @grant        none
    // ==/UserScript==
    
    const origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(...args) {
      if (typeof args[1] === 'string') {
        args[1] = args[1].replace('example.com', 'mywebsite.com');
      }
      return origOpen.apply(this, args);
    };