Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window.Parent.Postmessage with Parameter

I'm working with an IFrame on my page and making a Communication with Cross Domain IFrame - A Cross Browser Solution using .postmessage in java script

in my IFRAME target page I have something like this:

window.parent.postMessage("Assign to value1", "www.parentpage.com");
window.parent.postMessage("Assign to value2", "www.parentpage.com");

then in my parent page :

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var value1 = e.data;
var value2 = e.data;

}, false);      

I tested it and Its working with single var using value1 only.

Now I want to parametarized my .postmessage if its possible so that I can get the message dynamically. I'm expecting a result of :

value1=Assign to value1
value2=Assign to value2     

Any suggestion on how can I achieve that result?

like image 271
LennuJ Kram Avatar asked Aug 26 '14 23:08

LennuJ Kram


Video Answer


1 Answers

Cross domain script:

window.parent.postMessage(
    {
        event_id: 'my_cors_message',
        data: {
            v1: 'value1', 
            v2: 'value2'
        }
    }, 
    "*" //or "www.parentpage.com"
); 

Client / parent script:

window.addEventListener('cors_event', function(event) {
    if(event.data.event_id === 'my_cors_message'){
        console.log(event.data.data);
    }
});

Output:

{v1: 'value1', v2: 'value2'}
like image 178
gradosevic Avatar answered Oct 03 '22 19:10

gradosevic