Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load javascript from parent into child context

I have one HTML page with parent.js in it. Within that html, one iFrame will be created on runtime. This iframe needs the parent.js in its context. If I am having one

function save() { ... }

in the parent.js, I can call that from iframe.js, like

parent.save();

But i need to call that in the iframe context, like

save();

So I have loaded the parent.js again in the iframe html. This makes parent.js to be loaded everytime I create a new iframe.

Is there anyway I could reuse the parent.js which is already loaded, into each iframe created?, like

loadParentJS("parent.js");

within iframe.js. This shouldn't give another request to application server.

like image 213
Stalin Gino Avatar asked May 03 '26 06:05

Stalin Gino


2 Answers

Encapsulate your code in parent.js in a closure:

var loadParentJS = function(window) {
    window.save = function() {
      // code
    };

    window.other = function() {
      // code
    };

  // rest of your code...

};

loadParentJS(window);

Then in your iframe, run this:

parent.loadParentJS(window);
like image 189
jalbee Avatar answered May 05 '26 00:05

jalbee


In your parent.js file, preceed each function and variable with this. and then you should be able to take advantage of Javascript Closures.

Replace: function save() { ... } With: this.save = function() { ... }

Replace: var aVariable = "value"; With: this.aVariable = "value";

Then in your iframe you need to set the scope of this to parent:

this = parent;

All of your calls to functions or variables in parent.js (in the global javascript or in the iframe javascript) will look like this:

this.save();
alert(this.aVariable);
like image 31
BumbleB2na Avatar answered May 04 '26 23:05

BumbleB2na



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!