Coffee Bite
Coffee Bite

Reputation: 5164

How can I inject a Jquery object from a parent iframe to an embedded iframe?

I am embedding an iframe in a webpage and I want to inject jquery in this frame.

I tried something like:

frame.contentWindow.$ = window.$

While this works, the iframe's $ is still running in the parent's scope as opposed to its own independent copy.

Is there a way to inject an independent jquery object into the iframe without injecting a <script src="/path/to/jquery.js"></script> in the frame?

UPDATE

Solved it. The jquery.js conveniently defines jQuery for a scope by accepting the window object in an anonymous function:

function(windowObject){ .... define jquery }(window)

So all I had to do was to name this function, E.g. jQuerify and call it once for the parent window object and then for the child window object.

jQuerify = function(windowObject){ .... define jquery }
jQuerify(window)
jQuerify(iframe.contentWindow)

Upvotes: 2

Views: 1245

Answers (2)

Coffee Bite
Coffee Bite

Reputation: 5164

Solved it. The jquery.js conveniently defines jQuery for a scope by accepting the window object in an anonymous function:

function(windowObject){ .... define jquery }(window) So all I had to do was to name this function, E.g. jQuerify and call it once for the parent window object and then for the child window object.

jQuerify = function(windowObject){ .... define jquery }
jQuerify(window)
jQuerify(iframe.contentWindow)

Upvotes: 1

Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39057

You can try cloning the jQuery object:

See this answer or this one on how to implement a .clone function, then call this:

iframe.contentWindow.$ = window.$.clone();

or

iframe.contentWindow.$ = window.$.bind({});

... depending on how you choose to clone the function.

Upvotes: 0

Related Questions