addEventListener to iFrame
Asked Answered
R

6

18

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?

Relationship answered 22/5, 2015 at 13:16 Comment(7)
Binding to events in iFrames can be problematic because doing so sometimes captures events that are intended for the content hosted by the IFRAME itself; how this gets handled varies among browsers.Druggist
What this gives to you? --> alert($("#myIFrame").contents().find("body").length)Footwall
And the iFrame is of course showing a page from the same domain, with the same port and protocol ?Simsar
@DhavalMarthak I get 1Relationship
@Simsar yes, same domain/port/protocolRelationship
@DarkoMartic Then it should work!Footwall
@DhavalMarthak well, it doesn't :) I don't get alert('inside');Relationship
D
11

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'); 
     });
 });
Dugout answered 22/5, 2015 at 14:24 Comment(0)
P
24

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');
}
Proportionable answered 3/5, 2018 at 15:11 Comment(4)
Sometimes contentDocument does not exist, so try contentWindow in stead of it. Example: w3schools.com/jsref/…Unvarnished
Yes, in Chrome 79, this code worked for me only when changing it to iframe.contentWindow.document.addEventListener('mouseup', Handler);Possum
Hey Vince, nice profile pic.Rumpf
for me contentDocument / contenWindow did not work, but this did:var iframe_1 = document.getElementById('1_html'); iframe_1.onload = Handler_1; function Handler_1() { alert('works 1'); }Fairspoken
D
11

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'); 
     });
 });
Dugout answered 22/5, 2015 at 14:24 Comment(0)
P
3

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>
Premolar answered 22/5, 2015 at 13:46 Comment(1)
it wont work on jsfiddle, because it mark that script as CDATA. Try this on your local machine.Premolar
R
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

Ryley answered 23/7, 2021 at 20:19 Comment(2)
Thanks 👌 Your approach works perfectly, but I add to use 'contentDocument' instead of 'contentWindow'. iframe.contentDocument.body.addEventListener('click', () => console.log('click'));Habitual
Then how we can approach for cross domain origin.Osanna
B
1
$($("#iframeid").contents()[0], window).find('body').bind("mouseup", function(e) {
    alert("works");
});

Try this. Works in jsfiddle. Enjoy.

Bernettabernette answered 22/5, 2015 at 14:11 Comment(0)
S
0

To give trigger event to your iframe there is an alternate way: Wrap ifrmae inside a div and give onClick event to the div. So that onClick of div you can give trigger event on click of iframe.

Schooling answered 7/9, 2022 at 11:39 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Nguyetni

© 2022 - 2024 — McMap. All rights reserved.