Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在iframe中优雅地使用父窗口中的$ #5

Open
liusaint opened this issue Aug 22, 2017 · 0 comments
Open

在iframe中优雅地使用父窗口中的$ #5

liusaint opened this issue Aug 22, 2017 · 0 comments

Comments

@liusaint
Copy link
Owner

最近在给项目中的富文本编辑器进行更换。由tinymce改成kindeditor。
之前tinymce是由离职同事引入的。并且对其源码进行了一些修改。增加了一些自定义的功能。这几天给它切换成kindeditor编辑器,并且要将我们自定义的功能也迁进来。 

富文本编辑器的内容区一般是iframe中。我要在iframe中引入js代码。
有一些常用的功能需要用到$以及KindEditor中的接口,在iframe中重新引入一个jQuery或KindEditor文件显然是不划算的。那么直接取得两个iframe之外的现成的对象又如何?

直接引入

var $ = parent.$;
var KindEditor = parent.KindEditor;

这样的话,我们就可以使用对象的大部分接口方法了。

需要注意的是,由于我们的js的初始化环境是在parent环境,这些接口方法也是在这个环境里生成的,那么由于作用域原理,在库中使用到的document\window等宿主对象也是指向的parent中的对象而不是当前iframe中的对应对象。
所以有些接口不能那么放心地使用。

举个例子:

比如iframe中有一个

<span class="a"></span>

在iframe中输入使用$('.a')是找不到它的。它实际上是在父窗口里面在找。
但是我们可以使用find方法。它是一个相对安全的方法。
 

var body = document.getElementsByTagName('body')[0];
$(body).find('.a');//注意这里的body没有引号

简单讲,如果你发现你在iframe中引入的parent窗口的对象的某些方法没有正常运行,你可能要考虑它的一些作用域引起的问题。
不过其实大多数方法是安全而有效的。比如addClass()、offset()等。
如果方法不是那么有效,那么也是一定有替代方法的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant