Search code examples
javascriptjquerytampermonkey

Tampermonkey script gives "targetNode.dispatchEvent is not a function"


I want to click a button using Tampermonkey, but get this error:

userscript.html?id=2514f475-79e4-4e83-a523-6fef16dceeaa:10617 Uncaught TypeError: targetNode.dispatchEvent is not a function at triggerMouseEvent...

My script:

// ==UserScript==
// @name         Lootbits
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       Zan Draklar
// @match        https://lootbits.io/*
// @require      https://code.jquery.com/jquery-3.4.0.js
// ==/UserScript==

var gems = 0

$(document).ready(function() { 
    if($('#claimbtn').length) {
        simulateMouseClick('#claimbtn');
    }
})
function simulateMouseClick(targetNode) {
    function triggerMouseEvent(targetNode, eventType) {
        var clickEvent = document.createEvent('MouseEvents');
        clickEvent.initEvent(eventType, true, true);
        targetNode.dispatchEvent(clickEvent);
    }
    ["mouseover", "mousedown", "mouseup", "click"].forEach(function(eventType) {
        triggerMouseEvent(targetNode, eventType);
    });
}
setInterval(function() {
    $("#lootbits").val(function(e) {
        gems = $(this).text();
    });
    if(gems>0) {
        $('#lootboxout > div > div > div.lootbox-side.lootbox-side-front').click()
    }
}, 2000);
setInterval(function() {
    location.reload()
}, 605000);

Solution

  • Change: simulateMouseClick('#claimbtn'); to: simulateMouseClick($('#claimbtn'));

    Change: targetNode.dispatchEvent(clickEvent); to: document.querySelector("#claimbtn").dispatchEvent(clickEvent);