TamperMonkey用户脚本不会触发DOMContentLoaded事件

时间:2016-06-13 19:57:02

标签: javascript tampermonkey

这是TamperMonkey用户。为什么不“HELLO”弹出窗口?我在Ubuntu上运行Google Chrome。

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

1 个答案:

答案 0 :(得分:2)

使用此:

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

借鉴How to detect if DOMContentLoaded was fired