1

I am trying to make a simple redirect userscript for cbc.ca.

They have a "lite" version located at https://www.cbc.ca/lite/news.

And when you go to a news article the url is https://www.cbc.ca/lite/news/1.1111111, for example, where the numbers at the end reference the article. The same article on the full website would be located at, for example, https://www.cbc.ca/news/canada/something/a-very-long-descriptive-title-1.1111111

So far I have this:

// ==UserScript==
// @name Redirect to CBC Lite
// @include *.cbc.ca/news/*
// @run-at document-start
// @grant none
// ==/UserScript==

(function() {
    // create a new MutationObserver
    var observer = new MutationObserver(function(mutations) {
        location.href = location.href.replace(/news\/[\D]*/, 'lite/story/');
    });

    observer.observe(document, {
        childList: true,
        subtree: true
    });
})();

Which works, but I am required to refresh the page to make it do so. What do I need to add to make it work directly?

Small Update:

Now looks like this, still requires refresh to load:

const url = new URL(window.location.href);
const story_id = location.pathname.split('-').pop();
const lite_host = "https://www.cbc.ca/lite/story/";
const new_url = lite_host + story_id;

location.href = new_url;
2
  • Why do you need the MutationObserver? Shouldn't a simple location.href = `https://www.cbc.ca/lite/story/${location.pathname.split('-').pop()}` suffice? Commented Dec 10, 2022 at 8:33
  • I've made a change based on what you suggest @double-beep It still works, but I still need to refresh the page Commented Dec 10, 2022 at 11:55

1 Answer 1

2

It seems that the page doesn't reload each time you click a new article, hence the reason your script didn't work. You need to watch for URL changes. One way to do this is by using the urlchange event (only available to Tampermonkey)

// ==UserScript==
// @name         Redirect to CBC Lite
// @author       bbbhltz
// @description  Prefer the lite CBC version
// @version      0.0.1
// @match        *.cbc.ca/*
// @run-at       document-start
// @grant        window.onurlchange
// ==/UserScript==

(function() {
    function redirect() {
        const pathname = location.pathname;
        if (!pathname.startsWith('/news')) return;

        const storyId = pathname.split('-').pop();

        location.href = `https://www.cbc.ca/lite/story/${storyId}`;
    }

    window.addEventListener('urlchange', ({ url }) => {
        if (!url.startsWith('https://www.cbc.ca/news/')) return;

        redirect();
    });

    redirect();
})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.