Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener to iFrame

I'm tryin to add event listener to mouseup inside iframe object:

$("#myIFrame").contents().find("body").bind("mouseup", function() {
    //e.preventDefault(); //doesn't make difference
    alert('inside');
});

This doesn't work. Any ideas?

like image 714
Darko Martic Avatar asked May 22 '15 13:05

Darko Martic


2 Answers

iframe.contentWindow

const iframe = document.getElementById('iframeId');
iframe.contentWindow.body.addEventListener('click',() => console.log('click));

Mind the cross-origin policy

Event bubbling will be allowed only if frames have the same origin. Unless you will get next error (Chrome):

Blocked a frame with origin "http://example.com" from accessing a cross-origin frame

like image 116
Andrii Verbytskyi Avatar answered Oct 02 '22 02:10

Andrii Verbytskyi


If you just want a plain vanilla Javascript way, you can use the following:

var iframe = document.getElementById('myIFrame');
iframe.contentDocument.body.addEventListener('mouseup', Handler);

function Handler() {
    alert('works');
}
like image 32
Vince Pike Avatar answered Oct 02 '22 03:10

Vince Pike