2015-12-07 26 views
1

在我的網頁中我有一個圖像標記,其源代碼通過https連接從api獲取圖像,有時此請求會失敗並重定向到http連接上的錯誤圖像,用戶警告一些網頁部件處於不安全連接。有沒有一種方法可以防止瀏覽器使用不安全的鏈接,或者以某種方式通過https將它下載到https上。防止重定向與http圖像標記src

<img src="https://example.com/image_320x240.png"/> 

API不總是有準備的圖像,這樣會重定向到

<img src="http://example.com/error_320x240.png"/> 

誤差圖像也可在HTTPS,但我不知道瀏覽器是如何使用它使用js或在下載圖片之前檢查網址。

+0

只要您控制映像託管的服務器,並且可以使用SSL,爲什麼不只是將協議更改爲https以獲取錯誤圖像? – adeneo

+0

也許嘗試加載圖像與JS –

+0

我不控制在服務器上的API託管 –

回答

0

如果上面的圖像沒有準備好,您能提供自己的錯誤圖像嗎?

也許是這樣的:

function populateImage(url, element) { 
    var req = new XMLHttpRequest(); 
    req.open('Get', url); 
    req.onreadystatechange = function() { 
    if (req.readyState === 4) { 
     var img = document.CreateElement('img') 
     if (req.status === 200) { 
     img.src = url; 
     } else { 
     img.src = 'https://path.to.my.errorImage'; 
     } 
     element.appendChild(img); 
    } 
    }; 
    req.send(); 
} 



<p id='placeholder'></p> 
populateImage('https://exmple.com/320x240.png',document.getElementById('placeholder')); 
0

您可以嘗試通過加載通過JavaScript的圖像來解決這個問題:在HTML

var img = new Image(); 
img.onerror = function(e) { 
    // Do something on error. Load other image? 
} 
img.onload = function() { 
    if (this.src.match(/https:/)) { 
    document.getElementById('foo').src = this.src; 
    } else { 
    this.src = this.src.replace('http:', 'https:'); 
    } 
}; 
img.src = 'https://example.com/image_320x240.png'; 

你的圖像元素看起來是這樣的:

<img src="" alt="" id="foo" /> 

代碼的功能是通過javascript加載圖像。如果圖像被加載,則加載的圖像的URL被檢查。如果URL是安全的,那麼通過將圖像分配給DOM中的元素來顯示圖像。如果沒有,那麼這個不安全的url就會變成一個安全的url,並且新的url的圖像被加載。

我希望這可以幫助你進一步。