获取 iframe 内点击标签的父级

Get parent of clicked tag inside of iframe

本文关键字:标签 iframe 获取      更新时间:2023-09-26

我有一个包含HTML页面的iframe。现在我想获取单击的父项的类。
这是我的 ifram:

<iframe src="//example.com" id="frame" ></iframe>  

这是 CSS:

#frame{  width:380px;  height:420px;}  

这是我的脚本:

$(document).ready(function() {
  var iframe = document.getElementById('frame');
  var innerDoc = iframe.contentDocument || iframe.contentWindow.document.body;
  $(innerDoc).on('click', function(e) {
    var thisID = ((e.target).id);
    alert(thisID);
    alert(innerDoc.getElementById(thisID));

    $(thisID).click(function() {
      var Allclassnames = $(thisID).parent();
      console.log(Allclassnames);
    });
  });
});

但它返回的项目仅被单击。如何修复?

演示

:演示

NOTE :这些在同一个域中。也许下面DEMO由于这个原因不起作用。但我确信我的 HTML 与我的网站位于同一域内。谢谢。

将沙盒属性添加到 iframe

<iframe src="/example.html" id="frame" sandbox="allow-scripts allow-same-origin"></iframe> 

将脚本更改为

<script>
$('#frame').load(function() {
  $('#frame').contents().on('click', function(e) {  
    var thisID = ((e.target).id);
    alert(thisID); 
    alert($('#'+thisID,this));
      $('#'+thisID,this).click(function() {
        var Allclassnames = $(this).parent();
        console.log(Allclassnames); 
      });
  });
});
</script>

确保帧文档中的每个元素都有一些 id,否则 alert(( 可能会抛出错误。

要查看 iframe 的控制台消息,您需要从范围下拉列表中更改范围,它位于控制台选项卡中,除了 chrome 开发人员工具中的过滤器图标外。

除非iframe与父文档位于同一域中,否则无法与该内容进行交互。

看:
https://en.wikipedia.org/wiki/Same-origin_policy