SadPanda
SadPanda

Reputation: 165

Userscript should run once, not multiple times

// ==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);
    });
})();

So has you can see this code should return in the console : 0 then 1 but the result is different, actually the script run multiple times.

My only clue is that come from the site in question, any idea ?

Excepted : (low rep image 1)

Actual : (low rep image 2)

Upvotes: 11

Views: 2914

Answers (2)

yodog
yodog

Reputation: 6232

your script could be loading for each frame in the page.

add // @noframes to prevent this.

// ==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==

Upvotes: 21

Raphael Castro
Raphael Castro

Reputation: 1148

you can use Lodash to run a function once

_.once( //Function to run only once )

Upvotes: 2

Related Questions