0

I am trying to run some javascript inside an iframe after it loads and am having trouble. I'm not sure if it means my concept of what is happening is wrong or if my code is just wrong.

What I want to do is load a javascript file in the iframe environment and then call a function. (the iframe contents are static web pages captured with singlefile and served from my server. I want to be able to pop up menus for the images in the iframe page). Is this possible, or is it blocked for security considerations? I can get the contentDocument from the iframe and see what is in it but not make any changes to it. Adding a load event listener to the iframe runs in the top-level DOM, not the iframe.

An ugly workaround would be to add a line loading the script to each of my served html files, but I'm reluctant to do that since it seems kind of fragile. Is that my only option?

russell
  • 660
  • 1
  • 10
  • 18

1 Answers1

0

you can select the iframe element and access its internal window object. to do this first assign an id to your iframe element

<iframe id="chosen-iframe" ...></iframe>

and to access the window use the following

const iframe = document.getElementById('chosen-iframe');
const iFrameWindowElement = iframe.contentWindow;

and with access to the window, you can create a script tag that contains the script you want to inject inside the iframe

  var injectedScript = iFrameWindowElement.document.createElement("script");
  injectedScript.append(...);
  iFrameWindowElement.document.documentElement.appendChild(script);
Omid
  • 438
  • 4
  • 11
  • Thank you, I was very close to this process but didn't quite have it. With your reassurance I got it working. I think this needs to be done in a load event listener on the iframe so the iframe DOM is ready. It does seem being able to do this could be a security risk, doesn't it? – russell Oct 09 '21 at 02:01
  • @russell yes. if you're trying to attach event listeners to dom elements you'll need to use the `onload` event. as for the security risk, You can limit your webpage from being displayed in an iframe using HTML headers. and as for the iframe accessing the parent Window there is a sandbox parameter that limits this. – Omid Oct 09 '21 at 15:11