1

I'm trying to run a javascript function, which is located inside the iframe.

<script>
document.getElementById('myFrame').contentWindow.setupCookie()
</script>

<iframe id="myFrame" src="iframe.html"></iframe>

iframe.html

<script>
function setupCookie() {
    document.cookie = "guvenli=1";
}
</script>

<center style="margin-top:200px;">
            <a href="javascript:;" 
    onClick="setupCookie(); location.href='/index.php'">Enter Site >></a></center>

What is the correct way to do that ?

user198989
  • 4,574
  • 19
  • 66
  • 95
  • 3
    Does what you have work? You might need to wait until the iframe is *loaded* before you can call `setupCookie()`. – gen_Eric Oct 14 '14 at 19:44
  • 2
    This is a correct way. + http://stackoverflow.com/questions/1600488/calling-javascript-function-in-iframe The problem might be because you are trying to access it when iframe does not exist (it is below the line addressing it) or content not loaded. – Cheery Oct 14 '14 at 19:44

2 Answers2

2

Your method is correct, but your iframe needs to load before you can reference it with Javascript.

You should wait for the DOM content to load

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('myFrame').contentWindow.setupCookie();
});
Matt DeKok
  • 197
  • 1
  • 8
  • Why this listener is attached to `document` of the current window and not to the `iframe`? – Cheery Oct 14 '14 at 20:03
  • Because the iframe is part of the document and doesn't exist until the document has loaded. – Macil Oct 14 '14 at 20:08
1

Per comments above:

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById('myFrame').contentWindow.setupCookie();
});
Gary Storey
  • 1,779
  • 2
  • 14
  • 19