jquery listen for events in an iframe

和自甴很熟 提交于 2019-12-20 20:07:10

问题


I'm making a very simple Rich Text Editor using jquery... I don't want to use a third-party one.

I need to listen for events within an iframe (same domain etc), starting with typing. Apparently I'll need to use bind() a lot.

This is what I've got at the moment which works fine in IE8 (amazingly enough) but not Chrome.

<script>
$(function() {
    $('#text').contents().bind("keyup keydown keypress", function(e) {
        var code = e.keyCode || e.which;
        alert(code);
        return false;
    });
});
</script>

<body>
    <iframe id="text" name="text" src="edit.html"></iframe>
</body>

On the key press event above, I will also want to get the current value of 'edit.html' and update a textarea with that value...

Any help would be MUCH appreciated :)

Many thanks

EDIT: to explain further, edit.html is an editable file using "document.body.contentEditable = true;"

-

EDIT 2:

edit.html =

<script language="javascript">
    function InitializeIFrame() {
        document.body.contentEditable = true;                         
    } 

</script>
<html>
<body onload="InitializeIFrame();">

</body>
</html>

回答1:


I seem to recall running into a problem when I was trying to communicate with an iframe (same domain etc). The trick I found is to do the binding inside the frame and bind to functions in the main window. Something like this (in edit.html):

<script>
$('body').bind("keyup keydown keypress", function(e) {
  window.parent && window.parent.funcKey && window.parent.funcKey(e);
});
</script>

and then in the main page something like:

<script>
function funcKey(e) {
  var code = e.keyCode || e.which;
  alert(code);
  return false;
}
</script>

I realise this does not exactly fit into the way you were trying to do it, but the same effect is achieved. From what I understand of javascript and iframes, in practice it's easier to communicate with a parent than it is to communicate with an iframe. If you really need two-way communication you could (going on the example above) use the return value of the function funcKey() to pass data back into the iframe.




回答2:


One of the most annoying things about javascript is that document.frames["frameID"] returns a different object than document.getElementById("frameID"). (which is what you get when you use $("#frameID"))

This distinction is probably why you're running into cross-browser issues. You'll likely need to mess around with different ways of accessing the iframe contents until you find one that works correctly.



来源:https://stackoverflow.com/questions/5105620/jquery-listen-for-events-in-an-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!