'Figma React plugin PostMessage not working as expected

I'm trying to create a plugin for Figma, which has been going fine until now. It's based on the react example they provide on their github page: https://github.com/figma/plugin-samples/tree/master/react

In this example I've created a button, that on click will call this function:

(file: ui.tsx)
    onClick = () => {
        parent.postMessage({pluginMessage: {type: 'GetData'}}, '*');
    };

This is parent.postMessage is a function figma provides to communicate with another file in the project, code.ts. This file will receive the postMessage with the pluginMessage as parameter, which works as expected. The code.ts that receives this looks like this:

(file: code.ts)
    figma.ui.onmessage = msg => {
      if (msg.type === 'GetData') {
        figma.ui.postMessage({"title": figma.currentPage.selection[0].name});
      }
    };

This file receives the message, and it gets in the if statement since GetData has been set. Up until here, everything is good and well. The issue I'm walking into is the figma.ui.postMessage({}), which should do a callback to the onmessage function in ui.tsx:

(file: ui.tsx)
    onmessage = (selection) => {
        console.log(selection);
    };

This onmessage function should, according to Figma's documentation, receive the object from the postMessage in code.ts. This does however never happen; it will never be called at all. I can't access the current selection in ui.tsx, so I need data from code.ts. Is there any way to pass this data to ui.tsx, or does anyone know why this doesn't work?



Solution 1:[1]

I encountered the same issue. Within your ui.tsx file, try adding the following:

window.onmessage = selection => {
   let message = selection.data.pluginMessage;
   console.log(message);
}

Solution 2:[2]

or try this ->

window.addEventListener("message", (selection) => {
    console.log(selection);
});

this will add another message event handler to the window. if you use onmessage it might overwrite the previous handler!

Solution 3:[3]

put first of script

onmessage = event => {
  console.log("got this from the plugin code", event, event.data.pluginMessage)
}

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 greg
Solution 2 Elmer
Solution 3 user2781421