Search code examples
javascriptjsonfirefoxgoogle-chromeuserscripts

XMLHttpRequest for JSON file works perfectly in Chrome, but not in Firefox


I've narrowed my problem area down to the function below. It's part of a userscript I'm writing. It works perfectly in Chrome, but doesn't work at all in Firefox/Greasemonkey. I've tinkered with it all day and have hit a brick wall. The only thing that makes sense is if JSON.parse isn't working right, which would make sense since Chrome is known to handle JSON.parse somewhat differently... but I know the JSON is perfectly formed!

function getTagline() {
    var jsonfile = new XMLHttpRequest();
    jsonfile.open("GET", "http://example.com/somegood.json", true);
    jsonfile.onreadystatechange = function() {
        if (jsonfile.readyState == 4) {
            if (jsonfile.status == 200) {
                var taglines = JSON.parse(jsonfile.responseText);
                var choose = Math.floor(Math.random() * taglines.length);
                var tagline = document.createTextNode(taglines[choose].metais);
                insertTagline(tagline);
            }
        }
    };
    jsonfile.send(null);
}

Any ideas?


Solution

  • After some more troubleshooting, it turns out the was a cross-domain XHR issue. It was working in Chrome because, by default, Chrome was allowing the script on all domains. I tweaked the headers so Chrome knew to only allow the proper domains, but Firefox disallows cross-domain on XHR regardless. This was fixed by simply switching to GM_xmlhttpRequest instead, which allows cross-domain in Firefox and, thankfully, which Chrome also supports.

    Thanks for the help, folks!