XmlHttpRequest in a bookmarklet returns empty responseText on GET?

Posted by David Eyk on Stack Overflow See other posts from Stack Overflow or by David Eyk
Published on 2010-04-26T17:46:06Z Indexed on 2010/04/28 18:47 UTC
Read the original article Hit count: 337

I'm trying to build a javascript bookmarklet for a special URL shortening service we've built at http://esv.to for shortening scripture references (i.e. "Matthew 5" becomes "http://esv.to/Mt5". The bookmarklet is supposed to do a GET request to http://api.esv.to/Matthew+5, which returns a text/plain response of http://esv.to/Mt5.

The code for the bookmarklet itself looks like this (expanded for readability):

var body = document.getElementsByTagName('body')[0], script = document.createElement('script');     
script.type = 'text/javascript';
script.src = 'http://esv.to/media/js/bookmarklet.js';
body.appendChild(script);
void(0);

The code from http://esv.to/media/js/bookmarklet.js looks like this:

(function() {

    function shorten(ref, callback) {
      var url = "http://esv.to/api/" + escape(ref);
      var req = new XMLHttpRequest(); 
      req.onreadystatechange = function shortenIt() {
        if ( this.readyState == 4 && this.status == 200 ) {
          callback(req.responseText);
        };
      };
      req.open( "GET", url );
      req.send();
    };

    function doBookmarklet() {
      var ref = prompt("Enter a scripture reference or keyword search to link to:", "")
      shorten(ref, function (short) {
        prompt("Here is your shortened ESV URL:", short);
      });
    };

    doBookmarklet();

})();

When called from http://esv.to itself, the bookmarklet works correctly. But when used on another page, it does not. The strange thing is, when I watch the request from Firebug, the response is 200 OK, the browser downloads 17 bytes (the length of the returned string), but the response body is empty! No error is thrown, just an empty responseText on the XmlHttpRequest object.

Now, according to http://stackoverflow.com/questions/664689/ajax-call-from-bookmarklet, GET shouldn't violate the same origin policy. Is this a bug? Is there a workaround?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about bookmarklet