用户脚本应该运行一次,不能多次运行

问题描述 投票:1回答:2
// ==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)

javascript tampermonkey userscripts
2个回答
0
投票

您可以使用Lodash一次运行一个函数

_。once(//仅运行一次的函数)


0
投票

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

添加// @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==
© www.soinside.com 2019 - 2024. All rights reserved.