addEventListener to iFrame

后端 未结 4 1461
北海茫月
北海茫月 2020-12-18 03:33

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

$(\"#myIFrame\").contents().find(\"body\").bind(\"mouseup\", function() {
    //e.preventDe         


        
相关标签:
4条回答
  • 2020-12-18 04:15

    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>
    
    0 讨论(0)
  • 2020-12-18 04:21

    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');
    }
    
    0 讨论(0)
  • 2020-12-18 04:22
    $($("#iframeid").contents()[0], window).find('body').bind("mouseup", function(e) {
        alert("works");
    });
    

    Try this. Works in jsfiddle. Enjoy.

    0 讨论(0)
  • 2020-12-18 04:23

    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'); 
         });
     });
    
    0 讨论(0)
提交回复
热议问题