2016-11-17 39 views
0

我想获取外部网页的第一张图片,然后显示它。我使用XMLHttpRequest从网页获取文档,然后搜索该文档中的第一个图像,然后显示它。但没有图像出现。这是一个Chrome应用程序,而不是一个网页/网站。这是我的javascript:如何从使用XMLHttpRequest检索的html文档中获取图像?

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(); 
+0

尝试记录'img_src'来看看你得到了什么(如果有的话)。 –

+0

我无法查看登录到控制台的内容,因为我在学校管理的Chromebook上,并且该功能被阻止。 – Hobbs2000

+0

由于安全问题,客户端Web抓取是不可能的(http://stackoverflow.com/a/31626877/6941627)。你必须去服务器端。例如,您可以使用PhantomJS,但还有更多的选择。 –

回答

1

我想通了这个问题。我无法直接将图像src设置为从外部html文档中检索到的外部图像的url src。我必须为新发现的图像scr url发送另一个XMLHttpRequest并将其作为blob检索。然后将图像src设置为window.URL.createObjectURL(this.response)this.response是图像blob。我不太清楚为什么必须这样做,可能出于某种安全原因。我也把这个放到了自己的职责中。 pgURL参数是要检索图像的网页的网址。 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应用程序,而不是一个网站。

+0

哦,对,Chrome应用程序 - 我错过了第一次阅读您的问题。这里有一个关于主题的完整的[文档文章](https://developer.chrome.com/apps/app_external)! (剧透:它提供了非常相同的解决方案) – Xan

相关问题