2016-11-17 45 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

相關問題