0

I would like to load an ifram and then click on a button inside this iframe (the button is the on with a little umbrella on the left just above the forecats for the next 14 days)

So far this is what I was able to do, but it's not working:

<style>
  #my-div {
    width: 80%;
    height: 1500px;
    overflow: hidden;
    position: relative;
  }

  #my-iframe {
    position: absolute;
    top: -480px;
    left: -100px;
    width: 1280px;
    height: 1400px;
  }
</style>

<div id="my-div">
  <iframe src="http://www.meteofrance.com/previsions-meteo-france/paris-01e-arrondissement/75001" id="my-iframe"
    scrolling="no"></iframe>
</div>


<script>
  var iframe = document.getElementById("my-iframe");

  iframe.addEventListener("load", function () {
    console.log(iframe)
    var elmnt = iframe.contentWindow.document.getElementById("mf-accordion-bandeau-btn-unfold");
    console.log(elmnt)
    elmnt.click();
  });
</script>
MagTun
  • 5,619
  • 5
  • 63
  • 104
  • `elmnt.click;` is not clicking the element. You are not executing it. – epascarello May 17 '19 at 19:46
  • `elmnt.click;` should be `elmnt.click();` otherwise you're just returning the click method and not executing it: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click – Teh SoTo May 17 '19 at 19:46
  • sorry for the typo! But it still not working... – MagTun May 17 '19 at 19:49
  • Only way you will be able to click on an item in the iframe is if it is in the same domain. – epascarello May 17 '19 at 19:49
  • @epascarello, I am not sure what you mean, but my file is a local file, so does it mean, that I have no solution to send a click on this button ? – MagTun May 17 '19 at 19:55
  • Same origin policy will block it. Look at your console in your browser. I am sure there is an error message stating it. – epascarello May 17 '19 at 19:56
  • If you are trying to automate something, you might be better off with a tool like Selenium. – epascarello May 17 '19 at 20:05
  • Possible duplicate of [Attach an event in a child iframe to a handler in the parent window](https://stackoverflow.com/questions/3672726/attach-an-event-in-a-child-iframe-to-a-handler-in-the-parent-window) – Void Spirit May 17 '19 at 20:05

1 Answers1

1

Accessing the contents of an iframe with JavaScript is only possible in certain cases. The origin and protocol must be the same and also there can't be any headers on the child preventing the main page to access it.

This is pure for security reasons, as otherwise, websites would just be able to load 3rd party sites and steal personal data or act as the user.

dejakob
  • 2,062
  • 14
  • 21