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

Sad*_*nda 10 javascript userscripts tampermonkey

// ==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);
    });
})();
Run Code Online (Sandbox Code Playgroud)

所以你可以看到这段代码应该在控制台中返回:0然后1,但结果不同,实际上脚本运行了多次。

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

例外:(低代表图像 1)

实际:(低代表图像 2)

RAS*_*ASG 17

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

添加// @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==
Run Code Online (Sandbox Code Playgroud)