Skip to main content

Making Network Requests

In this section we will show you the basics of making network requests within a Figma plugin. It's mostly the same as in normal JavaScript running directly inside of a web browser: the only caveat is that the APIs for making network requests are provided by the browser, not by the Figma plugin sandbox itself. You may recall from the execution model section that you will need to create an <iframe> to access browser APIs.

The plugin below demonstrates this. It creates an invisible <iframe> as a worker, then uses that to make a network request. When it gets the result of that network request, it creates a text node with the contents of the response.

code.ts: Invisible iframe worker
figma.showUI(__html__, { visible: false })
figma.ui.postMessage({ type: 'networkRequest' })

figma.ui.onmessage = async (msg) => {
const text = figma.createText()
// Make sure the new text node is visible where we're currently looking
text.x = figma.viewport.center.x
text.y = figma.viewport.center.y

await figma.loadFontAsync(text.fontName as FontName)
text.characters = msg

figma.closePlugin()
}

The worker (the invisible "UI" which is the content of the <iframe>) is implemented in a separate file referred to by the ui section of manifest.json. Here, the worker simply makes a standard XMLHttpRequest and sends the results back to the main thread.

ui.html: Make network request
<script>
window.onmessage = async (event) => {
if (event.data.pluginMessage.type === 'networkRequest') {
var request = new XMLHttpRequest()
// This link has random lorem ipsum text
request.open('GET', 'https://cors-anywhere.herokuapp.com/http://www.randomtext.me/download/text/lorem/ul-8/5-15')
request.responseType = 'text'
request.onload = () => {
window.parent.postMessage({pluginMessage: request.response}, '*')
};
request.send()
}
}
</script>
info

Note: because Figma and Figma plugins run inside a browser environment, Cross-Origin Resource Sharing policies apply. Plugins run inside an iframe with a null origin. This means that they will only be able to call APIs with Access-Control-Allow-Origin: * (i.e., those that allow access from any origin). In the example above, we use a CORS proxy for simplicity, but it's not something you generally need to or should use.