ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

Creating Javascript anonymous functions from strings

Jeffrey P. Bigham

Related Ads

If you're using the xmlhttprequest or GM_xmlhttpRequest methods to do AJAX-style coding, it's often easiest to define an anonymous function that will be called when the request completes. Unfortunately, if you make a lot of these requests, it can seem hard to distinguish them. Often you'll have or can easily create a string that gives you the information you need, perhaps based on the DOM Element id of the thing you want to change or, alternatively, based on the URL of the request. The following is what you'd like to do, but this won't work:


var my_identifier;
GM_xmlhttpRequest({
  method: 'GET',
  url: link,
  headers: {},
  onload: function() {alert(my_identifier);}
});

Unfortunately, this will equate to alert(undefined) because my_identifier is long gone by the time it's called. Instead, construct your function by first building a string and everything will work out just fine, as this example demonstrates:


var my_identifier;

GM_xmlhttpRequest({
  method: 'GET',
  url: link,
  headers: {},
  onload: new Function("requestDetails", 
    "alert(" + my_identifier + ");");
});

While this example was written using the Greasemonkey GM_xmlhttpRequest(...) method, a similar strategy can help you define similarly useful anonymous function wherever you need them.

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles