Edit in GitHubLog an issue

How to make network requests

This sample app will show you how to load an image in an XD object (Rectangle or Artboard) by making network requests using XHR and fetch.

Prerequisites#

Development Steps#

Info Complete code for this plugin can be found on GitHub.

1. Create plugin scaffold#

First, edit the manifest file for the plugin you created in our Quick Start Tutorial.

Replace the uiEntryPoints field of the manifest with the following:

Copied to your clipboard
1"uiEntryPoints": [
2 {
3 "type": "menu",
4 "label": "How to make network requests",
5 "commandId": "applyImage"
6 }
7]

If you're curious about what each entry means, see the manifest documentation, where you can also learn about all manifest requirements for a plugin to be published in the XD Plugin Manager.

Then, update your main.js file, mapping the manifest's commandId to a handler function.

Replace the content of your main.js file with the following code:

Copied to your clipboard
1function applyImage(selection) {
2 // The body of this function is added later
3}
4
5module.exports = {
6 commands: {
7 applyImage,
8 },
9};

The remaining steps in this tutorial describe additional edits to the main.js file.

2. Require in XD API dependencies#

For this tutorial, we just need access to one XD scenegraph class.

Add the following lines to the top of your main.js file:

Copied to your clipboard
1// Add this to the top of your main.js file
2const { ImageFill } = require("scenegraph");

Now the ImageFill class is imported and ready to be used.

3. Write a helper function to make XHR requests#

Our XHR helper xhrBinary will make an HTTP GET request to any URL it is passed, and a return a Promise with an arraybuffer.

Copied to your clipboard
1function xhrBinary(url) {
2 // [1]
3 return new Promise((resolve, reject) => {
4 // [2]
5 const req = new XMLHttpRequest(); // [3]
6 req.onload = () => {
7 if (req.status === 200) {
8 try {
9 const arr = new Uint8Array(req.response); // [4]
10 resolve(arr); // [5]
11 } catch (err) {
12 reject(`Couldnt parse response. ${err.message}, ${req.response}`);
13 }
14 } else {
15 reject(`Request had an error: ${req.status}`);
16 }
17 };
18 req.onerror = reject;
19 req.onabort = reject;
20 req.open("GET", url, true);
21 req.responseType = "arraybuffer"; // [6]
22 req.send();
23 });
24}
  1. xhrBinary function takes a url as a parameter
  2. The function returns a Promise
  3. The function uses XMLHttpRequest to make network requests
  4. Once the correct response comes back, the function uses Unit8Array method to convert the response to an arraybuffer
  5. After the conversion, the promise is resolved
  6. Make sure the set the responseType as arraybuffer

4. Write a helper to apply ImageFill#

This helper function will create an ImageFill instance that can be applied to a user-selected XD scengraph object:

Copied to your clipboard
1function applyImagefill(selection, file) {
2 // [1]
3 const imageFill = new ImageFill(file); // [2]
4 selection.items[0].fill = imageFill; // [3]
5}
  1. The function accepts the selection and a file as parameters
  2. Use the ImageFill class to create the fill
  3. Apply the image to the user-selected XD object

We'll use this function in the next step.

5. Write a helper function to download the image#

Ok, you've just made three helper functions. Now we're going to tie them all together!

Note the use of the async keyword at the beginning of the function.

Copied to your clipboard
1async function downloadImage(selection, jsonResponse) {
2 // [1]
3 try {
4 const photoUrl = jsonResponse.message; // [2]
5 const photoObj = await xhrBinary(photoUrl); // [3]
6 const tempFolder = await fs.getTemporaryFolder(); // [4]
7 const tempFile = await tempFolder.createFile("tmp", { overwrite: true }); // [5]
8 await tempFile.write(photoObj, { format: uxp.formats.binary }); // [6]
9 applyImagefill(selection, tempFile); // [7]
10 } catch (err) {
11 console.log("error");
12 console.log(err.message);
13 }
14}
  1. This helper function accepts the selection and a JSON response object as parameters
  2. Gets the URL from the JSON response
  3. Uses our async xhrBinary function to get an arraybuffer
  4. Uses the fs module and its getTemporaryFolder method to create a temp folder
  5. Uses the createFile method to create a temp file
  6. Uses the write method to write the binary file to store
  7. Uses applyImagefill to place the image into a user-selected XD object

6. Write the main handler function#

This is the function that will be called with the user runs our plugin command.

Copied to your clipboard
1function applyImage(selection) {
2 if (selection.items.length) {
3 // [1]
4 const url = "https://dog.ceo/api/breeds/image/random"; // [2]
5 return fetch(url) // [3]
6 .then(function (response) {
7 return response.json(); // [4]
8 })
9 .then(function (jsonResponse) {
10 return downloadImage(selection, jsonResponse); // [5]
11 });
12 } else {
13 console.log("Please select a shape to apply the downloaded image.");
14 }
15}
  1. Checks if user has selected at least one object
  2. This is an example public URL to an image
  3. Pass the URL to fetch
  4. The first .then block returns the response JSON object
  5. The second .then block passes the selection and our JSON reponse to our downloadImage function, ultimately placing it in the document
Was this helpful?
Copyright © 2021 Adobe. All rights reserved.