使用 iframe 的内容在页面上执行 jquery .click()

perform jquery .click() on page using iframe's content

本文关键字:执行 jquery click iframe 使用      更新时间:2023-09-26

如果可能,我可以单击iframe中的元素并让它在呈现它的页面上执行功能吗?

例如:

<div class="page">
    <iframe class="frame">[... the source will render: <div class="clickme"></div>...] 
    </iframe>

。同时,回到主页...

    <script>
          $(".clickme").click(function(){
                 alert('clicked');
           });
    </script>
</div>

编辑也,我忘了提到 iframe 的 src 在页面加载后会发生变化,这可能是一个障碍!

它似乎对我不起作用,我在这里找不到合适的答案/问题。谢谢!

如果用户单击 iframe 中的项目会导致在父级中触发函数,则假设父级中有一个名为 doStuff 的函数,则以下内容将起作用:

window.top.doStuff();

当然,这需要 iframe 的域与父页面的域匹配。

如果需要跨域怎么办?

如果您需要跨域通信,那么HTML5 postMessage函数将使您能够将父页面注册为iframe的侦听器,从而允许iframe将消息传递到父页面。

在父 HTML 中,注册侦听器:

// register to listen for postMessage events
window.addEventListener("message", receiveMessage, false);  
// this is the callback handler to process the event
function receiveMessage(event)  
{  
  // you're responsible for your own security. Make sure requests are 
    // coming from domains you whitelist!
  if (event.origin !== "http://example.org:8080")  
    return;  
  if(event.data == "click!") {
      // do your stuff on the parent page here
  }
}  

在 iframe HTML 页面中:

// pass the string "click!" to the parent page, where the receiveMessage
 // handler will take action when it sees the message matches.
top.window.postMessage("click!", targetOrigin);

有关更多详细信息,请参阅window.postMessage。

您可以使用 content(( 访问 iframe 中的元素

$('.frame').contents().find('.clickme').each(function(){
   $(this).click(function(){ //this is .clickme
     //enter code here
   })
});

注意 如果 iframe 的 SRC 来自不同的域,您将被拒绝访问。

你可以在Iframe中调用一个函数,

window.frames['iframeName'].yourFunction();

并在 Iframe 中

    <script>
              $(".clickme").click(function(){
                      yourFunction();
               });
             function yourFunction(){
              alert('clicked');
             }
   </script>