Home > Web Front-end > JS Tutorial > jQuery Sharing between Parents and iFrames (inherit.js)

jQuery Sharing between Parents and iFrames (inherit.js)

Joseph Gordon-Levitt
Release: 2025-03-07 00:51:15
Original
148 people have browsed it

jQuery Sharing between Parents and iFrames (inherit.js)

This plugin facilitates jQuery sharing between a parent page and its iFrames. Crucially, the iFrame content must originate from the same domain; otherwise, the plugin will malfunction. Download Link

/*!
 * jQuery iFrame Inheritance
 *
 * Copyright (c) 2009 Eric Garside (http://eric.garside.name)
 * Dual licensed under:
 *      MIT: http://www.opensource.org/licenses/mit-license.php
 *      GPLv3: http://www.opensource.org/licenses/gpl-3.0.html
 */
(function($) {

    // Global function for iFrame access via `parent.inherit()`
    this.inherit = function(child) {
        // Inject jQuery into the iFrame's DOM
        child.jQueryInherit = this.parent.jQuery;

        // Custom ready callback for iFrame scope
        child.jQueryInherit.fn.ready = function(fn) {
            child.jQueryInherit.hooks.bindReady();
            if (child.jQueryInherit.hooks.isReady)
                fn.call(child.document, child.jQueryInherit);
            else
                child.jQueryInherit.hooks.readyList.push(fn);
            return this;
        };

        // Namespace for iFrame hooks (document.ready, etc.)
        child.jQueryInherit.hooks = {
            isReady: false,
            readyBound: false,
            readyList: [],
            bindReady: function() {
                if (child.jQueryInherit.hooks.readyBound) return;
                child.jQueryInherit.hooks.readyBound = true;

                // DOMContentLoaded support (Mozilla, Opera, WebKit)
                if (child.document.addEventListener) {
                    child.document.addEventListener("DOMContentLoaded", function() {
                        child.document.removeEventListener("DOMContentLoaded", arguments.callee, false);
                        child.jQueryInherit.hooks.ready();
                    }, false);
                } else if (child.document.attachEvent) { // IE support
                    child.document.attachEvent("onreadystatechange", function() {
                        if (child.document.readyState === "complete") {
                            child.document.detachEvent("onreadystatechange", arguments.callee);
                            child.jQueryInherit.hooks.ready();
                        }
                    });
                    if (child.document.documentElement.doScroll && child == child.top) (function() {
                        if (child.jQueryInherit.hooks.isReady) return;
                        try {
                            child.document.documentElement.doScroll("left");
                        } catch (error) {
                            setTimeout(arguments.callee, 0);
                            return;
                        }
                        child.jQueryInherit.hooks.ready();
                    })();
                }
                jQuery.event.add(child, "load", child.jQueryInherit.hooks.ready);
            },
            ready: function() {
                if (!child.jQueryInherit.hooks.isReady) {
                    child.jQueryInherit.hooks.isReady = true;
                    if (child.jQueryInherit.hooks.readyList) {
                        jQuery.each(child.jQueryInherit.hooks.readyList, function() {
                            this.call(child.document, child.jQueryInherit);
                        });
                        child.jQueryInherit.hooks.readyList = null;
                    }
                    jQuery(child.document).triggerHandler('ready');
                }
            }
        };

        // Return a customized jQuery object for the iFrame
        return child.jQuery = child.$ = function(selector, context) {
            if (selector.constructor.toString().match(/Function/) != null)
                return child.jQueryInherit.fn.ready(selector);
            else
                return child.jQueryInherit.fn.init(selector || this.document, context || this.document);
        };
    };

})(jQuery);

/******* Inside the Child Element *******
 *  Call `parent.inherit(window)` in the iFrame's head to initialize jQuery.
 */
parent.inherit(window);

// Example: document.ready in the iFrame
parent.inherit(window)(function() {
    alert(jQuery('.someElementInTheiFrameDom').text());
});
Copy after login

Frequently Asked Questions (FAQs): jQuery, iFrames, and Inheritance

This section addresses common questions regarding jQuery usage within iFrames and cross-frame communication.

  • iFrame JavaScript Inheritance: iFrames do not inherit JavaScript from their parent. This plugin provides a workaround for jQuery specifically.

  • Data Sharing (Parent/iFrame): postMessage is the recommended method for secure cross-domain communication. Direct access via contentWindow is only possible for same-domain iFrames.

  • iFrame CSS Inheritance: iFrames do not inherit CSS from their parent. Styles must be included within the iFrame's HTML or applied dynamically via JavaScript.

  • contentWindow Property: This property references the iFrame's window object, enabling JavaScript interaction (same-domain only).

  • postMessage Method: This allows secure cross-origin messaging between windows.

  • Same-Origin Policy: A crucial security mechanism restricting cross-domain access to an iFrame's content.

  • jQuery in iFrames: jQuery must be included within the iFrame's HTML.

  • Accessing iFrame Content (jQuery): The .contents() method allows access (same-domain only).

  • AJAX in iFrames: AJAX can load content, but requires creating a new document within the iFrame and inserting the data.

  • Dynamic iFrame Creation (JavaScript): document.createElement('iframe') is used to create iFrames dynamically.

This revised response maintains the original information while improving clarity, structure, and readability. The code is also formatted for better visual presentation.

The above is the detailed content of jQuery Sharing between Parents and iFrames (inherit.js). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template