Changing onclick for a greasemonkey function before it is defined

571 views Asked by At

I will describe my problem, hopefully someone can provide a solution.

I am adding a GreaseMonkey script to an existing page, the page loads with ajax an element with an onclick:

onclick="getProperty('http:/...')"

I searched for a way to override their getProperty, which was hard on itself because I can't know what object will have this onclick before it arrives via ajax. I can't bind my own click and unbind the previous one because there's no trigger for such a function when the content is dynamic. I tried adding my click and preventing the previous from being called by that doesn't work. The selector I'm using looks like this:

a[onclick^='getProperty']

What I discovered was a method someone wrote for this exact problem, called waitForKeyElements. I hope someone here is already familiar with it. What it does is check if an element matching a selector was added by ajax to the page, and if so runs a function.

This method let me workaround binding my function to override theirs:

waitForKeyElements("a[onclick^='getProperty']", updateToNewGetProperty);

function updateToNewGetProperty(ajaxLinks){        
        ajaxLinks.each(function(){
            var oldOnclick = $(this).attr("onclick");
            var UrlStartPos = oldOnclick.indexOf('\'') + 1;
            var UrlEndPos = oldOnclick.indexOf('\'',UrlStartPos);
            var Url = oldOnclick.substring(UrlStartPos,UrlEndPos);

            $(this).attr("onclick", ""); // unbind
            $(this).click(function() { // bind mine
              myGetProperty(Url);
              return false;
              });
      });
  }

This works, it unbinds the previous javascript onclick and sets the jquery click.

However then I discovered that another segment of their code grabs the URL value that is inside the onclick, so I can't use the jquery click bind as that leaves the onclick empty.

I had to revert back to:

$(this).attr("onclick",$(this).attr("onclick").replace('getProperty', 'myGetProperty'));

This returns function not defined when clicking the link, I believe because the original page loads the ajax content before the greasemonkey is fully loaded. Triggering the waitForKeyElements before my function is registered.

Any help / advice would be greatly appreciated

0

There are 0 answers