How to make a script redirect only once every time an appropriate page loads?

岁酱吖の 提交于 2019-11-29 16:50:44

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

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

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.

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/*');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!