tampermonkey 当前页面跳转后没有触发新页面对应逻辑

发布时间: 2018-10-14 00:19:06 作者: 大象笔记

现象

对页面 C 做了 tamermonkey 规则,即跳转到页面 A:

window.top.location.href = 'https://www.sunzhongwei.com/#/coding';

但是跳转之后,页面 A 对应 tampermonkey 逻辑并没有执行

if (window.location.hash == "#/coding" || window.location.hash == "#/") {
    setInterval(function() {
         unsafeWindow.location.href = "https://www.sunzhongwei.com/#/sleeping";
    }, 3000);

hash # 更改并不会触发页面从服务器重新加载

使用 angular, vue 之类的前端框架写过单页面 web app 都知道,hash # 的更改并不会导致页面从服务器重新加载页面。也就不会触发 tampermonkey 的脚本从头执行。

所以,这里需要 reload.

即在页面 C 中添加

window.top.location.href = 'https://www.sunzhongwei.com/#/coding';
window.top.location.reload(true);

页面 A 中

unsafeWindow.location.href = "https://www.sunzhongwei.com/#/sleeping";
window.location.reload(true)

reload 中的 true 参数

true 表示不从浏览器缓存中加载,而是强制从服务器端加载。

默认为 false.

逻辑优化

页面 A 中,使用 @exclude 将 C 页面剔除。

页面 A 中,去掉 if 判断 location.hash,直接 setInterval 定时判断。原因是,防止其他 hash # 页面导致逻辑被中断。

我是一名山东烟台的开发者,联系作者