How to initiate a JavaScript function in an iframe

2019-08-13 19:34发布

问题:

I have a function in a parent file that depends on several global variables. I am having the child iframe update one of the parent's global variables with

parent.myvar = "myvalue";

Works great (note: everything is on the same domain). Now I need to run the function in the parent to complete the process. Problem:

parent.myfunction();

I have just run the function I need minus any of the global variables in the parent file (it is being executed within the child iframe). Of course, I could bring over all the global variables from the parent file by just redeclaring all my global variables (I could even have the parent function do all the redeclairing). However, I was hoping for a more elegant solution. Is there any way to get a child to initiate a function to be run within the parent environment?

回答1:

I'm not sure if I understand the question, but couldn't you pass in a variable reference of parent to the child?

Like

var parentRef = this;

so the child could run

parentRef.myFunction();