Greasemonkey adds onclick event to button

I am attaching an onclick event to a dynamically created button, but the event does not fire.

var ind = location.href.indexOf('http://www.example.com/'); function init(){ alert('h'); } if(ind != -1){ var elem = document.createElement("input"); elem.id ='btnGumb'; elem.value = 'Select Check box'; elem.type = 'button'; elem.style.position = 'fixed'; elem.style.left = '0px'; elem.style.top = '0px'; //this is not working elem.setAttribute('onclick', 'init();'); //but alert is working: elem.setAttribute('onclick', 'alert("h");'); document.body.appendChild(elem); } 
+4
source share
2 answers

Use addEventListener .

 elem.addEventListener('click', init, false); 

Your init function is not defined in the content page window, so you cannot set the function name as a string.

+2
source

I did not work with GreaseMonkey, but I assume that your script is in its own area, and all of its variables are freed after the script completes. Since you define init in this area, but then call it on the main page, the function is undefined when it is called.

You can put the whole function in an onclick event or call a callback:

 if (elem.addEventListener) { elem.addEventListener('click',init,false); } else { elem.attachEvent('onclick',init); } 

(attachEvent is IE specific)

+1
source

All Articles