将事件监听器添加到 iFrame

addEventListener to iFrame

我正在尝试将事件侦听器添加到 iframe 对象内的 mouseup:

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

这行不通。有什么想法吗?

尝试在 chrome 上运行,刚刚测试

据我所知,iframe 必须来自同一域。

<!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>
$($("#iframeid").contents()[0], window).find('body').bind("mouseup", function(e) {
    alert("works");
});

试试这个。在 jsfiddle 中工作。享受。

这会起作用:

 $('#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'); 
     });
 });

如果您只想使用普通的 Javascript 方式,您可以使用以下方法:

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

function Handler() {
    alert('works');
}

iframe.contentWindow

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

注意跨源策略

仅当帧具有相同来源时才允许事件冒泡。 除非你会得到下一个错误 (Chrome):

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