user198989
user198989

Reputation: 4665

Run javascript function which is inside iframe?

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 ?

Upvotes: 1

Views: 127

Answers (2)

Gary Storey
Gary Storey

Reputation: 1814

Per comments above:

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

Upvotes: 1

Matt DeKok
Matt DeKok

Reputation: 196

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();
});

Upvotes: 2

Related Questions