'Post a message from iframe in React

I have trouble about sending message from cross-domain iframe in React. I read many articles, most of them are about sending message to iframe.

The issue is that it didn't show any error message in the page that embed the iframe , and when I go to the see the page that I embed, it did show a error message.

Scene.js:230 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://thewebsite.com') does not match the recipient window's origin ('https://mywebsite').

so I can't tell if I the message have been sent successfully or not.

Here is my code :

confirm = () => {
    const { homeId, correctData } = this.state
    const form = new FormData();

    //process data
    form.append('scene_id', homeId)
    form.append('material_id', correctData[0].id)
    form.append('material_img', correctData[0].component_img)

    const obj = JSON.parse(JSON.stringify(form));
    //
    //way 1
    parent.postMessage(obj, '*')

    //way 2
    parent.postMessage(obj, 'https://www.thewebsite.com/pro_wall.html')

    //way 3
    window.frames.postMessage(obj, '*')

    //way 4
    window.top.postMessage(obj, '*')

    //way 5
    const targetWindow = window.open('https://www.thewebsite.com/pro_wall.html')

    setTimeout(() => {
      targetWindow?.postMessage(obj, '*')
    }, 3000)  
  }

Sorry for writing too many ways to post message, Just want to make sure I tried every possibility.



Solution 1:[1]

After few tries, I got positive feedback from client said they got data. This is my code I wrote eventually.

confirm = () => {
  const { homeId, correctData } = this.state
  const formData = new FormData();

  formData.append('scene_id', homeId)
  formData.append('material_id', correctData[0]?.id)
  formData.append('material_img', correctData[0]?.component_img)

  var object = {};
  formData.forEach((value, key) => {object[key] = value});
  var json = JSON.stringify(object);

  parent.postMessage(json, `https://www.thewebsite.com/pro_wall.html`)
} 

and I saw the code at client's side from web devTool, it looks like this,

<scritp>
  window.addEventListener("message", receivewall, false);
  function receivewall(event){
      var origin = event.origin;
      if(origin == 'https://mywebsite'){
          var params = JSON.parse(event.data);
          $('#result').html($.param(params));
          // console.log(params);
      }
      // $('#result').html(data);
  }
  function getQueryVariable(query) {
      var vars = query.split('&');
      var params = {};
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      }
      return params;
  }
</scritp>

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 Karen Huang