如何从使用 XMLHttpRequest 检索到的 html 文档中获取图像?

How to get image from html document retrieved with XMLHttpRequest?

我想获取外部网页的第一张图片,然后显示出来。我使用 XMLHttpRequest 从网页获取文档,然后搜索该文档中的第一张图片,然后显示它。但是没有图像显示。这是针对 chrome 应用程序,而不是网络 page/website。这是我的 javascript:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://ab.reddit.com/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
  var ext_doc = this.response;
  var img_src = ext_doc.getElementsByTagName("img")[0];
  var img_html = document.querySelector('#TestImage2');
  img_html.src = img_src.src;
};
xhr.send();

我想通了。我无法直接将图像 src 设置为从外部 html 文档检索到的外部图像的 url src。我必须为新发现的图像 scr url 发送另一个 XMLHttpRequest 并将其作为 blob 检索。然后设置图片src为window.URL.createObjectURL(this.response)this.response 是图像 blob。我不太确定为什么必须这样做,可能出于某些安全原因。我也把它放到它自己的函数中。 pgURL参数是要获取图片的网页的url。 index是网页所有图片列表中想要的图片的索引。 display 是要更改的图像 html 元素。

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();
}

提醒!这是针对 chrome 应用程序,而不是网站。