Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greasemonkey adding onclick event to button

I am attaching onclick event on dynamically created button but the event is not firing.

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); 

}
like image 654
coure2011 Avatar asked Aug 04 '10 05:08

coure2011


2 Answers

Use addEventListener.

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

Your init function isn't defined on the content page window, so you can't set the function name as a string.

like image 56
Matthew Flaschen Avatar answered Nov 14 '22 08:11

Matthew Flaschen


I haven't worked with GreaseMonkey, but I'm guessing your script is in its own scope and all its variables are released after the script finishes running. Since you're defining init in this scope, but then calling it on the main page, the function is undefined when it's called.

You could put the entire function in the onclick event or trigger a callback:

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

(attachEvent is IE-specific)

like image 28
Anthony DiSanti Avatar answered Nov 14 '22 08:11

Anthony DiSanti