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

不想你离开。 提交于 2019-12-06 06:39:54

If the user clicking on an item in the iframe should result in a function firing in the parent, then the following will work, assuming you have a function called doStuff in the parent:

window.top.doStuff();

Of course, this requires the domain of the iframe to match the domain of the parent page.

What if it needs to be cross-domain?

If you require cross-domain communication, then the HTML5 postMessage function will empower you to register the parent page as a listener to the iframe, allowing the iframe to pass messages to the parent page.

In the parent HTML, register a listener:

// 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
  }
}  

In the iframe HTML page:

// 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);

See window.postMessage for more details.

You can access element in iframe using content()

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

note if iframe's src come from different domain you 'll get access denied.

you can call a function in the Iframe,

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

and in the Iframe

    <script>
              $(".clickme").click(function(){
                      yourFunction();
               });

             function yourFunction(){
              alert('clicked');
             }
   </script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!