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

标签 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 = 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 应用程序,而不是网站。

关于javascript - 如何从使用 XMLHttpRequest 检索的 html 文档中获取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665162/

相关文章:

javascript - 有多个模块的名称仅在外壳 React 上不同

html - 调整表格大小时,Chrome 渲染错误,标题背景粘在另一个 div 之上

javascript - 使用 chrome 打包的应用程序/扩展程序将数据保存在文本文件中

javascript - 如何在 Google Chrome 应用程序上发布 JSON?

javascript - 如何在jade中进行嵌套迭代?

javascript - Jquery 绑定(bind)/实时使用动态值

javascript - 将 textarea 列的编号设置为等于容器/表格的宽度

php - 需要锁定登录页面中的文本框?

google-chrome-app - 在 Chrome 打包应用程序中使用 MySQL 和 PHP?

javascript - 检测某些元素外的点击