London Smith
London Smith

Reputation: 1659

Iframe post Message, passing variable

How to pass variable through postMessage. I can call a parent function like this:

function parent_goTopPage() {
  window.parent.postMessage({"func": "goTopPage"}, "*");
}

But didn't find a way to pass variable in the function. For example the variable myvar in the parent function checkVar:

function checkVar(myvar) {
  alert(myvar);
}

The following javascript does not work:

function parent_checkVar(myvar) {
  window.parent.postMessage({"func": "checkVar(" + myvar + "}, "*");
}

EDIT

I finally realised that I already had this possibility with the "message" option window[data.func].call(null, data.message);

On the parent window:

function checkVar(myvar) {
  alert(myvar);
}

window.addEventListener("message", onMessage, false);

function onMessage(event) {
  // Check sender origin to be trusted
  if (event.origin !== "https://example.com") {
     alert("Error Cross-origin onMessage.");
     return;
  };
   var data = event.data;
   if (typeof(window[data.func]) == "function") {
     window[data.func].call(null, data.message);
  }
}

Inside the iframe:

function parent_checkVar(myvar) {
   window.parent.postMessage({"func": "checkVar", "message":myvar}, "*");
}
parent_checkVar(3);

The choice of "message" was not very clear to me, I changed it to var1 only on (parent windows):

window[data.func].call(null, data.var1);

And on (iframe):

window.parent.postMessage({"func": "checkVar", "var1":myvar}, "*");

With the choice of "message" there was like a misunderstanding with on this line (parent window) window.addEventListener("message", onMessage, false);. "message" must stay with this name.

Upvotes: 1

Views: 2767

Answers (1)

user6702203
user6702203

Reputation:

First, the JavaScript you posted has a malformed object. It should be {"func": "checkVar(" + myvar + ")"}

Second, although you didn't post it, I'm almost certain you're wanting to use eval() for checkVar(myVar). Instead of doing that, you can create an object and assign a function with key name of "checkVar". When you do this, you can pass the checkVar variable separately and call the function using the object. You can see the example below:

Pass an extra key/value with your object. I added "thisvar":myvar.

window.parent.postMessage({"func": "checkVar", "thisvar":myvar}, "*");

On your listener, you create an object with your function inside of it.

var postFunctions = {
  'checkVar': function(myvar) {window.alert(myvar);}
}
window.addEventListener('message', function(event) {
  // checks if the function "checkVar" exists inside the "postFunctions" object
  if (postFunctions[event.data.func]) {
    // if it does exist, call that function and pass the variable as an argument
    postFunctions[event.data.func](event.data.thisvar);
  }
});

Upvotes: 2

Related Questions