最近公司项目中需要做一个简易的BBS论坛,相应的就需要富文本编辑器,之前使用过CFeditor,但UI总感觉不适合个人喜爱,经过对比后选择了百度开源的UEditor。
目前最新版本:1.4.3,以下使用及配置都是基于此版本。
UEditor官网地址:http://ueditor.baidu.com/website/
1. 配置
定义页面展现的对象
<script id="message" name="message" type="text/plain">
或
<textarea id="message"></textarea>
引入UEditor的JS文件
<script type="text/javascript" src="${contextPath}/ueditor/ueditor.config.js"></script> <script type="text/javascript" src="${contextPath}/ueditor/ueditor.all.min.js"></script>
根据实际情况,修改相应的配置
<script type="text/javascript"> window.UEDITOR_HOME_URL = "${contextPath}/ueditor/"; window.onload = function () { window.UEDITOR_CONFIG.initialFrameWidth = 1600; window.UEDITOR_CONFIG.initialFrameHeight = 600; UE.getEditor("message"); } </script>
运行所在的WEB应用,浏览相应的页面就可以看到UEditor效果;
2. 问题:
由于这个论坛只是公司项目中的一个子项目,且此工程需要集成到一个信息门户CMS中,在现有项目中是通过iframe的方式将这个工程内嵌到信息门户CMS的,这里会遇到iframe跨域的问题,好在我们的项目是集成部署的,最终配置的域名统一,例如信息门户CMS地址为www.test.com,论坛地址:bbs.test.com,他们的根域都是test.com,所以在集成中通过设置document.domain来解决跨域造成的iframe高度自适应问题
document.domain = "test.com";
具体代码如下:
a. 在信息门户CMS的iframe所在页面中设置域名
document.domain = "test.com";b. 在信息门户CMS中创建共用JS,由第三应用(这里就是BBS论坛)调用这个JS文件,我们这里默认称它为代理JS,取名为agent.js,只有一句话;
document.domain = "test.com";c. 在BBS论坛中,在公用页面引用agent.js
<script type="text/javascript" src="http://www.test.com/agent.js"></script>d.这样就解决了iframe的跨域问题,可以互相访问对方应用页面中的document对象,我们这里需要解决的是iframe跨域高度自适应的问题,那么我们就可以在CMS页面onload时,通过获取iframe页面中的实际高度来设置iframe具体的高度。
e. 但后面的问题又来了,iframe中的页面的高度是不断变化的,所以我们又需要根据iframe的高度变化来动态改变CMS页面的高度,此时我们可以通过setInterval动态个性iframe的高度
f. 我们默认设置iframe的初始高度小一些,这样比较明显
g. 这里我们是解决的iframe跨同子域的问题,如何实现完全跨域的iframe高度自适应的问题,可以参照链接:
http://www.cnblogs.com/snandy/p/3900016.html
http://blog.sina.com.cn/s/blog_63940ce201015w0d.html
再回到我们的UEditor,由于内嵌在CMS中的页面设置了document.domain = “test.com”,而我们的UEditor上传图片,上传视频等 ,需要新打开一个窗口,且窗口是通过iframe进行加载的,这里初步的弹出窗口域名为bbs.test.com,两者不在一个域名下,此时我们的UEditor就无法正常使用,此时我们就得个性UEditor默认的配置
a. 修改ueditor/dialogs/internal.js文件,在第一行,即在var parent = window.parent;上方增加:document.domain = “test.com”,但此时只能解决在chrome和firefox中跨域的问题,但在IE在还是无法使用,提示“没有权限”,此时我们需要再修改editor.all.js
将:
src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') + 'document.write("' + html + '");document.close();}())'
修改为:
src: 'javascript:void(function(){document.open();' + 'document.domain="test.com"' + 'document.write("' + html + '");document.close();}())'
同时在方法Editor.prototype._setup中me.document = doc;下方增加document.domain = “test.com",至此终于解决了跨子域的问题。