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

不想你离开。 提交于 2019-12-08 02:36:15

问题


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!


回答1:


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.




回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/10670624/perform-jquery-click-on-page-using-iframes-content

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