Search code examples
javascriptiframe

How to pass data from ifram to parent


i am creating a vue js application that is hosted in my subdomain

and i want load a form from my main site using iframe.simple i want to load a form from my primary domain to my subdomain through i frame.And is working perfectly

<iframe ref="formFrame" @load="afterLoad()" :src="url"></iframe> 

And now i have a function in my vue js app like

displaySuccess(data){
            console.log("data from server: "+data);
        }

And this function should be triggered from my form. so i addedd a code like below in the form

window.parent.displaySuccess(text);

But it is not triggering.How can i call parent methods from iframe form.Thanks in advance


Solution

  • You can use the window.postMessage() method safely (enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it like in your example).

    This is a basic example for a duplex communication between a parent and an Iframe.

    Parent -> IFrame

       iframe.contentWindow.postMessage('hello world', '*'); // from parent
    
    window.onmessage = function(e) { // inside the iframe
        if (e.data == 'hello world') {
            alert('It works!');
        }
    };
    

    IFrame -> Parent

    window.onmessage = function(e) { // inside the parent
        if (e.data == 'hello world') {
            alert('It works!');
        }
    };
    
    window.top.postMessage('hello world', '*') //inside the iframe
    

    Window.postMessage - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage