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

2019-05-26 02:01发布

If possible, can I click on an element in an iframe and have that perform a function on the page it is rendered on?

for example:

<div class="page">

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

...meanwhile, back on the main page...

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

edit also, I forgot to mention that the iframe's src changes after the page loads, this could be an obstacle!

It doesn't seem to work for me and I couldn't find an appropriate answer/question here. Thanks!

3条回答
2楼-- · 2019-05-26 02:31

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.

查看更多
Root(大扎)
3楼-- · 2019-05-26 02:39

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>
查看更多
别忘想泡老子
4楼-- · 2019-05-26 02:44

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.

查看更多
登录 后发表回答