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.