Search code examples
javascriptgoogle-chrome-extensionxmlhttprequest

Chrome Extension xmlhttprequest loading incorrect url


I am writing a chrome extension and in my extension, I have an XMLHttpRequest that gets JSON data back from the server. I then parse the JSON data looking for URLs.

The problem is that I then call XMLHttpRequest with the URL's I have obtained from the parsed JSON data but for some reason, my URL's have extra information.

The error below is what I get when calling XMLHttpRequest:

GET chrome-extension://kppcidkhcjeehdfhcaliekdbgpbkjahg/%22https://b.thumbs.redditmedia.com/BldqCmg1rCqffUDXXYjvO_CQ_58pYIfAGCuHY7dTBIw.jpg%22 net::ERR_FILE_NOT_FOUND

I don't understand why there is extra information in my URL. Whenever I output the var that contains the URL string to console.log it outputs correctly: https://b.thumbs.redditmedia.com/BldqCmg1rCqffUDXXYjvO_CQ_58pYIfAGCuHY7dTBIw.jpg

That above URL is what I want XMLHttpRequest to perform a GET request on, but it seems that the GET request fails because it is not a proper URL.

My initial XMLHttpRequest works when I hard-code the URL, and I have tested hard-coding the URL: https://b.thumbs.redditmedia.com/BldqCmg1rCqffUDXXYjvO_CQ_58pYIfAGCuHY7dTBIw.jpg which results in my XMLHttpRequest working fine.

Am I not allowed to perform GET requests on URLs I obtain dynamically from a remote server?


Solution

  • There are 2 %22 sequences in the faulty url. This is the encoding for a double quote. I think the variable with the url contains a string enclosed in double quotes. When you perform the GET request, it performs a request to the local filesystem of the extension. Hence the request to chrome-extension://

    One way to diagnose this kind of error, is to console.log the length of the variable containing your url and compare it to what it should be:

    var real_url = "https://b.thumbs.redditmedia.com/BldqCmg1rCqffUDXXYjvO_CQ_58pYIfAGCuHY7dTBIw.jpg";
    console.log(real_url.length);
    console.log(url.length);
    

    or console.log the first character of the string:

    console.log(url.substr(0,1)); // is this a double quote?
    

    Try to strip the extra quotes or change the code that's responsible for parsing the json data for the url.