javascript - greasemonkey - adding onclick event to existing button - Stack Overflow

admin2025-04-19  0

I'm currently writing a Greasemonkey script to add an onclick event to an existing button, to show a confirmation popup window.

This is the existing html:

<input type="button" id="previewOrder" title="" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false" value="Preview Order">

I came up with the following javascript but it does not work or fails

function confirm () {
    alert ("Sure?");
}

document.getElementById("previewOrder").addEventListener("click", confirm(), false);

Any suggestions on how to get this working?

I'm currently writing a Greasemonkey script to add an onclick event to an existing button, to show a confirmation popup window.

This is the existing html:

<input type="button" id="previewOrder" title="" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false" value="Preview Order">

I came up with the following javascript but it does not work or fails

function confirm () {
    alert ("Sure?");
}

document.getElementById("previewOrder").addEventListener("click", confirm(), false);

Any suggestions on how to get this working?

Share Improve this question asked Jun 21, 2016 at 22:40 AureliaAurelia 471 silver badge4 bronze badges 1
  • you can't call your function confirm, which is vauge anyway. call it something meaningful to and avoid the conflict. – dandavis Commented Jun 22, 2016 at 0:08
Add a ment  | 

2 Answers 2

Reset to default 3

confirm() is native window method. Therefore put it in a function :

function myFunction() {
    confirm( ... );
}

Example :

function myFunction() {
  confirm("Sure?");
}

document.getElementById("previewOrder").addEventListener("click", myFunction);
<input type="button" id="previewOrder" title="" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false" value="Preview Order">

Thanks for helping out. In the end it appears the reason it was not working on my side is that the script was executed before the page (and in particular the target element) was loaded. After adding the waitForKeyElements() utility the code was working.

See https://stackoverflow./a/12899331/3149095

function myConfirm () {
confirm ("Sure?\n\nCheck rules.\n\n");
}

function setConfirm () {
document.getElementById("previewOrder").addEventListener("click", myConfirm);
}

waitForKeyElements ("#previewOrder", setConfirm);

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745042125a281608.html

最新回复(0)