I figured out the issue. I cannot directly set the image src to the retrieved url src of the external image from the external html document. I have to send another XMLHttpRequest for the newly found image scr url and retrieve it as a blob. Then set the image src to window.URL.createObjectURL(this.response)
. this.response
being the image blob. I am not quite sure why it has to be done this way, probably for some security reason. I also put this into its own function. The pgURL
parameter is the url of the web page for images to be retrieved. index
is the index of the image wanted in the list of all the images on the web page. And display
is the image html element to be changed.
function getImage(pgURL, index, display)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', pgURL, true);
xhr.responseType = 'document';
xhr.onload = function(e) {
var doc = this.response;
var img_src = doc.getElementsByTagName("img")[index];
var src = img_src.src;
//Have to make a new XMLHttpRequest for the image found because img sources cannot be directly set
var xhr2 = new XMLHttpRequest();
xhr2.open('GET',src);
xhr2.responseType = 'blob'; //Must make blob object of retrieved image
xhr2.onload = function(e){
display.src = window.URL.createObjectURL(this.response); //Finally set the src for the image
};
xhr2.send();
};
xhr.send();
}
REMINDER! This is for a chrome app, not a website.