9

I want to click a button which is on webpage opened in iframe based on class selector from my parent page.

I tried this:

$.each($('.classname'), function(i, el){
  setTimeout(function(){
  $(el).trigger('click');
  },30000 + ( i * 30000 ));
});

but no success. How can i achieve this?

kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25

5 Answers5

5

If the src of the iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of the iframe in javascript.

Billy Fischbach
  • 191
  • 1
  • 9
4

If the source of the iframe is in a different domain (even subdomain) than the parent page, you will not be able to change the parent content from the embedded iframe. Web browsers block this functionality by default.

Niche
  • 967
  • 5
  • 23
1

Assuming the page you've opened in the iframe is from your own domain, you want the contentDocument to access elements in the iframe. As stated everywhere though, if you try to load an external page not on your domain, your browser will not allow this due to security issue.

How to get the body's content of an iframe in Javascript?

The second answer here: jQuery/JavaScript: accessing contents of an iframe

https://www.w3schools.com/jsref/prop_frame_contentdocument.asp

PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10
1

That is not going to be possible in the way that you want for this reason Same-origin policy. That basically means that you can not edit the data in the iframe except if that page has the same port and domain, you can not get the data for security purposes (The browser is not going to allow you to do that).....

I need more information to help you to find different solution to your problem... :)

Ricardo
  • 1,308
  • 1
  • 10
  • 21
0

As everybody is suggesting, browsers won't allow you to do that due to security reasons.But there is way out using browser's window.

from your page:

window.postMessage({action: 'clickOnIframeButton',selector:$el},'*');  

in your iframe:

   window.addEventListener('clickOnIframeButton',
         function clickButton(e,data){
               $(data.selector).click();
           });

so you can do something like,

$.each($('.classname'), function(i, el){
  setTimeout(function(){
    window.postMessage({action: 'clickOnIframeButton',selector:$el}'*');
  },30000 + ( i * 30000 ));
});
Prakash Palnati
  • 3,231
  • 22
  • 35