如何实现无需刷新的CBC新闻转Lite版UserScript重定向?
CBC Lite 自动重定向油猴脚本问题解决
我正在为cbc.ca制作一个自动重定向到精简版(Lite)的油猴脚本,相关URL规则如下:
- CBC新闻完整版文章URL示例:
https://www.cbc.ca/news/canada/something/a-very-long-descriptive-title-1.1111111 - 对应的Lite版URL示例:
https://www.cbc.ca/lite/news/1.1111111,核心是提取URL末尾的文章标识(如1.1111111),拼接成Lite版地址
我先后写了两段代码,但都需要手动刷新页面才能触发重定向:
第一段代码(用MutationObserver)
// ==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 }); })();
第二段代码(直接提取ID)
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;
问题根源
CBC新闻网站采用了**单页应用(SPA)**架构,页面内的跳转是前端无刷新完成的,油猴脚本默认仅在页面首次加载时执行一次,后续的路由变化不会触发脚本执行,所以必须刷新才生效。
解决代码
以下是修改后的完整脚本,无需刷新即可自动触发重定向:
// ==UserScript== // @name Redirect to CBC Lite // @include *.cbc.ca/news/* // @run-at document-start // @grant none // ==/UserScript== (function() { function redirectToLite() { // 已在Lite页面,直接跳过避免无限循环 if (window.location.href.includes('/lite/')) return; // 提取有效文章ID:匹配数字+点+数字的格式 const pathParts = window.location.pathname.split('-'); const storyId = pathParts.find(part => /^\d+\.\d+$/.test(part)); if (!storyId) return; // 无有效ID则不执行跳转 const newUrl = `https://www.cbc.ca/lite/news/${storyId}`; window.location.replace(newUrl); // 用replace避免回退到原页面 } // 页面首次加载时立即执行 redirectToLite(); // 监听浏览器前进/后退操作的路由变化 window.addEventListener('popstate', redirectToLite); // 监听SPA路由切换带来的DOM更新 const observer = new MutationObserver(() => { redirectToLite(); }); observer.observe(document.documentElement, { childList: true, subtree: true }); })();
关键改进点
- 防无限循环:增加了URL判断,已经是Lite页面时不再执行跳转
- 精准提取ID:用正则匹配确保拿到的是有效的文章标识,避免误提取路径中的其他数字片段
- 多场景覆盖:
- 首次加载页面直接触发重定向
- 监听
popstate事件处理浏览器导航按钮的路由变化 - 用MutationObserver捕捉SPA前端跳转带来的DOM更新,自动触发重定向
内容的提问来源于stack exchange,提问作者user20706869
相关产品推荐
相关产品推荐

