最近項目中使用到了umeditor 1.2.2,在圖片上傳的過程中遇到跨域問題。umeditor在圖片上傳模塊中使用iframe來獲取服務端的返回結果。衆所周知,在chrome等瀏覽器中是不允許iframe跨域訪問的。當在不同域下使用umeditor向服務器上傳圖片時,會報跨域錯誤.
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://xxxx.com/image/c0d23233851f4f40a0e40f9a0d431597.png?temp=0.9339469703071119 with MIME type application/xml. See https://www.chromestatus.com/feature/5629709824032768 for more details.
經過調試,查閱資料,看到github上有人說可以用window.name來跨域返回上傳結果,遂逐一調試,最後終於實現跨域上傳圖片功能。iframe利用window.name跨域原理網上已經有很多資料了,這裏就不在重複。主要講下如何修改umeditor來實現window.name跨域.由於項目服務端用的是JAVA,這裏我就用jsp來舉例,其他語言思路也是一致的.
其實umeditor使用window.name跨域非常簡單.
1.修改umeditor\jsp\imageUp.jsp中result字符串拼接,以<script>標籤返回結果.
String result = "<script>window.name='{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}' </script>";
2.新建一個空的proxy.html文件
3.修改umeditor\dialogs\image\image.js sumbit方法
var ifstate=0;
$('<iframe name="up" style="display: none"> </iframe>').insertBefore(me.dialog).on('load', function(){
if (ifstate === 1) {
var r = this.contentWindow.name;
if(r == '')return;
me.uploadComplete(r);
$(this).unbind('load');
$(this).remove();
} else if (ifstate === 0) {
ifstate = 1;
this.contentWindow.location = "./proxy.html";
}
});
這樣就解決了umeditor 的上傳圖片回顯的跨域問題