Get element from iframe and click it

10,412

Solution 1

Is this what you are trying with

document.getElementById('iframeResult').contentWindow.document.getElementById('buttonId').click()

where iframeResult is Id of iframe and buttonId is Id of element to be clicked ??

Solution 2

Do you mean you are trying to "click it" programmaticly, like via JavaScript? Or a user interaction like with your mouse and cant?

If you are trying via JavaScript its not going to work. Look up something called "same origin security". JavaScript cannot access other pages load via an iframe for security purposes. http://javascript.info/tutorial/same-origin-security-policy

Solution 3

Have you tried document.getElementById('elementid').click();?

Share:
10,412
Donny van V
Author by

Donny van V

Updated on June 15, 2022

Comments

  • Donny van V
    Donny van V about 2 years

    I wanne get an element from an iFrame and click it. Getting the element succeeded. Unfortunately i cant get the element within the iframe clicked. Anyone with a solution?

    Thanks!

    <script>
    $(document).ready(function(){
    var frame = $('#f314dbebb8'); //ID from the frame
    console.log(frame);
    });
    </script>
    
  • Donny van V
    Donny van V over 10 years
    I know how to use the click function, i gave it a try with a small script and it worked. Now i started to click something in the iframe and that doesnt work.
  • Cyph
    Cyph over 10 years
    Yep, saw your sample code. Not do-able. It violates same origin policy, unless you happen to be running the iframe from the same domain.
  • Donny van V
    Donny van V over 10 years
    Is it possible to get all elements from the iframe, and transform it to clickable?
  • Donny van V
    Donny van V over 10 years
    Tried to make a var from it, and logged it to the console and returned zero
  • Donny van V
    Donny van V over 10 years
    Yeah it is what i try... The only point is that the buttonId doesnt contain an ID but a class
  • Cyph
    Cyph over 10 years
    it is not allowed to read from another origin. you wont be able to read anything from the iframe using JS running on your domain.
  • Piyush Ashtt
    Piyush Ashtt over 10 years
    document.getElementById('google_ads_iframe_/16833175/MainLea‌​derboard_0').content‌​Window.document.getE‌​lementsByClassName('‌​rhbutton')[0].click(‌​) this works good for me
  • Donny van V
    Donny van V over 10 years
    Retrieving an error: Uncaught TypeError: Cannot read property 'contentWindow' of null
  • Boris Verkhovskiy
    Boris Verkhovskiy almost 4 years
    You can't do this with modern browsers unless the iframe is on the same host as the page it's on, which means you have to serve your directory locally, if you're just looking at html files on your disk, see stackoverflow.com/questions/29983786/…