0

How to invoke a function in iframe using JS or how to even target the iframe? I've tried using document.getElementByID("myIframe"), but it didn't seem to work. Below is a basic form of the HTML:

<html>
<head>
<script>
    function runFunction() {
        var win = document.getElementByID("myIframe");
    }
</script>
</head>
    <body onload="runFunction()">
        <iframe id="myIframe" name="myIframe" src="http://www.myothersite.com/"></iframe>
    </body>
</html>

My other site has a function named getEvents() that I would like to somehow invoke. Any help would be greatly appreciated.

5
  • So when you do console.log(win), you are getting nothing? Commented May 30, 2015 at 18:21
  • Is your other site in the same domain? Satpal's answer looks correct, but only if the iframe is in the same domain as the main page. If the sites are in two different domains you won't be able to call the function. Commented May 30, 2015 at 18:26
  • It is the same domain. Satpals answer didn't seem to invoke the function for me. Commented May 30, 2015 at 18:28
  • How do you know whether or not it is invoking the function if you're not getting any feedback, errors, etc.? Commented May 30, 2015 at 18:35
  • Because that function does an AJAX call to gather all events for the day and logs to a table the access date. Satpal's didn't insert a access date into the log table, but NightOwls did. Now I just need to try to access the results. Commented May 30, 2015 at 18:38

2 Answers 2

1

You should be able to access the iframe and invoke the function using the following:

// reference to window in iframe with id or name 'myIframe'
var win = window.frames['myIframe'];

// invoke function in win
win.getEvents();
Sign up to request clarification or add additional context in comments.

2 Comments

I think this invoked my function. Can I get the results it returns?
I accepted your answer because you did answer my question, but if you could help get the results that would be very helpful! TIA for any suggestions.
1

You can use the contentWindow property which can be used to access the window object that belongs to a iframe element.

The contentWindow property returns the Window object by an iFrame element (through the Window object, you can access the document object and then any one of the document's elements). This DOM attribute is read-only.

document.getElementById("myIframe").contentWindow.getEvents();

Comments