Calling a parent window function from an iframe

后端 未结 10 2377
悲&欢浪女
悲&欢浪女 2020-11-22 01:43

I want to call a parent window JavaScript function from an iframe.



&         


        
10条回答
  •  伪装坚强ぢ
    2020-11-22 02:13

    Window.postMessage()

    This method safely enables cross-origin communication.

    And if you have access to parent page code then any parent method can be called as well as any data can be passed directly from Iframe. Here is a small example:

    Parent page:

    if (window.addEventListener) {
        window.addEventListener("message", onMessage, false);        
    } 
    else if (window.attachEvent) {
        window.attachEvent("onmessage", onMessage, false);
    }
    
    function onMessage(event) {
        // Check sender origin to be trusted
        if (event.origin !== "http://example.com") return;
    
        var data = event.data;
    
        if (typeof(window[data.func]) == "function") {
            window[data.func].call(null, data.message);
        }
    }
    
    // Function to be called from iframe
    function parentFunc(message) {
        alert(message);
    }
    

    Iframe code:

    window.parent.postMessage({
        'func': 'parentFunc',
        'message': 'Message text from iframe.'
    }, "*");
    // Use target origin instead of *
    

    UPDATES:

    Security note:

    Always provide a specific targetOrigin, NOT *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site (comment by ZalemCitizen).

    References:

    • Cross-document messaging
    • Window.postMessage()
    • Can I Use

提交回复
热议问题