javascripttampermonkey

TamperMonkey userscript doesn't fire DOMContentLoaded event


This is a TamperMonkey userscript. Why doesn't "HELLO" popup? I am running Google Chrome on Ubuntu.

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://*/*
// @match        https://*/*
// @grant        none
// ==/UserScript==

window.addEventListener("DOMContentLoaded", function(event) {
    alert("HELLO");
  });


Solution

  • Use this:

    // ==UserScript==
    // @name         New Userscript
    // @namespace    http://tampermonkey.net/
    // @version      0.1
    // @description  try to take over the world!
    // @author       You
    // @match        http://*/*
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        if (document.readyState == "complete" || document.readyState == "loaded" || document.readyState == "interactive") {
            alert("Already Loaded");
        } else {
            document.addEventListener("DOMContentLoaded", function(event) {
                alert("Just Loaded");
            });
        }
    })();
    

    Borrowed from How to detect if DOMContentLoaded was fired.