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

更新日期: 2018-10-14 阅读次数: 7747 分类: Tampermonkey

现象

  • 页面 A: https://www.sunzhongwei.com/#/coding
  • 页面 B: https://www.sunzhongwei.com/#/sleeping
  • 页面 B 的内嵌 iframe 页面 C: https://www.sunzhongwei.com/dreaming

对页面 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 # 页面导致逻辑被中断。

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式