Search code examples
javascriptgoogle-apps-script-editor

HTMLElement.click() would not fire an expected event


I try to use some simple native javascript code, in order to simulate a user click on a button at script.google.com:

document.querySelector("#runButton").click();

When I do it, nothing really happens, but when I really click on this element (#runButton), I can see a popup shows up.

It might have something to do with the fact that #runButton is a div, cause when I do the same with anchor() elements, it works.

Any ideas what I can do to better simulate this click? Something specific about google apps script editor that prevents me from doing it?


Solution

  • Looks like Google Apps Script editor supresses programmatic click events on interface buttons, here is solution to emulate "click" on those buttons:

    function doClick(n)
    {
        e = document.createEvent("MouseEvents");  
        e.initEvent("mousedown", true, false);  
        n.dispatchEvent(e,true); 
        e = document.createEvent("MouseEvents");  
        e.initEvent("mouseup", true, false);  
        n.dispatchEvent(e,true);
    }
    
    // do the click
    doClick(document.getElementById("runButton"));