Search code examples
javascripthtmlformsgreasemonkeyform-submit

Trying to simulate the clicking of a button with greasemonkey


I'm trying to write a greasemonkey script that updates inventory for a collection of items through the browser. To do this I need to autofill a few forms and simulate a mouseclick on the submission button. I have the forms filling out fine, but I'm stuck on the button submission.

Here is the HTML for the button I am trying to simulate clicking

<input type="submit" value="Find" style="" name="process-form" onclick="imhocaller.value='find-resources-page.left'; imhoaction.value='process-form';">

I tried doing something like this, but haven't had any luck.

document.getElementsByName('process-form').submit();

I can post more code if needed. Thank you!


Solution

  • You can also dispatch a custom click event via most recent browsers and "fire" an onclick event in IE. This is a recent feature that allows tons of control over events.

    var button = document.getElementById("test");
    button.onclick = function()
    {
        alert("event was dispatched on me");      
    }
    if(document.createEvent)
    {
        var click = document.createEvent("MouseEvents");
        click.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);
        button = document.getElementById("test");
        button.dispatchEvent(click);
        button.focus();
    }else if(document.documentElement.fireEvent)
    {
        button = document.getElementById("test");
        button.fireEvent("onclick");
        button.focus();
    }
    

    http://jsfiddle.net/ZWyp7/3/

    Do note that you need to listen for the event before dispatching it.