Let's discuss how plugins run inside Figma.

As mentioned previously, plugins are written using JavaScript, HTML and CSS. This exposes a very browser-like environment. It is, however, important to note that writing JavaScript for a Figma plugin has some differences from writing JavaScript for a website.

In order for the plugin system to be secure and stable, some browser APIs are unavailable or need to be accessed differently. We won't bore you with too many details, but it's important to understand our model to answer questions like:

For performance, we have decided to go with an execution model where plugin code runs on the main thread in a sandbox. The sandbox is a minimal JavaScript environment and does not expose browser APIs.

This means that you have all of the standard JavaScript ES6 library available, including the standard types, the JSON and Promise APIs, binary types like Uint8Array, etc. We have also added a minimal version of the console API. But browser APIs like XMLHttpRequest and the DOM are not directly available from the sandbox.

To use browser APIs (e.g. to show UI or to access the network), you will need to create an <iframe> with a <script> tag inside. This can be done with figma.showUI(). Inside of this <iframe>, you can write any HTML/JavaScript and access any browser APIs.

The main thread can access the Figma "scene" (i.e. the hierarchy of layers that make up a Figma document) but not the browser APIs. Conversely, the iframe can access the browser APIs but not the Figma "scene." The main thread and the iframe can communicate with each other through message passing.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/665ab359-5a4a-4964-a0f6-f0513cbcdb39/04c4c6293fce2a7fe67bccd385ee5ab998705780

When the plugin is finished with its work, it must call figma.closePlugin() to tell Figma that it is finished. Otherwise the user will just see "Running [your plugin]" forever.

Note that the user can cancel the plugin at any point by using the UI that Figma displays while the plugin is running. When this happens, Figma will itself call figma.closePlugin().

Tip: to see the list of available JavaScript/Browser APIs on the main thread, run console.log(this) as the first line of your plugin.