最近项目中使用到了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 的上传图片回显的跨域问题