我想获取外部网页的第一张图片,然后显示它。我使用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应用程序,而不是网站。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句