Promise-based messaging between plugin and ui

Does anyone know of a way to do promise-based messaging between the plugin and the UI? (@Gleb :slight_smile:)

Using the globals:

parent.postMessage(...) β†’ figma.ui.onmessage β†’ figma.ui.postMessage(...) β†’ window.onmessage can lead to spaghetti code… promises would be so much cleaner.

Really only the UI β†’ Plugin direction would be fine, e.g.:

someCoolMessaging.post(type: 'get-some-data', payload: { id: 5 }).then(data => {
    console.log('got some data', data)
})
.catch((error) => {
  console.log('error getting data from plugin')
})

Found this: GitHub - okotoki/figma-messenger: Type-safe communication for good 🧐. and I have this: Figma Plugin Utility: html <-> script I/O for TypeScript · GitHub but there are more.

2 Likes

figma-messenger seems to be just a type-safe version of 1-way comms, but html<->script I/O seems to have a way to do async/promises. Will try it, thanks!

1 Like

I’ve created a library for it, and maybe I should publish it. It is built on top of Utilities β€” Create Figma Plugin with 3 basic primitives: req, res and subscribe.

I should probably publish it too.

This emit utility will help a lot. Any mechanism that abstracts iframe <=> iframe communication will help too.

In any case, what you are asking is

// ui.js
await Main.drawRect()

// main.js
function drawRect() { 
  const rect = figma.createRect()
  ....
}

From what I’ve seen no other library currently supports this.