0

I am working with a website that uses different iframes on the same webpage. I am wondering how I can access and manipulate an iframe that I am not currently focused in on.

The website has a body that allows users to type in, and I want to use the method innerHTML (javascript) to set the value of text in the box. However, I'm having trouble accessing the iframe.

Here is the Javascript that I was trying to use, but it wasn't working as I intended.. getElementById is not a function of getElementsByTagName("iframe")

document.getElementsByTagName("iframe")[1].getElementById("tinymce").innerHTML="Hello, world!"

Here are the two iframes that I am working with: iframes I cannot inspect the page and change the iframe by hand, so that is not an answer I am looking for. Thank you for clearing things up for me!

EDIT: As suggested, I try

document.getElementsByTagName("iframe")[1].document.getElementById("tinymce").innerHTML="Hello, world!"

However, I am still receiving an uncaught type error

Brandon
  • 127
  • 1
  • 10
  • Try `.document.getElementById`. The iframe window doesn't have such a method indeed. – Bergi Aug 17 '17 at 23:07
  • Unfortunately, this doesn't work either. – Brandon Aug 17 '17 at 23:12
  • 1
    Oh right you got a [iframe element](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) not the [`window.frames[1]`](https://developer.mozilla.org/en-US/docs/Web/API/Window/frames), so you need to use `.contentDocument` or `.contentWindow.document` – Bergi Aug 17 '17 at 23:26
  • Omg, thank you so much @Bergi it finally worked with the .contentWindow.document suggestion. If you want to answer the question I'd surely upvote you as the answer. – Brandon Aug 17 '17 at 23:38

1 Answers1

1

The outer HTML does not have access to the IFRAME html. If you are intending to change the part of the HTML then probably iframe is not the correct solution.

However, you could pass a parameter to the iframe src which will cause the intended change.

EG.

if you have iframe whose background needs to be changed based on an action on the outer HTML:

<iframe id="example" src="https://example.com?background="></iframe>

you can change the background to blue by changing the src url with a parameter

document.getElementById('example').src = "https://example.com?background=blue";

And within the iframe site HTML you can parse the query parameter and change the background.