【问题标题】:Userscript should run once, not multiple times用户脚本应该运行一次,而不是多次
【发布时间】:2020-01-17 21:36:11
【问题描述】:
// ==UserScript==
// @name         Test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://myanimelist.net/*
// @require http://code.jquery.com/jquery-3.4.1.slim.min.js
// @grant        none
// ==/UserScript==
var index = 0;
(function() {
    'use strict';
    $(document).ready(function () {
        console.log(index);
        index++;
        setTimeout(() => {  console.log(index); }, 2000);
    });
})();

您是否可以看到此代码应在控制台中返回:0 然后 1 但是 结果不一样,实际上脚本运行了多次。

我唯一的线索是来自相关网站,有什么想法吗?

Excepted : (low rep image 1)

Actual : (low rep image 2)

【问题讨论】:

  • 无论是否使用 Tampermonkey,对我来说都运行良好。你确定你没有脚本的多个实例吗?
  • 没有测试,我看到一个 IIFE 加上 ready( 事件。使用慢速互联网,jquery 尚未加载(标头缓存更改尚未成功 200OK),但 IIFE 已经触发,因为它是纯 javascript。
  • 该站点可能有 iframe,您可以在 devtools 中进行测试。在元区块评论中添加// @noframes。此外,您根本不需要 jquery,也不需要 $(document).ready 包装器。
  • // @noframes 完成了这项工作! (已解决)

标签: javascript tampermonkey userscripts


【解决方案1】:

您的脚本可能正在为页面中的每个框架加载。

添加// @noframes 以防止这种情况发生。

// ==UserScript==
// @name         Test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://myanimelist.net/*
// @require http://code.jquery.com/jquery-3.4.1.slim.min.js
// @grant        none
// @noframes
// ==/UserScript==

【讨论】:

    【解决方案2】:

    你可以使用 Lodash 运行一次函数

    _.一次( //函数只运行一次 )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2021-10-09
      • 2019-06-09
      • 2016-07-13
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多