Posted By

noah on 12/04/08


Tagged

regex edit hack data event rails String functions macros eventhandlers LISP alter


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Alter an existing, hard-coded onclick function


 / Published in: JavaScript
 

URL: http://www.urbandictionary.com/define.php?term=omg%20hax

Get the existing hardcoded function, convert it to a string, edit the string. Then strip the string down to just the function body, re-instantiate the string into a function, and assign it back to the onclick handler.

The code here is extremely site-specific. Here's what the original onclick function I was working against looked like:

new Ajax.Request('/publications?categories%5B%5D=1,2,3', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent('6b670face4ca93ce4bf53def7685d8663780b7d9')}); return false;

The code below just changes the query string in the first parameter. The idea being that you have a bunch of checkboxes with IDs like foo-1, foo-2, and you want that query pram to reflect the number thats appended to the end of each checkbox's ID.

Not that you want to do that :) But hey, these kinds of situations sometimes come up in production. Anyway, the interesting bit is JavaScript's ability to break a function down into a string, edit the string, and then re-instantiate the string as a new function, possibly overriding the original.

Functions as data: Mmmm... Lispy.

Tested only in Firefox 3 but should work in any browser.

  1. /*
  2.   * When the button is moused over, the user is probably about to click
  3.   * At that pont, recalculate the onclick method
  4.   * so as to give the correct category list parameter to Rails
  5.   */
  6. Event.observe('filterButton', 'mouseover', function() {
  7. var allthecheckboxes = $$('#catfilter li input');
  8. var selectedCats = [];
  9. var railsAjaxFn = this.onclick.toString();
  10. allthecheckboxes.each(function(el){
  11. if (el.checked) {
  12. var cat = el.id.match(/\d+$/);
  13. if (cat != null) {
  14. var catnumber = cat[0];
  15. selectedCats.push(catnumber);
  16. //console.debug(el, catnumber, selectedCats);
  17. }
  18. }
  19. });
  20. //console.debug(selectedCats);
  21. var newFnString = railsAjaxFn.replace(/\?.*?\"/, '?' + escape('[]') + '=' + selectedCats.toString() + '\"');
  22. var fnBodyString = newFnString.match(/.*}/g)[0];
  23. var newFn = new Function(['event'], fnBodyString + ');\n return false;');
  24. this.onclick = newFn;
  25. console.debug(fnBodyString, newFn);
  26. //this.onclick();
  27. });

Report this snippet  

You need to login to post a comment.