React Figma plugin message communication failing between UI and code files

I’m building a Figma plugin using React and running into issues with message passing between the UI component and the main code file.

I have a button in my UI that triggers this function:

// ui-component.tsx
handleClick = () => {
    parent.postMessage({pluginMessage: {type: 'FetchSelection'}}, '*');
};

This successfully sends a message to my main plugin file, which receives it properly:

// main.ts
figma.ui.onmessage = message => {
  if (message.type === 'FetchSelection') {
    figma.ui.postMessage({"elementName": figma.currentPage.selection[0].name});
  }
};

The problem is that when the main file tries to send data back to the UI, nothing happens. I have this message handler in my UI file:

// ui-component.tsx
onmessage = (data) => {
    console.log(data);
};

This function never gets triggered even though the postMessage call in main.ts executes without errors. I need to get selection data from the main plugin context into my React UI but the return communication isn’t working. Has anyone experienced similar issues with bidirectional messaging in Figma plugins?

try window.onmessage instead of just onmessage in ur react component. had the same issue last month and that’s what fixed it. u need to attach the message handler to the window object.

This happens all the time with Figma plugins and React. You’re setting up the message listener wrong in your UI component. Don’t use a simple onmessage assignment - you need a proper event listener to catch messages from the main plugin thread. Replace your current handler with window.addEventListener('message', (event) => { console.log(event.data); });. Don’t forget to clean up this listener when your component unmounts or you’ll get memory leaks. The main plugin context sends messages as window events, not direct function calls. I’ve hit this exact issue before and this fix works.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.