1

I'm writing a Tampermonkey script that I want to use to redirect from youtube.com/* to a YouTube channel address.

window.addEventListener ("load", LocalMain, false);

function LocalMain () {
    location.replace("https://www.youtube.com/channel/*");
}

When the script is running it redirects to the channel URL but then keeps running and continuously redirects.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Pep Pizza
  • 13
  • 1
  • 3

4 Answers4

2

You need to check if the current pathname includes channel before reassigning a new href

function LocalMain () {

     if(!location.pathname.includes('/channel/')) {
        location.replace("https://www.youtube.com/channel/*");
     }
}

Also note you don't need to window load event to complete to do this

charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

You could check to see if the location contains 'channel', then return before you change the location.

window.addEventListener ("load", LocalMain, false);

function LocalMain () {
    if(location.href.indexOf('channel') === -1) return;
    location.replace("https://www.youtube.com/channel/*");
}
2

The standard, much more efficient, and much faster performing way to do this kind of redirect is to tune the script's metadata to not even run on the redirected-to page.

Also, use // @run-at document-start for even better response.

So your script would become something like:

// ==UserScript==
// @name        YouTube, Redirect to my channel
// @match       https://www.youtube.com/*
// @exclude     https://www.youtube.com/channel/*
// @run-at      document-start
// ==/UserScript==

location.replace("https://www.youtube.com/channel/UC8VkNBOwvsTlFjoSnNSMmxw");

Also, for such "broad spectrum" redirect scripts, consider using location.assign() so that you or your user can recover the original URL in the history in case of an overzealous redirect.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
0

Is tampermonkey configured to run the script only when not on your channel URL?

If not... then your script might ironically be doing exactly what you want: running once each page load. And the script loads a new page.

You can fix this within the script, like this:

window.addEventListener ('load', localMain, false);

function localMain () {
    if (location.href.startsWith('https://www.youtube.com/channel/')) {
        return; // exit
    }
    location.replace('https://www.youtube.com/channel/*');
}
Matthias
  • 13,607
  • 9
  • 44
  • 60