Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Event in iFrame

I'm building a WYISWYG editor with an iframe with designMode = 'on'.

The problem is that I can't use any event on the iframe in Firefox and Opera (IE untested), for example I would like to track the onkeyup event:

document.getElementById("myFrame").onkeyup = function(){
    doSomething...
}

But doesn't works in the parent window.

I tried in the iframe too with this:

top.frames[0].onkeyup = function(){
        doSomething...
}

and all kind of stuff like these:

top.document.frames[0].onkeyup
top.frames["myFrame"].onkeyup
top.frames[0].document.onkeyup

But none of them wants to work so at the end turned out that even window.onclick doesn't works, so now I'm a bit confused...

What's the solution for this?

EDIT

The problem seems to be with document.designMode = "on" in the iframe

like image 891
Adam Halasz Avatar asked Dec 29 '22 01:12

Adam Halasz


1 Answers

I would suggest catching the event on the iframe's Document, and in Firefox at least you need to do this using addEventListener() rather than onkeyup. The following will work in all major browsers:

var iframe = document.getElementById("myFrame");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

function handleIframeKeyUp(evt) {
    alert("Key up!");
}

if (typeof iframeDoc.addEventListener != "undefined") {
    iframeDoc.addEventListener("keyup", handleIframeKeyUp, false);
} else if (typeof iframeDoc.attachEvent != "undefined") {
    iframeDoc.attachEvent("onkeyup", handleIframeKeyUp);
}
like image 113
Tim Down Avatar answered Jan 06 '23 03:01

Tim Down