I couldn't find how to do this after digging through S\O. Im using javascript to create an iframe and then i'm loading jQuery into the Iframe. Now I just want to call methods such as $ajax in the Iframe context. Below is how i did it.
var iframe = document.createElement('iframe');
iframe.name = "loginFrame";
iframe.id = "loginFrame";
document.body.appendChild(iframe);
var idocument = iframe.contentWindow.document;
var jq = idocument.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
idocument.getElementsByTagName('body')[0].appendChild(jq);
jq.onload = function () {
}
This works and idocument
will in fact have the jQuery script in its body. Now using the Iframe, how would I make calls using jQuery?
idocument.$.ajax(url, settings)
Does not work and returns
Uncaught TypeError: Cannot read property 'ajax' of undefined
error. Any help is much appreciated?
EDIT: For the following method to work properly the iframe src cannot point to a different domain, and must be set, for example
iframe.src = "about:blank"
The jquery "$" is an attribute of the window object of the iframe.
So you can access jquery using
iframe.contentWindow.window.$
If you wanted to make an ajax call you would do:
iframe.contentWindow.window.$.ajax(url, settings)
Also if you want to use Jquery the normal way you can do
$ = iframe.contentWindow.window.jQuery
Note: This should be in jq.onload and this will conflict with jQuery if it is on the main page so you could instead do:
iframe.$ = iframe.contentWindow.window.jQuery
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With