addEventListener to iFrame
45,041
Solution 1
This will work:
$('#myIFrame').load(function(){
//then set up some access points
var contents = $(this).contents(); // contents of the iframe
$(contents).find("body").on('mouseup', function(event) {
alert('test');
});
});
Solution 2
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');
}
Solution 3
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
Solution 4
Try this working on chrome, just tested
As per my knowledge, Iframe must be from same domain.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function () {
var $frame = $("#myIFrame");
$frame.contents().bind("mouseup", function (e) {
alert('inside');
});
});
</script>
</head>
<body>
<iframe id="myIFrame" src="/WebForm4.aspx" style="position:absolute; width:500px; height:500px;left:0px; top:50px"></iframe>
</body>
</html>
Solution 5
$($("#iframeid").contents()[0], window).find('body').bind("mouseup", function(e) {
alert("works");
});
Try this. Works in jsfiddle. Enjoy.
Author by
Darko Martic
Updated on July 24, 2021Comments
-
Darko Martic almost 3 years
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?
-
Maddy almost 9 yearsit wont work on jsfiddle, because it mark that script as CDATA. Try this on your local machine.
-
Shayan over 4 yearsSometimes
contentDocument
does not exist, so trycontentWindow
in stead of it. Example: w3schools.com/jsref/… -
cazort over 4 yearsYes, in Chrome 79, this code worked for me only when changing it to
iframe.contentWindow.document.addEventListener('mouseup', Handler);
-
user1298923 about 2 yearsThanks 👌 Your approach works perfectly, but I add to use 'contentDocument' instead of 'contentWindow'. iframe.contentDocument.body.addEventListener('click', () => console.log('click'));
-
Mohamed Ali almost 2 yearsThen how we can approach for cross domain origin.