Reputation:
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;
Upvotes: 1
Views: 1240
Reputation: 5504
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();
})();
Upvotes: 1