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

Javascript 如何从使用XMLHttpRequest检索的html文档中获取图像?,javascript,html,google-chrome-app,Javascript,Html,Google Chrome App,我想得到一个外部网页的第一个图像,然后显示它。我使用XMLHttpRequest从网页获取文档,然后搜索文档中的第一个图像,然后显示它。但是没有图像显示出来。这是用于chrome应用程序,而不是网页/网站。以下是我的javascript: var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://ab.reddit.com/', true); xhr.responseType = 'document'; xhr.onload = funct

我想得到一个外部网页的第一个图像,然后显示它。我使用XMLHttpRequest从网页获取文档,然后搜索文档中的第一个图像,然后显示它。但是没有图像显示出来。这是用于chrome应用程序,而不是网页/网站。以下是我的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
是图像斑点。我不太清楚为什么要这样做,可能是出于某种安全原因。我也把它变成了它自己的功能。
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应用程序,而不是一个网站。

尝试登录
img_src
以查看您得到了什么(如果有的话)。我无法检查登录到控制台的内容,因为我使用的是学校管理的Chromebook,并且该功能已被阻止。客户端网页抓取是不可能的。您将不得不在服务器端执行此操作。例如,你可以使用PhantomJS,但是还有更多的选择。虽然我可以通过这种方式检索直接图像,而且我可以将文档解析为字符串并显示htmlWell现在你有一个打字错误,
scr
,而不是
src
。另外,你应该警告你的学校系统管理员,他们忘记了锁定安装未打包的扩展..哦,对了,Chrome应用程序-我第一次读你的问题时就错过了。这里有一个完整的主题!(扰流板:它提供了完全相同的解决方案)