之前測試了傳送文字訊息(HTML5 使用postMessage在不同網頁之間傳送文字訊息),
現在下面的範例,則是測試傳送圖片資料。
之前傳送給 window.open 開啟的頁面,現在改測試傳給 iframe 開啟的頁面。
註:
此範例在 chrome、IE11 測試正常,但在 Firefox 29.0.1 會出現 DataCloneError: The object could not be cloned. 錯誤。
但若改成使用 window.open 開啟接收頁面,且不跨網域,Firefox 也可正常運作。
傳送圖片頁面 (http://demo.cinc.biz/html5-postmessage/img.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 使用postMessage在不同網頁之間傳送文字訊息(傳送頁面)</title>
<style>
</style>
</head>
<body>
HTML5 使用postMessage在不同網頁之間傳送圖片(傳送頁面)<br>
測試範例:<br>
1.選擇圖片:<input id="pic_file" type="file" onchange="showPic()"/><br>
<img id="myimg" src="" width="300"/><br>
2.<button onclick="sendImg()">傳送圖片到 iframe 頁面</button>
<br><br>
<iframe id="myiframe" src="http://demo2.cinc.biz/html5-postmessage/img-new.html" width="500" height="300"></iframe>
<script>
window.URL = window.URL || window.webkitURL;
/* 傳送圖片給 Iframe */
function sendImg() {
var frame_win = document.getElementById("myiframe").contentWindow;
var img = document.getElementById("pic_file").files[0];
frame_win.postMessage(img, "http://demo2.cinc.biz");//表示要送給demo2.example.com網域
}
/* 圖片預覽 */
function showPic() {
var img = document.getElementById("pic_file").files[0];
if (img) {
var img_url = window.URL.createObjectURL(new Blob([img]));
document.getElementById('myimg').src = img_url;
}
}
</script>
</body>
</html>
接收圖片頁面 (http://demo2.cinc.biz/html5-postmessage/img-new.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 使用postMessage在不同網頁之間傳送圖片(接收頁面)</title>
<style>
</style>
<script>
window.URL = window.URL || window.webkitURL;
var myMsg = function(e) {
alert("接收到的資料:" + e.data);
alert("資料來源網域:" + e.origin);
if (e.origin != "http://demo.cinc.biz") {
alert("不明來源,不處理");
return; //不明來源,不處理
}
var img_url = window.URL.createObjectURL(new Blob([e.data]));
document.getElementById('myimg').src = img_url;
};
window.addEventListener("message", myMsg, false);//監聽message事件
</script>
</head>
<body>
HTML5 使用postMessage在不同網頁之間傳送圖片(接收頁面)
<img id="myimg" width="400"/>
</body>
</html>
DEMO:
http://demo.cinc.biz/html5-postmessage/img.html
參考:
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
https://developer.mozilla.org/en-US/docs/Web/API/Window.URL
https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL
https://developer.mozilla.org/en-US/docs/Web/API/Blob
沒有留言:
張貼留言