How do you send something from the figma document to your plugin's UI?

Hi there, I am trying to send selected text from the document to my ui.html file so that I can display it in the plugin. I’m a newbie to the figma API, so I’m struggling to figure out how to do this. Right now I have the following code:

const selected_text = figma.currentPage.selection;
figma.ui.postMessage({ type: ‘text-selected’,selected_text});

I just want to send the “characters” attribute of the TextNode. However, if I change the code to this

const selected_text = figma.currentPage.selection.characters;
figma.ui.postMessage({ type: ‘text-selected’,selected_text});

I get the error Property ‘characters’ does not exist on type ‘readonly SceneNode’.

How would I approach just sending the characters in a selected node? Thank you!

To avoid these errors, you have to explicitly set type sometimes. Here’s an example:

const iThinkThisIsATextNode = figma.currentPage.selection[0] as TextNode;
const selected_text = iThinkThisIsATextNode.characters;
figma.ui.postMessage({ type: 'text-selected',selected_text});

While the above example may work, it is prone to breakage because the selection may NOT always be a TextNode, so you need to check for that in your code e.g. if (iThinkThisIsATextNode.type === 'TEXT') {

thank you so so much! that makes a lot of sense!