How to make a script redirect only once every time

2020-02-15 05:24发布

问题:

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.

回答1:

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



回答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/*");
}


回答3:

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.



回答4:

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/*');
}