如何在 window.location.href 更改后运行 TamperMonkey 函数

使用 TamperMonkey 脚本自动化工作流时,你经常遇到这样的情况:你想运行某个函数,然后设置 window.location.href,在该页面加载后运行代码的另一部分。但是,由于浏览器物理上重新加载页面,Tampermonkey 脚本也会重新加载 - 因此,你的原始函数将停止执行。

一旦你理解了概念,修复就很简单:

  1. 重新加载页面之前,我们在 sessionStorage 中设置特定键,指示页面加载完成后我们要做什么
  2. 然后我们可以设置 window.location.href
  3. 每次页面加载时,我们检查键是否已设置,如果是,我们运行适当的函数并删除键

注意在 TamperMonkey 上下文中,这仅限于脚本 @match 配置中包含的页面(否则,脚本不会在正在加载的新页面上执行):

tampermonkey-continuation.user.js
// ==UserScript==
// @name         TamperMonkey 续展示例
// @namespace    http://tampermonkey.net/
// @version      0.1
// @author       你
// @match        https://techoverflow.net
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    const continuationKey = "_my_script_continuation_key"; // 此 sessionstorage 键

    // 检查续展
    const continuationActions = {
        "printMsg": onPrintMsg
    };
    const _continuation = sessionStorage.getItem(continuationKey);
    if(_continuation) {
        sessionStorage.removeItem(continuationKey);
        const action = continuationActions[_continuation]
        if(action) {action();}
    }

    function onPrintMsg() {
        console.log("这在重新加载页面后运行");
    }

    function onAltQ() {
        console.log("现在将重新加载页面...");
        sessionStorage.setItem(continuationKey, "printMsg");
        window.location.href = window.location.origin + "/";
    }

    function onKeydown(evt) {
        // 使用 https://keycode.info/ 获取键
        if (evt.altKey && evt.keyCode == 81) {
            onAltQ();
        }
    }
    document.addEventListener('keydown', onKeydown, true);
})();

Check out similar posts by category: Javascript