11

Within my webpage I have an iframe like so:

<iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>

(The iframe is of a page on the same site...)

My question is, is it possible to use javascript on the page that has the iframe to control the 'thispage.html' (like use javascript functions?)

2
  • thispage.html is the main html file or the file you are loading into iframe. Commented Oct 21, 2013 at 15:33
  • related question Commented Jun 5, 2014 at 18:49

2 Answers 2

18

Yes you can. Say your iframe's ID is 'myIFrame'

<iframe id="myIFrame" src="thispage.html"
    width="100%" height="600"
    frameBorder="2">
</iframe>

Then, add the following in your JavaScript:

// Get the iframe
const iFrame = document.getElementById('myIFrame');

// Let's say that you want to access a button with the ID `'myButton'`,
// you can access via the following code:
const buttonInIFrame = iFrame.contentWindow.document.getElementById('myButton');

// If you need to call a function in the iframe, you can call it as follows:
iFrame.contentWindow.yourFunction();

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

3

Yes, if you give your iframe an ID, for example

<iframe src="thispage.html" width="100" height="600" frameBorder="2" id="myIframe"></iframe>

You can access the inner window like this:

var iw = document.getElementById("myIframe").contentWindow;

So you can call its functions e.g.

iw.theFunctionInsideIframe();

And you can locate the DOM elements like

let anElement = iw.document.getElementById("myDiv");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.