【问题标题】:How to get a Tampermonkey script to wait for page to finish after a hashchange event?如何让 Tampermonkey 脚本在 hashchange 事件后等待页面完成?
【发布时间】:2018-12-26 14:08:48
【问题描述】:

我正在编写 Tampermonkey 脚本,并为 hashchange 设置了一个侦听器。
在那个监听器中,我调用了一个操作 DOM 的函数。问题是该函数在页面完全加载之前被调用。

当从一个部分切换到另一个部分时,页面并未完全重新加载,因此on load 只能工作一次,这就是为什么我正在收听hashchange 而不是load。

window.addEventListener('hashchange', function (e) {
    if (!/step=view&ID=/.test(location.hash)) {
        //TODO clean up if leaving active trade
        return
    }
    console.log('hash changed', e)
    setup()
});

function setup() {
    //wait for page load here
    $('.myclass').after(<span>foo</span>);
}

我尝试在设置中添加on load,但没有任何效果。

编辑:

在setup 之外为load 添加一个侦听器如果转到确切的链接也只能工作一次,所以这也不是一个选项。

【问题讨论】:

  • 尝试添加setTimeout()。根据页面的实际工作方式,可能还可以使用 MutationObserver API
  • 我正在使用超时,我正在寻找一种不太脏的方法。
  • 也可以使用 setInterval 并检查 dom 内的条件,一旦满足就清除间隔。对更简洁的答案知之甚少
  • 在更高级别上也可以使用 ajax 拦截器,如果这是更改内容的方式,但需要研究网络请求并且不是通用方法

标签: javascript jquery greasemonkey userscripts tampermonkey


【解决方案1】:

这是waitForKeyElements、MutationObserver 或setTimeout 的工作

在几乎所有此类页面上,waitForKeyElements 本身就足够了,不需要hashchangelistener:

// ==UserScript==
// @name     _spans of foo
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements (".myclass", setupMyClass);

function setupMyClass (jNode) {
    jNode.after ('<span>foo</span>');
}

由于您添加的&lt;span&gt;foo&lt;/span&gt;s 在 hashchange 之后显然没有持续存在,那么这种技术可能就是您所需要的。


但是,如果页面是重用 .myclass 节点 (¿但以某种方式破坏了您的跨度?) 而不是重新创建它们,则使用类似的技术this other answer 中显示的内容。

在这种情况下,MutationObserver 可能是更好的选择。但是,这取决于您的问题中未提供的详细信息。


另请参阅How do I reload a Greasemonkey script when AJAX changes the URL without reloading the page?。

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多