首页 > 解决方案 > 如何通过悬停 iframe 动态获取 iframe 内的元素

问题描述

我需要通过将鼠标悬停在元素上来获取 iframe 内的元素,例如,如果 iframe 内的按钮可用,则意味着我需要获取按钮元素。

我使用查询选择器 (:hover) 来获取悬停的元素,但我只能从顶部文档中获取 iframe 的元素。我无法获取 iframe 中的元素。

有没有人遇到过这个?

标签: iframe

解决方案


它受到CORS的限制(因此通常您无法通过这种方式观察 3rd 方站点中包含的小部件),但在最近的浏览器中也是可行的,您只contentWindow需要iframe使用elementFromPoint().

示例frame.html

<div>Test1</div>
<div>Test2</div>
<div>Test3</div>
<div>Test4</div>
<div>Test5</div>

并包含test.html

<!DOCTYPE html>
<html>
  <head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <script>
      function startup(){
        frame.contentWindow.document.addEventListener("click",function(event){
          frame.contentWindow.document
            .elementFromPoint(event.clientX,event.clientY).innerHTML+="!";
        });
      }
    </script>
  </head>
  <body onload="startup()">
    <iframe id="frame" width="300" height="200" src="frame.html"></iframe>
  </body>
</html>

单击 的元素,iframe其内容将附加感叹号。


推荐阅读