#plugin-widget-api:plugin-bugs category would be more appropriate for this post.
That said, is this not working when you are actively interacting with the widget (while it’s open/active)? This listener won’t work while the widget is simply idle on the canvas. Only while the widget is “running” (like when the plugin is open), this listener will work.
Whoops! Thanks, I didn’t see that category!
Thanks for the quick reply Gleb!
What counts as “actively interacting with the widget”?
If I use exactly the code that appears on this page in the documentation — useEffect | Widget API — and I put the widget on the canvas, then I select a Sticky Note somewhere else on the canvas, I expect the widget to receive a “selectionchange” event. It doesn’t 😞
In this case this is not a bug. The widget is not “alive” when you simply place it on the canvas. It only becomes alive and runs the code (and can do things like listen to events) only when you interact with it and keep it running. Just like if you open a plugin, it might close automatically after doing the task or it can stay open (usually if it has some kind of UI) until you close it or open another plugin. I don’t know exactly how it’s done in widgets but this looks close: waitForTask | Widget API
Note that if your goal is to listen to events at all times, this is not possible with widgets and plugins. They both live only temporarily while the user interacts with them and only one widget or plugin can be active at one time so you can’t keep one open forever.
Thanks! That link you shared helped a lot — adding a waitForTask did (temporarily) allow the events to be handled.
For anyone else that finds this thread, the code in the documentation doesn’t work because for the widget to be active it has to be selected and listening for selection events while the widget is selected is pretty limiting, but changing the code to something like this will make it work for a short while:
const { widget } = figma;
const { Text, useEffect, waitForTask } = widget;
function EventHandlerExample() {
useEffect(() => {
const logSelection = () => {
console.log(figma.currentPage.selection);
};
figma.on("selectionchange", logSelection);
return () => figma.off("selectionchange", logSelection);
});
useEffect(() => {
waitForTask(
new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, 60000); // Some arbitrary long time
})
);
});
return <Text>Event handler example</Text>;
}
widget.register(EventHandlerExample);
Changing the timeout, or finding ways to keep the widget “active” for the duration you require, is the challenge 👍
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.