Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jquery from parent inside an iframe?

I have a file, let us call it parent-win.html, served by domain example.com. This file has jquery included in it. An iframe, lets call it iframe-win.html, is embedded in this page. iframe-win.html has a form element with id form-elem and value Hello World!. Now I do following inside iframe.

var jQuery = parent.jQuery;
console.log(jQuery('#form-elem').val());

According to my limited knowledge of JS I should see Hello World! on console but instead I see undefined. Now, my question is do I need to load jquery again in an iframe or can I utilise jquery object already loaded in parent window?

Do note that this is not as usual access iframe/parent content from parent/iframe.

like image 663
Kumar Avatar asked Jun 08 '12 13:06

Kumar


People also ask

Can you use jQuery in an iFrame?

You can use jQuery to add jQuery effects to your iFrame elements, to change the CSS rules, or even to add content. Above, the script is used to change the background color of the . page element within the frame to white.

How to access iFrame parent page using jQuery?

To find in the parent of the iFrame use: $('#parentPrice', window. parent. document).

How do I access elements in an iFrame?

Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.


1 Answers

try this in the iframe:

if (typeof(jQuery) == "undefined") {
    var iframeBody = document.getElementsByTagName("body")[0];
    var jQuery = function (selector) { return parent.jQuery(selector, iframeBody); };
    var $ = jQuery;
}
like image 104
Moin Zaman Avatar answered Sep 20 '22 13:09

Moin Zaman