简体   繁体   中英

How do I inject a function declared in the parent page into an iframe, then call it?

I can inject an iframe like this:

iframe.contentWindow.action...

However, what if I want to send a function to be declared within the iframe, and then call it?

eg

function hello(){...}
iframe.contentWindow...

and basically both declare and call hello from within the iframe?

Just to clarify, hello 's actions should be done inside the iframe. For example, if I put document.getElementById("input").value="foo"; inside hello and then call it inside the iframe, the changes should take effect inside input from inside the iframe and not in the parent window.

Insert a script tag into the <head> section of the frame with your code in it. The script tag can be either an external script reference or an inline script. You will have to be same origin in order to do the injection.

var idoc = iframe.contentWindow.document;
var script = idoc.createElement("script");
script.textContent = 'document.getElementById("input").value="foo";'
idoc.getElementsByTagName("head")[0].appendChild(script);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM