'Javascript PostMessage with JSON object as data

I have to post JSON object as data using javascript PostMessage method, below is the object that I would like to post:

{ 
   "Type" : "Login" 
}

I believe this method is used to between iframe implemented inside a website, the iframe source URL is different from the parent window, how do I implement it in code?

I have this sample code I used, but I don't understand how to it work and how can I test it. Appreciate if someone can help!!

Code:

    @{
        string jsonParameter = Newtonsoft.Json.JsonConvert.SerializeObject("Login");
    }

    var jsonData = "@Html.Raw(jsonParameter)";
    parent.postMessage({ "Type": jsonData }, "*");


Solution 1:[1]

You are correct, PostMessage is used to send messages between ifames. The code you have given in your sample is intended to be used in a child iframe and it is sending a message to the parent iframe.

In the parent iframe You also need to listen for messages coming in, for example

window.addEventListener("message", (event) => {
  console.log("Received data from child iframe ", event.data);
});

Assuming you are sending a static message, the code sample you have given that sends a message to the parent iframe can also be simplified as there is no need for the c#

parent.postMessage({ "Type": ""Login }, "*");

Please also note the second parameter to PostMessage should be an expected domain instead of "*" as it prevents malicious sites from intercepting messages. I would recomend reading the mdn page for more information https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samuel