### Install Spectrum Web Component Button Source: https://developer.adobe.com/indesign/uxp/resources/fundamentals/create-ui To use UXP Spectrum Web Components (Beta), install them individually using npm. This example shows installing the Spectrum button component. ```bash npm i @spectrum-web-components/button@0.19.8 ``` -------------------------------- ### Setup UXP Plugin Entry Points Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry Points/EntryPoints Configure plugin lifecycle, panels, and commands using `entrypoints.setup`. This example demonstrates defining panel creation, showing, hiding, destruction, menu item configurations, and command run/cancel functions. ```javascript const { entrypoints } = require("uxp"); entrypoints.setup({ plugin: { create() {..}, destroy() {..} }, panels: { "panel1": { create() {..}, show() {..}, hide() {..}, destroy() {..}, invokeMenu() {..}, update() {..}, // customEntrypoint example validatNode() {..} // customEntrypoint example menuItems: [ { id: "signIn", label: "Sign In...", enabled: false, checked: false submenu: [ { id: "submenu1", label: "submenu1", enabled: false, checked: false}, { "submenu2" } ] }, "-", // separator. "Sign out", // by default enabled, and the id will be same with the label. ] }, "panel2": {..} }, commands: { "command1": { run() {..}, cancel() {..} }, "command2": function(){..} } }); ``` -------------------------------- ### XMLHttpRequest GET Request Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/Data Transfers/XMLHttpRequest Demonstrates how to initiate a GET request using XMLHttpRequest and log the response text upon successful loading. ```javascript const xhr = new XMLHttpRequest(); xhr.addEventListener("load", () => { console.log(xhr.responseText); }); xhr.open("GET", "https://www.adobe.com"); xhr.send(); ``` -------------------------------- ### Install SWC Component via npm Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-spectrum/swc Install the desired SWC component package using npm. This example shows installing the button component. ```bash npm install @swc-uxp-wrappers/button ``` -------------------------------- ### Example Output of Host Environment Info Source: https://developer.adobe.com/indesign/uxp/resources/recipes/host-info This is an example of the console output when the host environment information script is executed. ```text System information: darwin v21.1.0 Application: InDesign v18.5.0 powered by uxp-7.1.0 ``` -------------------------------- ### Example Spectrum Web Component Button Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest Shows how to use a Spectrum Web Component button. This requires `enableSWCSupport` to be true in the manifest and the component to be installed and imported. ```html Click me ``` -------------------------------- ### justify-content: flex-start Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-css/Styles/justify-content This example demonstrates how to use justify-content with the flex-start value to align items to the beginning of the main axis. ```css .someElement { justify-content: flex-start; } ``` -------------------------------- ### Example manifest.json with StringsDefinition Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest This example shows how to define a plugin name and localized strings within the manifest.json file. The 'strings' property allows for default and locale-specific translations. ```json { "name": "my-plugin", "strings": { "my-plugin": { "default": "My Plugin", "de": "Mein Plugin" } } } ``` -------------------------------- ### UXP Plugin Manifest Example Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest This is a complete example of a manifest.json file. It includes essential fields like manifestVersion, id, name, version, main entry point, host configuration, command and panel entry points, icon definitions, and required permissions. ```json { "manifestVersion": 5, "id": "YOUR_ID_HERE", "name": "Name of your plugin", "version": "1.0.0", "main": "index.html", "host": { "app": "HOST_APPLICATION", "minVersion": "HOST_VERSION" }, "entrypoints": [ { "type": "command", "id": "commandFn", "label": { "default": "Show A Dialog" } }, { "type": "panel", "id": "panelName", "label": { "default": "Panel Name" } } ], "icons": [ { "width": 24, "height": 24, "path": "icons/icon.png", "scale": [ 1, 2 ] } ], "requiredPermissions": { "network": { "domains": "all" } } } ``` -------------------------------- ### Controlling video playback and seeking Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLVideoElement This example demonstrates how to get a reference to a video element, play it, set its current playback time, and listen for the 'seeked' event. Ensure the video element has an ID for programmatic access. ```html ``` -------------------------------- ### Using align-self: flex-start Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-css/Styles/align-self This example demonstrates how to use the `align-self` property with the `flex-start` value to align an element to the start of its container's cross axis. ```css .someElement { align-self: flex-start; } ``` -------------------------------- ### Install Spectrum Web Component Button Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-spectrum Command to install the Spectrum Web Component button package using npm. This is required before importing and using SWC components. ```bash npm i @swc-uxp-wrappers/button ``` -------------------------------- ### Invalid Domain Configuration Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLWebViewElement This example shows an invalid configuration for the 'domains' attribute in the manifest.json, where top-level wildcards are not permitted. ```json "requiredPermissions": { "webview": { "domains": ["https://www.*", "https://www.adobe.*"], "allow": "yes" } } ``` -------------------------------- ### HTMLVideoElement Example: Setting currentTime and listening for seeked event Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global%20Members/HTML%20Elements/HTMLVideoElement This example demonstrates how to set the current playback time of a video element and listen for the 'seeked' event. ```APIDOC ## Example ```html ``` ``` -------------------------------- ### Get Plugin, Plugin-Data, and Temp Folder Paths Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLWebViewElement Use the 'uxp' API to get the root paths for the plugin, plugin-data, and temporary folders. This is useful for managing local files accessed by the WebView. ```javascript const localFileSystem = require("uxp").storage.localFileSystem; const pluginFolder = await localFileSystem.getPluginFolder(); const pluginDataFolder = await localFileSystem.getDataFolder(); const tempFolder = await localFileSystem.getTemporaryFolder(); console.log(`pluginFolder = ${pluginFolder.nativePath}`); console.log(`pluginDataFolder = ${pluginDataFolder.nativePath}`); console.log(`pluginTempFolder = ${tempFolder.nativePath}`); ``` -------------------------------- ### arch() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/os/OS Gets the platform architecture. ```APIDOC ## arch() ### Description Gets the platform architecture we are running on (eg. "x32, x64, x86_64 etc") ### Returns `string` - the string representing the architecture ``` -------------------------------- ### Use WebView Component Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest Example of embedding a webview in the plugin's UI. ```html ``` -------------------------------- ### Make Network Requests Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest Example of making a fetch request to an allowed domain. ```javascript const response = await fetch("https://example.com"); ``` -------------------------------- ### setup(entrypoints) Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry Points/EntryPoints Initializes the plugin's entry points, including handlers for plugin creation/destruction, panel lifecycle events, and command executions. This function should be called only once. ```APIDOC ## setup(entrypoints) ### Description API for plugin to add handlers and menu items for entrypoints defined in manifest. This API can only be called once and thereafter other APIs can be used to modify menu items. The function throws in case of any error in entrypoints data or if its called more than once. ### Parameters #### entrypoints (`Object`) It consists of mainly three objects - 'plugin', 'panels' and 'commands'. ##### entrypoints.plugin (`Object` | `function`) This can be an object or a function. If this is a function, it is assumed as the 'create' handler. - **create** (`function`): Called after the plugin is loaded. 'this' can be used to access UxpPluginInfo object. If 'plugin' object is defined, 'create' must be defined. To signal failure, throw an exception. - **destroy** (`function`): Called before the plugin is unloaded. 'this' can be used to access UxpPluginInfo object. ##### entrypoints.panels (`Array`) Contains a list of key-value pairs where each key is a panel id (string) and value is the data for the panel whose type can be object/function. If a function, it is assumed to be the 'show' method. If an object, it can contain following properties, but it is a must to define either 'create' or 'show'. - **create** (`function`): Called when a panel is created. 'this' can be used to access UxpPanelInfo object. This function can return a promise. To signal failure, throw an exception or return a rejected promise. Default Timeout: 300 MSec (from manifest v5 onwards). - Parameters (till Manifest Version V4): `create(event)` - Parameters (from v5 onwards): `create(rootNode)` - **show** (`function`): Called when a panel is shown. 'this' can be used to access UxpPanelInfo object. This function can return a promise. To signal failure, throw an exception or return a rejected promise. Default Timeout: 300 MSec (from manifest v5 onwards). - Parameters (till Manifest Version V4): `show(event)` - Parameters (from v5 onwards): `show(rootNode, data)` - **hide** (`function`): Called when a panel is hidden. 'this' can be used to access UxpPanelInfo object. This function can return a promise. To signal failure, throw an exception or return a rejected promise. Default Timeout: 300 MSec (from manifest v5 onwards). - Parameters (till Manifest Version V4): `hide(event)` - Parameters (from v5 onwards): `hide(rootNode, data)` - **destroy** (`function`): Called when a panel is going to be destroyed. 'this' can be used to access UxpPanelInfo object. To signal failure, throw an exception. - Parameters (till Manifest Version V4): `destroy(event)` - Parameters (till Manifest Version V4): `destroy(rootNode)` - **invokeMenu** (`function`): Called when a panel menu item is invoked. Menu id is passed as the first argument. 'this' can be used to access UxpPanelInfo object. This function can return a promise. To signal failure, throw an exception or return a rejected promise. - **customEntrypoint** (`function`): Host Apps can define additional entrypoints for custom lifecycle events. Details are defined by the host app. Currently, Photoshop hasn't defined any custom entrypoints. XD has defined one custom entrypoint `update`. - Parameters: `update(scenegraph.selection, scenegraph.update)` - **menuItems** (`Array`): Array of menu items. Each menu item can be a string or an object with properties defined below. Menu items are displayed in the same order as specified in this array. For specifying a separator, a value of "-" or a menu item with label "-" can be used. - **id** (`string`): Identifier of the menu item. - **label** (`string`): Display text for the menu item. Should be localized. If label is not specified, id is used as label. - **enabled** (`boolean`): Enabled/disabled state for the menu item. Default: true. - **checked** (`boolean`): Checked state for the menu item. Default: false. - **submenu** (`Array`): Submenu for this menu item, again as an array of 'menuItems'. 'id' of submenus should still be unique across the panel. ##### entrypoints.commands (`Array`) Contains a list of key-value pairs where each key is the command id and value is command's data whose type can be an object or function. If a function, it is assumed to be the 'run' method. If an object, it can contain the following properties, but 'run' is a must to specify. - **run** (`function`): The main handler for the command. ``` -------------------------------- ### Setup Entrypoints using UXP API Source: https://developer.adobe.com/indesign/uxp/plugins/tutorials/adding-command-entrypoints Associate command entrypoints with their handler functions using the `entrypoints.setup()` method from the UXP API. This method can only be called once. ```javascript const { entrypoints } = require("uxp"); entrypoints.setup({ commands: { myCommand: myCommandHandler } }); ``` -------------------------------- ### entrypoints.setup Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry Points/EntryPoints Sets up the entry points for your UXP plugin. This includes defining plugin lifecycle methods, panel configurations, and command handlers. ```APIDOC ## setup(entrypoints) ### Description Configures the plugin's entry points, including commands, panels, and plugin lifecycle. ### Parameters * **entrypoints** (object) - An object defining the plugin's entry points. * **plugin** (object) - Plugin lifecycle methods. * **create** (function) - Called when the plugin is created. * **destroy** (function) - Called when the plugin is destroyed. * **panels** (object) - Configuration for plugin panels. * **[panelId]** (object) - Configuration for a specific panel. * **create** (function) - Called when the panel is created. * **show** (function) - Called when the panel is shown. * **hide** (function) - Called when the panel is hidden. * **destroy** (function) - Called when the panel is destroyed. * **invokeMenu** (function) - Called when a menu item associated with the panel is invoked. * **update** (function) - Custom entry point example. * **validatNode** (function) - Custom entry point example. * **menuItems** (array) - Defines menu items for the panel. * **{object}** - Menu item configuration. * **id** (string) - Unique identifier for the menu item. * **label** (string) - Text displayed for the menu item. * **enabled** (boolean) - Whether the menu item is enabled. * **checked** (boolean) - Whether the menu item is checked. * **submenu** (array) - Defines a submenu for the menu item. * **"-"** - Represents a menu separator. * **"[label]"** (string) - A simple menu item with its label as the ID. * **commands** (object) - Configuration for plugin commands. * **[commandId]** (object | function) - Configuration or handler for a specific command. * **run** (function) - This is called when the command is invoked via menu entry. 'this' can be used to access UxpCommandInfo object. This function can return a promise. To signal failure, throw an exception or return a rejected promise. Parameters : run(event) {}, till Manifest Version V4 run(executionContext, ...arguments) {}, from v5 onwards * **cancel** (function) - For future use. ### Example ```javascript const { entrypoints } = require("uxp"); entrypoints.setup({ plugin: { create() { /* ... */ }, destroy() { /* ... */ } }, panels: { "panel1": { create() { /* ... */ }, show() { /* ... */ }, hide() { /* ... */ }, destroy() { /* ... */ }, invokeMenu() { /* ... */ }, update() { /* ... */ }, // customEntrypoint example validatNode() { /* ... */ } // customEntrypoint example menuItems: [ { id: "signIn", label: "Sign In...", enabled: false, checked: false, submenu: [ { id: "submenu1", label: "submenu1", enabled: false, checked: false}, { "submenu2" } ] }, "-", // separator. "Sign out", // by default enabled, and the id will be same with the label. ] }, "panel2": { /* ... */ } }, commands: { "command1": { run() { /* ... */ }, cancel() { /* ... */ } }, "command2": function() { /* ... */ } } }); ``` ``` -------------------------------- ### Get User ID Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/User Information Retrieve the GUID of the plugin user. This method is read-only and available since v7.3.0. ```javascript let userId = require('uxp').userInfo.userId(); // Get the GUID of plugin user console.log(userId); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ``` -------------------------------- ### Get Plugins Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Plugin Manager/PluginManager Retrieves the current list of plugins installed in the host application. This is useful for Inter-Plugin Communication (IPC). ```APIDOC ## plugins ### Description To get the current list of plugins in Plugin Manager. ### Returns - `Set` - A Set containing Plugin objects. ``` -------------------------------- ### Get PluginManager Instance Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Plugin Manager/PluginManager Obtain an instance of the PluginManager to interact with installed plugins. This is the entry point for managing plugins. ```javascript const { pluginManager } = require("uxp"); ``` -------------------------------- ### window.fetch(input, [init]) Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/Data Transfers/fetch Fetches a resource from the network. Requires network permissions to be configured in the manifest.json. ```APIDOC ## window.fetch(input, [init]) ### Description Fetches a resource from the network. ### Parameters #### Path Parameters - **input** (string | Request) - Required - Either the URL string to connect with or a Request object having the URL and the init option. - **init** (Object) - Optional - Custom settings for a HTTP request. - **init.method** (string) - HTTP request method. The default value is "GET". - **init.headers** (Headers) - HTTP request headers to add. - **init.body** (string | ArrayBuffer | TypedArray | Blob | FormData | URLSearchParams) - Body to add to HTTP request. - **init.credentials** (string) - Indicates whether to send cookies. The default value is "include". Possible values are "omit" (cookies are NOT sent) or "include" (cookies are sent). ### Returns `Promise` - Promise that resolves to a Response object. ### Throws - `TypeError` - If init.body is set and init.method is either "GET" or "HEAD". - `TypeError` - If either network error or network time-out occurs after a http request is made. - `TypeError` - If there is a failure in reading files in FormData during posting FormData. ### Permissions To use `fetch`, update the `manifest.json` with the `network.domains` permission: ```json { "permissions": { "network": { "domains": [ "https://www.adobe.com", "https://*.adobeprerelease.com", "wss://*.myplugin.com" ] } } } ``` **Limitation:** From UXP v7.4.0 onwards `permissions.network.domains` does not support WildCards in top-level domains. ``` -------------------------------- ### Get File Instance Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Persistent File Storage/File Demonstrates how to obtain a File instance using `createEntryWithUrl`. This method requires the `uxp` module and its `localFileSystem`. The `isFile` property can then be checked. ```javascript const fs = require('uxp').storage.localFileSystem; const file = await fs.createEntryWithUrl("file:/Users/user/Documents/tmp"); // Gets a File instance console.log(file.isFile); // returns true ``` -------------------------------- ### XMPMeta Constructor and Basic Usage Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/XMP/XMP%20Classes/XMPMeta Demonstrates creating an XMPMeta object and using basic property manipulation functions like setProperty, getProperty, and doesPropertyExist. ```APIDOC ## XMPMeta Constructor ### Description Creates an XMPMeta object. It can be initialized with an RDF/XML serialized metadata packet or an array of bytes. If no argument is provided, an empty object is created. ### Parameters - **packet** (string) - Optional - A String containing an XML file or an XMP packet. - **buffer** (Array) - Optional - An Array of Numbers representing the UTF-8 or UTF-16 encoded bytes of an XML file or an XMP packet. ### Example ```javascript let { XMPMeta, XMPConst } = require("uxp").xmp; let meta = new XMPMeta(); meta.setProperty(XMPConst.NS_XMP, "Name", "vkumarg"); let prop = meta.getProperty(XMPConst.NS_XMP, "Name"); console.log(prop.namespace); console.log(prop.options); console.log(prop.path); if(meta.doesPropertyExist(XMPConst.NS_XMP, "Name")) { meta.deleteProperty(XMPConst.NS_XMP, "Name"); } if(!meta.doesPropertyExist(XMPConst.NS_XMP, "Name")) { console.log("Property doesn't exist"); } else { console.log("Property exists"); } ``` ``` -------------------------------- ### Get Element Bounding Rectangle Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLLinkElement Gets the size and position of an element relative to the viewport. ```javascript const rect = element.getBoundingClientRect(); ``` -------------------------------- ### Basic sp-link Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-spectrum/Spectrum UXP Widgets/User Interface/sp-link Renders a standard link that navigates to a specified URL when clicked. Ensure the href attribute is provided to launch a browser. ```html Adobe ``` -------------------------------- ### Establish WebSocket Connection Source: https://developer.adobe.com/indesign/uxp/resources/recipes/network This example demonstrates establishing a WebSocket connection, sending a message, and handling incoming messages, connection status, and errors. The `javascript.info` domain is used for the WebSocket server. ```javascript let socket; async function foo() { // Establish web socket connection if (!!socket) { console.log("Already connected; disconnecting first."); await socket.close(); return; } socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello"); socket.onopen = function(e) { console.log("Connection established"); // sending data to server socket.send("My name is John"); }; socket.onmessage = function(event) { alert(`Data received from server: ${event.data}`); }; socket.onclose = function(event) { console.log("Connection closed"); socket = null; }; socket.onerror = function(error) { console.error(`Connection error ${error}`); }; } ``` ```json { "requiredPermissions": { "network": { "domains": [ "wss://javascript.info" ] } } } ``` -------------------------------- ### Example CSS for SVG Fill Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest Provides the CSS to define the `--iconColor` variable used in the example SVG. ```css :root { --iconColor: blue; } ``` -------------------------------- ### open() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global%20Members/Data%20Transfers/XMLHttpRequest Initializes a request or re-initializes an existing one. Note that UXP does not support synchronous requests, so the async parameter must be true. ```APIDOC ## open(method, url, [async], [user], [password]) ### Description Initializes a request or re-initializes an existing one. Self-signed certificates are not currently supported for HTTPS connections. Note that UXP does not support synchronous request, which means 'async' is false. ### Parameters #### Path Parameters * **method** (string) - Required - HTTP request method to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs. * **url** (string) - Required - String representing the URL to send the request to. * **[async]** (boolean) - Optional - Defaults to `true`. Indicates whether or not to perform the operation asynchronously. If this value is false, the send() method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown. * **[user]** (string) - Optional - Defaults to `null`. User name to use for authentication purposes. * **[password]** (string) - Optional - Defaults to `null`. Password to use for authentication purposes. ### Throws * `DOMException` NotSupportedError if async parameter is false * `DOMException` TypeError if method and url parameters are not provided * `DOMException` SyntaxError if either method is not valid or url cannot be parsed. * `DOMException` SecurityError if method matches for CONNECT, TRACE or TRACK. ``` -------------------------------- ### Install Yarn Package Manager Source: https://developer.adobe.com/indesign/uxp/introduction/essentials/tech-stack Use npm to install Yarn globally. Yarn is an alternative package manager for Node.js projects. ```bash npm install yarn --global ``` -------------------------------- ### Accessing an Entry Instance Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Persistent File Storage/Entry Demonstrates how to obtain an Entry instance (specifically a Folder) using localFileSystem and then access its properties. ```javascript const fs = require('uxp').storage.localFileSystem; const folder = await fs.getPluginFolder(); // returns a Folder instance const folderEntry = await folder.getEntry("entryName.txt"); // Now we can use folderEntry to invoke the APIs provided by Entry console.log(folderEntry.isEntry); // isEntry is an API of Entry, in this example it will return true ``` -------------------------------- ### Getting the Native File System Path Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Persistent File Storage/Entry Access the `nativePath` property to get the platform-specific file system path for the entry. This property is read-only. ```javascript console.log(anEntry.nativePath); ``` -------------------------------- ### HTMLVideoElement Example: Seeking to the end of the video Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global%20Members/HTML%20Elements/HTMLVideoElement This example shows how to set the video's current time to its duration when the 'loadeddata' event is fired. ```APIDOC ## Example ```html ``` ``` -------------------------------- ### Using display: flex Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-css/Styles/display This example shows how to set an element's display to flex using CSS. ```css .someElement { display: flex; } ``` -------------------------------- ### Get File/Folder Stats Synchronously Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/fs Use `lstatSync` to get file or folder information synchronously. The returned object's methods might have platform limitations. ```javascript const stats = fs.lstatSync("plugin-data:/textFile.txt"); const birthTime = stats.birthtime; ``` -------------------------------- ### Making an HTTP GET Request with XMLHttpRequest Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/Data Transfers/XMLHttpRequest This snippet demonstrates how to initialize an XMLHttpRequest, set up an event listener for the response, configure the request with overrideMimeType, and send the request. Note that UXP does not support synchronous requests, so the 'async' parameter in open() must be true. ```javascript const xhr = new XMLHttpRequest(); xhr.onload = () => { console.log(xhr.response); console.log(xhr.responseText); }; xhr.open("GET", "https://www.myxmlserver.com"); xhr.overrideMimeType("text/plain"); xhr.send(); ``` -------------------------------- ### Setup UXP Plugin Entry Points Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry%20Points/EntryPoints Use this code to define the lifecycle methods for your plugin, panels, and commands. Panels can have custom menu items and lifecycle methods. ```javascript const { entrypoints } = require("uxp"); entrypoints.setup({ plugin: { create() {..}, destroy() {..} }, panels: { "panel1": { create() {..}, show() {..}, hide() {..}, destroy() {..}, invokeMenu() {..}, update() {..}, // customEntrypoint example validatNode() {..} // customEntrypoint example menuItems: [ { id: "signIn", label: "Sign In...", enabled: false, checked: false, submenu: [ { id: "submenu1", label: "submenu1", enabled: false, checked: false}, { "submenu2" } ] }, "-", // separator. "Sign out", // by default enabled, and the id will be same with the label. ] }, "panel2": {..} }, commands: { "command1": { run() {..}, cancel() {..} }, "command2": function(){..} } }); ``` -------------------------------- ### Get XMPMeta Object using XMPFile Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/XMP/XMP Classes/XMPFile Demonstrates how to instantiate XMPFile and retrieve the associated XMPMeta object for a given file. Ensure the XMPFile class is imported from 'uxp'. ```javascript // Example of using the XMPFile class to get the XMPMeta object // Import the XMPFile class const { XMPFile } = require("uxp").xmp; // Create a new XMPFile object const xmpFile = new XMPFile("sample.psd", XMPConst.FILE_PHOTOSHOP, XMPConst.OPEN_FOR_UPDATE); // Get the XMPMeta object const xmpMeta = xmpFile.getXMP(); ``` -------------------------------- ### Create Folder and File in UXP Source: https://developer.adobe.com/indesign/uxp/resources/recipes/file-operation Use `createEntryWithUrl` to create a new folder and then `createFile` to create a file within that folder. The `overwrite` option can be set to true to replace existing files. Ensure to check `isFolder` before proceeding. ```javascript const { localFileSystem, types } = require('uxp').storage; async function foo(){ // Create new folder and file try { const newFolderEntry = await localFileSystem.createEntryWithUrl("plugin-temp:/temp", { type: types.folder }); if (newFolderEntry.isFolder) { const newFile = await newFolderEntry.createFile("temp.txt", {overwrite: true}); await newFile.write("Sample file created."); } } catch (e) { console.error(e); } } ``` -------------------------------- ### Example LocalizedString object Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest This example demonstrates the structure of a LocalizedString object, which includes a default value and translations for specific locales. It's used for localizing various user-facing strings. ```json { "default": "Hello", "en": "Hello", "de": "Hallo" } ``` -------------------------------- ### Using Schemes for File Locations Source: https://developer.adobe.com/indesign/uxp/resources/recipes/file-operation UXP provides schemes to represent different file locations. Use 'plugin:/', 'plugin-data:/', and 'plugin-temp:/' for sandbox locations, and 'file:/' for external paths. ```html ``` -------------------------------- ### CSS Child Combinator Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-css/Selectors/Child combinator This example demonstrates how to use the child combinator to select and style direct child elements. It targets all 'sp-button' elements that are direct children of a 'footer' element. ```css footer > sp-button { margin: 12px; } ``` -------------------------------- ### Stop Video Playback and Listen for Events Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLVideoElement Starts video playback, stops it (pausing and resetting to the beginning), and logs messages for both the uxpvideostop and seeked events. This is useful for resetting playback to the start. ```html ``` -------------------------------- ### Get UXP Entry Points Instance Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry Points/EntryPoints Use this method to obtain an instance of the UXP entry points. This is the primary way to interact with UXP functionalities. ```javascript require("uxp").entrypoints ``` -------------------------------- ### Get XMPMeta Object using XMPFile Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/XMP/XMP%20Classes/XMPFile Demonstrates how to instantiate XMPFile and retrieve the XMPMeta object for a given file. Ensure the necessary XMPFile class is imported. ```javascript const { XMPFile } = require("uxp").xmp; // Create a new XMPFile object const xmpFile = new XMPFile("sample.psd", XMPConst.FILE_PHOTOSHOP, XMPConst.OPEN_FOR_UPDATE); // Get the XMPMeta object const xmpMeta = xmpFile.getXMP(); ``` -------------------------------- ### Get Host Environment Info with JavaScript Source: https://developer.adobe.com/indesign/uxp/resources/recipes/host-info Use this snippet to log system and application information. It requires importing the 'uxp' and 'os' modules. ```javascript async function foo() { const { host, versions } = require('uxp'); const osInfo = require('os'); console.log(`System information: ${osInfo.platform()} v${osInfo.release()}`); console.log(`Application: ${host.name} v${host.version} powered by ${versions.uxp}`); } ``` -------------------------------- ### Manifest.json Domain Limitation Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/Data Transfers/fetch From UXP v7.4.0 onwards, the 'domains' property in network permissions does not support wildcards in top-level domains. This example illustrates the correct format for specifying domains without unsupported wildcards. ```json "domains": [ "https://www.adobe.*", "https://www.*" ] ``` -------------------------------- ### cpus() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/os/OS Gets the CPU information of the platform. ```APIDOC ## cpus() ### Description Gets the platform cpu information we are running on (eg. "{'Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz', 2900}") ### Returns `array` - the array of objects containing information about each logical CPU core Currently only model and speed properties are supported. times property is not supported. Access to CPU information, such as model string and frequency, is limited on UWP. "ARM based architecture" or "X86 based architecture" is returned as a 'model' value on UWP. 0 is returned as a 'speed' value on UWP. ``` -------------------------------- ### Basic sp-menu-item Usage Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-spectrum/Spectrum UXP Widgets/User Interface/sp-menu-item Demonstrates how to render a basic menu item, a selected menu item, and a disabled menu item. ```html Chicago New York City St. Louis ``` -------------------------------- ### platform() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/os/OS Gets the platform the application is running on. ```APIDOC ## platform() ### Description Gets the platform we are running on (eg. "win32", "win10", "darwin") ### Returns `string` - the string representing the platform ``` -------------------------------- ### getAttribute Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLImageElement Gets the value of the specified attribute. ```APIDOC ## getAttribute(name) ### Description Gets the value of the specified attribute. ### Parameters #### Path Parameters - **name** (string): Name of the attribute whose value you want to get. ### Returns `string` ``` -------------------------------- ### XMPFile() Constructor Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/XMP/XMP Classes/XMPFile Initializes a new XMPFile object to manage XMP metadata for a given file. ```APIDOC ## XMPFile(filePath, format, openFlags) ### Description Initializes a new XMPFile object. ### Parameters #### Path Parameters - **filePath** (string) - Required - A string containing the file path of a document. - **format** (number) - Required - The file format constant. See File format numeric constants. - **openFlags** (number) - Required - The open options for the file. One of these constants: - XMPConst.OPEN_FOR_READ - Open for read-only access. - XMPConst.OPEN_FOR_UPDATE - Open for reading and writing. - XMPConst.OPEN_ONLY_XMP - Only the XMP is wanted, allows space/time optimizations. - XMPConst.OPEN_STRICTLY - Be strict about locating XMP and reconciling with other forms. - XMPConst.OPEN_USE_SMART_HANDLER - Require the use of a smart handler. No packet scanning is performed. - XMPConst.OPEN_USE_PACKET_SCANNING - Force packet scanning, do not use a smart handler. - XMPConst.OPEN_LIMITED_SCANNING - Only packet-scan files known to need scanning. ``` -------------------------------- ### Fetch Weather Data using fetch API Source: https://developer.adobe.com/indesign/uxp/resources/recipes/network This example demonstrates fetching weather data using the `fetch` API. It includes error handling and logs the forecast. Ensure the `api.weather.gov` domain is permitted in your manifest. ```javascript async function foo() { // Get weather forecast for San Jose try { const response = await fetch(`https://api.weather.gov/gridpoints/MTR/99,82/forecast`); if (!response.ok) { throw new Error(`HTTP error fetching weather station; status: ${response.status}`); } const responseJson = await response.json(); console.log(`Forecast ${responseJson.properties.periods[0].detailedForecast}`); } catch (e) { console.error(e); } } ``` ```json { "requiredPermissions": { "network": { "domains": [ "https://api.weather.gov" ] } } } ``` -------------------------------- ### Adjacent Sibling Combinator Example Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-css/Selectors/Adjacent Sibling combinator This example demonstrates how to use the adjacent sibling combinator (+) to apply styles to an element that immediately follows another. It targets `sp-action-button` elements that are directly preceded by another `sp-action-button`, setting their right margin to 0. ```css sp-action-button + sp-action-button { margin-right: 0; } ``` -------------------------------- ### homedir() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/os/OS Gets the home directory path of the user. ```APIDOC ## homedir() ### Description Gets the home directory path of the user ### Returns `string` - the home directory path of the user ``` -------------------------------- ### Get Entry Metadata Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Persistent File Storage/EntryMetadata Instantiate EntryMetadata by using Entry's getMetadata(). You will need to first invoke the localFileSystem and then fetch an instance of a File or Folder. ```javascript const fs = require('uxp').storage.localFileSystem; const folder = await fs.getPluginFolder(); // Gets an instance of Folder (or Entry) const entryMetaData = await folder.getMetadata(); console.log(entryMetaData.name); ``` -------------------------------- ### load() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLVideoElement Resets the media to its initial state and begins the process of selecting a media source and loading the media for playback. ```APIDOC ## load() ### Description Resets the media to its initial state and begins the process of selecting a media source and loading the media in preparation for playback. The amount of media data that is prefetched is determined by the value of 'preload' attribute. ### Emits - `event:loadedmetadata` - `event:loadeddata` - `event:uxpvideoload - Deprecated: Use loadeddata instead` ### Example ```html ``` ``` -------------------------------- ### release() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/os/OS Gets the release number of the operating system. ```APIDOC ## release() ### Description Gets the release number of the os (eg. "10.0.1.1032") ### Returns `string` - the string representing the release ``` -------------------------------- ### getAttribute(name) Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLSelectElement Gets the value of a specified attribute. ```APIDOC ## getAttribute(name) ### Description Gets the value of a specified attribute. ### Returns - `string` - The value of the attribute. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the attribute whose value you want to get. ``` -------------------------------- ### Callee Plugin: Define Entrypoints for Communication Source: https://developer.adobe.com/indesign/uxp/plugins/tutorials/inter-plugin-comm Register commands and panels in your plugin's entrypoints using `entrypoints.setup`. This allows other plugins to invoke your commands or display your panels. ```javascript const { entrypoints } = require("uxp"); entrypoints.setup({ commands: { simpleCommand: () => doThing(), commandWithInput: (args) => doThing(args) }, panels: { simplePanel: { show({node} = {}) { /* ... */} } } }); function doThing(args) { console.log('Executed a command to do something cool', args && args.data[0]); } ``` -------------------------------- ### getAttributeNode Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLMenuElement Gets the attribute node with the specified name. ```APIDOC ## getAttributeNode(name) ### Description Gets the attribute node with the specified name. ### Returns `*`: The attribute node. ### Parameters #### Path Parameters - **name** (string): The name of the attribute node to retrieve. ``` -------------------------------- ### Accessing Entry Points Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry%20Points/EntryPoints To get an instance of the UXP entry points, use the require statement as shown below. ```APIDOC ## Accessing Entry Points ### Description This section shows how to obtain an instance of the UXP entry points. ### Method `require` ### Endpoint `uxp` ### Code Example ```javascript require("uxp").entrypoints ``` ``` -------------------------------- ### Basic Usage of window.prompt() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML DOM/prompt Demonstrates how to use the prompt() function with a message and a default value. The first argument is the message displayed to the user, and the second is the default text in the input field. ```javascript // Below prompt function has 2 params // "Enter your name: " - Message to display // "Adobe" - Default value that will be present in the Prompt pop-up at launch prompt("Enter your name: ","Adobe"); ``` -------------------------------- ### className Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLElement Gets or sets the class attribute of an element. ```APIDOC ## HTMLElement.className : `string` ### Description Gets or sets the class attribute of an element. ``` -------------------------------- ### tabIndex Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLElement Gets or sets the tab order of an element. ```APIDOC ## HTMLElement.tabIndex : `number` ### Description Gets or sets the tab order of an element. ``` -------------------------------- ### Configure Launch Process Permissions Source: https://developer.adobe.com/indesign/uxp/plugins/concepts/manifest Specify allowed URL schemes and file extensions for launching external processes. ```json { "schemes": ["http", "https"], "extensions": [] } ``` -------------------------------- ### getContent() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/Data Transfers/Clipboard Gets data from the clipboard. This is a non-standard API. ```APIDOC ## getContent() Get data from clipboard. Note: This is a non-standard API. **Returns**: `Promise` **Example**: ```javascript navigator.clipboard.getContent(); ``` ``` -------------------------------- ### User File Selection for Opening Source: https://developer.adobe.com/indesign/uxp/resources/recipes/file-operation Use `getFileForOpening` to present a file picker to the user, allowing them to select a file. You can specify the initial domain and allowed file types. This requires 'request' permission for `localFileSystem`. ```javascript const fsProvider = require('uxp').storage.localFileSystem; async function foo() { // Ask user to select a file. Show their 'Desktop' as the default folder. if (fsProvider.isFileSystemProvider) { const { domains, fileTypes } = require('uxp').storage; try { const file = await fsProvider.getFileForOpening({ initialDomain: domains.userDesktop, types: fileTypes.text }); if (!file) { console.error("Something went wrong."); return; } // read the file content const text = await file.read(); console.log(`File content: ${text}`); } catch (err) { console.error(err); } } } ``` ```json { "requiredPermissions": { "localFileSystem": "request" } } ``` -------------------------------- ### UxpMenuItems() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Entry%20Points/UxpMenuItems Initializes a new instance of the UxpMenuItems class. This class describes the menu of a panel. ```APIDOC ## UxpMenuItems() * * * Class describing the menu of a panel. ``` -------------------------------- ### length Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Key-Value Storage/SecureStorage Gets the number of items stored in the secure storage. ```APIDOC ## length : `number` **Read only** Number of items stored in the secure storage. ``` -------------------------------- ### Listen for WebView Load Start Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML Elements/HTMLWebViewElement Logs the URL when the WebView begins loading a new page. Attach this event listener to the WebView element. ```javascript const webview = document.getElementById("webviewSample"); webview.addEventListener("loadstart", (e) => { console.log(`webview.loadstart ${e.url}`); }); ``` -------------------------------- ### beginPath() Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Global Members/HTML DOM/CanvasRenderingContext2D Starts a new path, allowing for the creation of new shapes independent of previous paths. ```APIDOC ## beginPath() * * * Creates a new path. **See** : CanvasRenderingContext2D - beginPath for more details ``` -------------------------------- ### SecureStorage.length Source: https://developer.adobe.com/indesign/uxp/reference/uxp-api/reference-js/Modules/uxp/Key-Value%20Storage/SecureStorage Gets the number of items stored in the secure storage. ```APIDOC ## length ### Description Read only. Number of items stored in the secure storage. ### Returns * `number` - Number of items stored. ```