I’m working on a Figma plugin using React and I’ve hit a snag. The plugin’s setup is similar to Figma’s React example, but I’m having trouble with message passing between files.
In my ui.tsx, I’ve got a button that triggers this on click:
The problem is, the postMessage from code.ts isn’t reaching my ui.tsx:
onmessage = (data) => {
console.log(data);
};
This onmessage function never gets called. I need to get info from code.ts to ui.tsx, but it’s not working. Any ideas on how to fix this or why it’s happening? I’m stuck and could really use some help!
I ran into a similar issue when developing a Figma plugin with React. The problem might be in how you’re setting up the message listener in ui.tsx. Instead of using a global onmessage, try adding an event listener to window:
This approach worked for me. Make sure to wrap it in a useEffect hook if you’re using functional components. Also, double-check that your tsconfig.json includes the correct lib settings for DOM manipulation. Hope this helps!
I’ve been there, mate. Message passing in Figma plugins can be tricky. One thing that solved it for me was using a more robust event listener setup in ui.tsx. Try this:
This approach ensures you’re catching all messages, and it’s cleaner than a global onmessage. Also, double-check your webpack config if you’re using it. Sometimes it can interfere with message passing if not set up correctly.
Lastly, make sure you’re not accidentally overwriting the onmessage handler elsewhere in your code. That caught me out once. Keep at it, you’ll crack it soon!
I’ve encountered this issue before. One thing to check is the origin of your messages. In your code.ts, try specifying the target origin when posting messages:
Also, ensure you’re listening for messages in ui.tsx as soon as the component mounts. You might want to use a useEffect hook for this:
useEffect(() => {
const messageHandler = (event) => {
if (event.data.pluginMessage) {
console.log(event.data.pluginMessage);
// Handle your message here
}
};
window.addEventListener(‘message’, messageHandler);
return () => window.removeEventListener(‘message’, messageHandler);
}, );
This should help establish proper communication between your ui.tsx and code.ts files. Let me know if you still face issues after trying these changes.