SettimeOut间隔失败,显示“无法将undefined或null转换为object”

问题描述 投票:5回答:3

我正在使用tampermonkey进入用户脚本,无法解决此错误,任何帮助将不胜感激。

我检测到键很好,空格键触发此功能,只要键保持在向下位置,它就会重复。控制台或多或少地正常写入输出30秒,然后出现TypeError。

根据声誉限制,这是一个截图:

用户脚本:

// ==UserScript==
// @name         TEST STUFF--------------------
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @run-at         document-start
// @include        http://*
// @include        https://*
// @grant        none
// ==/UserScript==

( function()
{
    'use strict';
    window.addEventListener ( "keydown", CaptureKeyPress );
    window.addEventListener ( "keyup", CaptureKeyPress );
    var Hotkeys =
    {
        perform: 32
    };
    var HotkeyToggle = false;
    function CaptureKeyPress ( a )
    {
        if ( a.keyCode == Hotkeys.perform )
        {
            a.preventDefault();
            a.stopPropagation();
            a.cancelBubble = true;
            a.stopImmediatePropagation();

            if ( a.type == "keydown" && !HotkeyToggle )
            {
                console.clear();
                HotkeyToggle = true;
                perform();
            }

            if ( a.type == "keyup" && HotkeyToggle )
            {
                HotkeyToggle = false;
            }
        }
    }
    function perform()
    {
        if(HotkeyToggle == false) // exit
        {
            return 0
        }
        //do stuff...

        console.info("working...");
        if(HotkeyToggle == true) // continue after everything completes
        {
            setTimeout(() => {
                perform()
            }, 280);
            return 0
        }
        return 1
    }
} ) ();

javascript userscripts tampermonkey
3个回答
4
投票

这可能是特定于TamperMonkey的问题,也可能是Chrome本身的新安全策略/错误 - 我遇到了同样的事情并在调试器中捕获了它,并且没有任何参数是null / undefined; setTimeout未被覆盖。

编辑:有问题的用户脚本与我正在调试的用户脚本之间的共享特征是setTimeout的“递归”使用。我改为将其改为setInterval,这似乎已经解决了我的情况。 enter image description here


3
投票

这是Chrome中已确认的错误:

Reported on TM github

Reported on bugs.chromium.org

另一个看起来有效的解决方案是.bind window的功能,例如:

window.clearTimeout = window.clearTimeout.bind(window);
window.clearInterval = window.clearInterval.bind(window);
window.setTimeout = window.setTimeout.bind(window);
window.setInterval = window.setInterval.bind(window);

该错误应该在Chrome 75中修复。


2
投票

我使用Tampermonkey和谷歌浏览器时遇到了同样的问题。对我有用的是使用window.setTimeout而不是setTimeout

© www.soinside.com 2019 - 2024. All rights reserved.