Troubleshooting (Script Authors): Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
Added xhr callback/binding prob
No edit summary
Line 1: Line 1:
__TOC__
The article [http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey-pitfalls.html Avoid Common Pitfalls in Greasemonkey] covers some of the most common problems people come across when writing [[user script]]s.
The article [http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey-pitfalls.html Avoid Common Pitfalls in Greasemonkey] covers some of the most common problems people come across when writing [[user script]]s.



Revision as of 06:55, 28 March 2007

The article Avoid Common Pitfalls in Greasemonkey covers some of the most common problems people come across when writing user scripts.

If your problem is not listed, please ask on the mailing list.

When using GM_xmlhttpRequest or setTimeout, variables change before the callback runs

Problem example:

 for (var i=0; i < document.links.length; i++) {
   var link = document.links[i];
 
   GM_xmlhttpRequest({
     method: "GET",
     url: 'http://example.com/lookup?url=' + link.href,
     onload: function(result) {
       link.href = result.responseText;
     }
   });
 }

The request is asynchronous, meaning the rest of the code doesn't wait for it to complete. The for keeps running as the request loads. When the request for the first link on the page completes and the onload callback function runs, the link variable might point to a different link altogether, typically the last one (since the for loop completes much quicker than the HTTP requests).

One solution is to pass those values that you want unchanged into a function surrounding the request, as arguments. Then they will be in a different scope, and will no longer be changed from the outside.

Solution example with named function:

 function do_it(link_inside) {
   GM_xmlhttpRequest({
     method: "GET",
     url: 'http://example.com/lookup?url=' + link.href,
     onload: function(result) {
       link_inside.href = result.responseText;
     }
   });
 }
 
 for (var i=0; i < document.links.length; i++) {
   var link = document.links[i];
 
   do_it(link);
 }

Solution example with anonymous function:

 for (var i=0; i < document.links.length; i++) {
   var link = document.links[i];
 
   (function (link_inside) {
 
     GM_xmlhttpRequest({
       method: "GET",
       url: 'http://example.com/lookup?url=' + link.href,
       onload: function(result) {
         link_inside.href = result.responseText;
       }
     });
 
   })(link);
 }

Links