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 ?

2
  • 3
    Does what you have work? You might need to wait until the iframe is loaded before you can call setupCookie(). Commented Oct 14, 2014 at 19:44
  • 2
    This is a correct way. + stackoverflow.com/questions/1600488/… 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. Commented Oct 14, 2014 at 19:44

2 Answers 2

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(); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

Why this listener is attached to document of the current window and not to the iframe?
Because the iframe is part of the document and doesn't exist until the document has loaded.
1

Per comments above:

document.addEventListener("DOMContentLoaded", function(event) { document.getElementById('myFrame').contentWindow.setupCookie(); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.