LoginSignup
2
1

はじめに


FigmaのPluginを開発する際、Figma PluginsのUI側とcode側でデータを受け渡したいと思ったことはありますか?
この記事では、Figma PluginsのUI側とcode側でデータを受け渡す方法を解説します。

UI側 → code側にデータを渡す

⚪︎ UI側でデータを送る

UI側からデータを送るには、postMessage() という関数を使います。

postMessage(pluginMessage: any, options?: UIPostMessageOptions): void

postMessage() の引数には、any型のpluginMessage と UIPostMessageOptions型のoptions を渡すことができます。

  • UIPostMessageOptions
    • originOAuth を実装するための高度なオプション
      • origin を指定すると、iframe 内のドキュメントの origin と一致する場合にのみ、メッセージが iframe に配信されます
    • *:デフォルト値
      • どのドキュメントにもメッセージを渡すことができる
main.html
<script>
  /* 文字列 を送る */
  parent.postMessage({ pluginMessage: 'anything here' }, '*')

  /* 配列 を送る */
  parent.postMessage({pluginMessage: ['hoge', 'fuga']}, '*')

  /* データ を送る */
  parent.postMessage({pluginMessage: {
    type: 'hgoe',
    isShow: true,
    ...  
  }}, '*')
</script>

⚪︎ code側でデータを受け取る

UI側で送られたデータをcode側で受け取るには、figma.ui.onmessage 関数を使います。

onmessage: MessageEventHandler | undefined

type MessageEventHandler = {
  pluginMessage: any
  props: OnMessageProperties
}

MessageEventHandlerは、引数にpluginMessagepropsを渡すことができます。

  • pluginMessage:UI側から送られたpluginMessageを受け取る
  • propsOAuth を実装するための高度なオプション
    • メッセージを送信したドキュメントのオリジンを含むoriginプロパティが含まれる
code.ts
interface onMessageProps {
  type: string
  isShow: boolean
}

figma.ui.onmessage = (props: onMessageProps) => {
  /* 処理 */
}

code側 → UI側にデータを渡す

⚪︎ code側でデータを送る

code側からデータを送るには、postMessage() という関数を使います。

引数で渡す値はany型なので、どんなデータでも送ることができます。

code.ts
figma.ui.postMessage({
  type: 'hgoe',
  isShow: true,
  ...
})

⚪︎ UI側でデータを受け取る

code側で送られたデータをUI側で受け取るには、onmessageを使います。
postMessageで送られたデータをevent.data.pluginMessage で受け取っています。

main.html
<script>
  onmessage = (event) => {
    /* 処理 */
    console.log(event.data.pluginMessage.type) // コンソールに hoge が表示される
  }
</script>

まとめ

この記事では、Figma PluginsのUI側とcode側でデータを受け渡す方法を解説しました。
ぜひこの記事を参考にUI側とcode側でデータを受け渡してみてください。


最後まで読んでくださってありがとうございます!

普段はデザインやフロントエンドを中心にQiitaで記事を投稿しているので、ぜひQiitaのフォローとX(Twitter)のフォローをお願いします。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1