### Example: Get All Pages and Folders and Log Names Source: https://developers.webflow.com/designer/reference/get-folder-name This example demonstrates how to fetch all pages and folders, then iterate through them to log the name and type of each folder. It utilizes the `webflow.getAllPagesAndFolders()` and `folder.getName()` methods. ```typescript // Get all Pages and folders const pagesAndFolders = await webflow.getAllPagesAndFolders() for (let folder of pagesAndFolders) { const folderName = await folder.getName() const type = folder.type console.log(folderName, type) } ``` -------------------------------- ### Example: Get and Log Search Description Source: https://developers.webflow.com/designer/reference/get-search-description This example demonstrates how to get the current page, retrieve its search engine description, and then log it to the console. Ensure the `webflow` object and `Page` type are available in your scope. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Get search engine description and print details const searchEngineDescription = await currentPage.getSearchDescription() console.log(searchEngineDescription) ``` -------------------------------- ### Example: Get Element Styles and Properties Source: https://developers.webflow.com/designer/reference/get-style-properties Demonstrates how to get the selected element, retrieve its styles, and then fetch properties for each style at a specific breakpoint. ```typescript // Get selected element const element = await webflow.getSelectedElement() if (element?.styles) { // Get Element Styles const styles = await element.getStyles() // Initialize an empty object to store all properties const allProperties: { [key: string]: any } = {}; for (let style of styles) { // Use string type for styleName const styleName: string = await style.getName(); const options: StyleOptions = { breakpoint: 'xxl' } const properties = await style.getProperties(options); allProperties[styleName] = properties; } console.log(allProperties); } ``` -------------------------------- ### Example: Set and Get Page Slug Source: https://developers.webflow.com/designer/reference/set-page-slug This example demonstrates how to get the current page, set its slug, and then retrieve the new slug to verify the change. Ensure you have the `webflow` object initialized. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Set page Description await currentPage.setSlug(slug) const newSlug = await currentPage.getSlug() console.log("Slug",newSlug) ``` -------------------------------- ### Example: Applying Theme Styles to Extension UI Source: https://developers.webflow.com/designer/reference/get-theme-styles Demonstrates how to get the current theme, retrieve its styles using `getThemeStyles`, and apply a theme color to the extension's body background. ```javascript const theme = await webflow.getTheme(); const styles = await webflow.getThemeStyles(theme); // Apply the Designer's primary background color to your extension document.body.style.backgroundColor = styles.colors['bg-primary']; ``` -------------------------------- ### Example: Get and Log Search Title Source: https://developers.webflow.com/designer/reference/get-search-title This example demonstrates how to get the current page object and then retrieve its search engine title using `getSearchTitle()`. The title is then logged to the console. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Get Search engine title and print details const searchEngineTitle = currentPage.getSearchTitle() console.log(searchEngineTitle) ``` -------------------------------- ### Example: Setting Parent Folder for Folders Source: https://developers.webflow.com/designer/reference/set-parent-folder This example demonstrates how to retrieve all pages and folders, create a new folder to serve as a parent, and then assign this new parent folder to all existing folders. ```javascript // Get all Pages and folders const pagesAndFolders = await webflow.getAllPagesAndFolders() // Create and name new folder const newFolder = await webflow.createPageFolder() await newFolder.setName("Parent Folder") for (let folder of pagesAndFolders) { await folder.setParent(newFolder) } ``` -------------------------------- ### Example: Get Current Page Description Source: https://developers.webflow.com/designer/reference/get-page-description This example demonstrates how to get the current page object and then retrieve its description. The description is logged to the console. Ensure you have authenticated and obtained a `webflow` instance. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Get page Description const pageDescription = await currentPage.getDescription() console.log(pageDescription) ``` -------------------------------- ### Install Webflow CLI Source: https://developers.webflow.com/designer/reference/webflow-cli Installs the Webflow CLI globally using npm, yarn, or pnpm. Ensure Node.js is installed beforehand. ```bash $ npm install -g @webflow/webflow-cli # or yarn add global @webflow/webflow-cli or pnpm add -g @webflow/webflow-cli ``` -------------------------------- ### Install Webflow CLI Source: https://developers.webflow.com/designer/reference/designer-api/getting-started Install the Webflow CLI globally to manage your Designer Extensions from the command line. ```shell npm i -g @webflow/webflow-cli ``` -------------------------------- ### Example: Setting Form Properties Source: https://developers.webflow.com/designer/reference/form-element/set-form-settings This example demonstrates how to set various properties for a selected form element using the `setSettings` method. It includes checks to ensure the selected element is a form. ```javascript const selectedElement = await webflow.getSelectedElement() if (selectedElement?.type === 'FormForm' || selectedElement?.type === 'FormWrapper'){ await selectedElement.setSettings({ state: "success", name: "My Form", redirect: "https://www.my-site.com/thank-you", action: "https://{dc}.api.mailchimp.com/3.0/lists/{list_id}/members", method: "post" }) } else { console.log("Selected Element is not a Form Element") } ``` -------------------------------- ### Example: Set Variable Mode on Selected Element's Style Source: https://developers.webflow.com/designer/reference/set-variable-mode-style This example demonstrates how to get the selected element, retrieve its primary style, fetch a default variable collection and mode, and then apply that mode to the style. It logs a success message upon completion. ```typescript // Get Selected Element const selectedElement = await webflow.getSelectedElement() if (selectedElement?.styles) { // Get Styles const styles = await selectedElement.getStyles() const primaryStyle = styles[0] // Get the primary style // Get Variable Collection const variableCollection = await webflow.getDefaultVariableCollection() const variableModes = await variableCollection?.getAllVariableModes() const variableMode = variableModes[0] // Set Variable Mode if (primaryStyle && variableCollection) { await primaryStyle.setVariableMode(variableCollection, variableMode) console.log('Variable mode set successfully') } } ``` -------------------------------- ### LaunchContext Object Example Source: https://developers.webflow.com/designer/reference/get-launch-context An example of a LaunchContext object, specifically for an 'AppIntent' launch type with form creation intent. ```json { type: 'AppIntent', value: { form: 'create' } } ``` -------------------------------- ### Subscribe to Current App Mode Event (Before) Source: https://developers.webflow.com/designer/reference/user-changes-mode This example shows the older method of subscribing to mode changes, which required an additional call to `webflow.canForAppMode()` to get user capabilities. ```typescript // Before: extra canForAppMode() call required const unsubscribe = webflow.subscribe('currentappmode', async () => { const capabilities = await webflow.canForAppMode( Object.values(webflow.appModes), ); console.log(capabilities); }); ``` -------------------------------- ### Example: Accessing and Logging Text Prop Element Children Source: https://developers.webflow.com/designer/reference/component-element/getTextPropElement Demonstrates how to find a component instance, retrieve its text properties, get the corresponding prop element using `getTextPropElement`, and log the number of its child elements. Ensure `webflow` is initialized and accessible. ```typescript const elements = await webflow.getAllElements(); const componentInstance = elements.find(el => el.type === 'ComponentInstance'); if (componentInstance?.type === 'ComponentInstance') { const props = await componentInstance.getProps(); const textProp = props.find(p => p.type === 'textContent'); if (textProp) { const propEl = await componentInstance.getTextPropElement(textProp.id); if (propEl) { const name = await propEl.getDisplayName(); const children = await propEl.getChildren(); console.log(`Prop element "${name}" has ${children.length} child(ren)`); } } } ``` -------------------------------- ### Webflow Notify Function Examples Source: https://developers.webflow.com/designer/reference/notify-user Provides examples of how to use the webflow.notify function to display different types of notifications: Info, Error, and Success. ```javascript webflow.notify({ type: 'Info', message: 'Great work!' }); // General notification ``` ```javascript webflow.notify({ type: 'Error', message: 'Something went wrong, try again!' }); // Error notification ``` ```javascript webflow.notify({ type: 'Success', message: 'Successfully did something!' }); // Success notification ``` -------------------------------- ### React Example: Handling App Connection on Load Source: https://developers.webflow.com/designer/reference/get-current-app-connection This React example demonstrates how to use `webflow.getCurrentAppConnection()` within `useEffect` to conditionally redirect the user based on the App Connection identifier. Ensure `webflow` is available in your scope. ```typescript React.useEffect(() => { async function onLoad() { /* Await the current App Connection information. If the App was launched via a specific App Connection button, this will return a string with the connection name; otherwise, it returns null. */ const appConnection = await webflow.getCurrentAppConnection(); /* Check if the App Connection matches 'myAwesomeAppManageFormElement'. If it does, the App will redirect to the '/editForms' page to provide a tailored experience based on the App Connection. */ if (appConnection === "myAwesomeAppManageFormElement") { redirectToPage("/editForms"); } } // Call the onLoad function when the component mounts. onLoad(); }, []); ``` -------------------------------- ### Example: Logging Variant Changes and Unsubscribing Source: https://developers.webflow.com/designer/reference/user-changes-variant This example demonstrates how to subscribe to the 'selectedvariant' event, log the variant's name and ID to the console, and then unsubscribe after a specified delay. ```typescript const unsubscribeVariant = webflow.subscribe('selectedvariant', (variant) => { console.log('Variant changed:', variant.name); console.log('Variant ID:', variant.id); }); // Stop listening after 10 seconds setTimeout(unsubscribe, 10000); ``` -------------------------------- ### Initialize Project with React Template Source: https://developers.webflow.com/designer/reference/webflow-cli Example of initializing a new project named 'my-react-extension' using the 'react' template. ```bash webflow extension init my-react-extension react ``` -------------------------------- ### Example: Get Current Page Name Source: https://developers.webflow.com/designer/reference/get-page-name This example demonstrates how to get the current page object and then retrieve its name using `page.getName()`. The page name is then logged to the console. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Get page name const pageName = await currentPage.getName() console.log(pageName) ``` -------------------------------- ### List Available Templates Source: https://developers.webflow.com/designer/reference/webflow-cli Lists all available templates that can be used with the `init` command. ```bash webflow extension list ``` -------------------------------- ### Example: Get Variable Name Source: https://developers.webflow.com/designer/reference/get-variable-name This example demonstrates how to get the name of the first variable from a collection. It first retrieves the default variable collection, then all variables, and finally the name of the first variable. ```typescript // Get Collection const collection = await webflow.getDefaultVariableCollection() // Get All Variables const variables = await collection.getAllVariables() // Get Value of first Variable const variable = variables[0] const value = await variable.getName() ``` -------------------------------- ### Example: Setting Multiple Props on a Component Instance Source: https://developers.webflow.com/designer/reference/component-element/setProps Demonstrates how to retrieve all elements, find a component instance, and then use `setProps` to apply static overrides, bind to other props or CMS data, and reset a prop to its default. ```javascript // Get all elements on the page const elements = await webflow.getAllElements() const instanceEl = elements.find(el => el.type === 'ComponentInstance') if (instanceEl?.type === 'ComponentInstance') { const updated = await instanceEl.setProps([ // Set a static value override { propId: 'prop_1', value: 'New Heading' }, // Bind to a parent component prop { propId: 'prop_2', value: { sourceType: 'prop', propId: 'parent_prop_5' } }, // Bind to a CMS field { propId: 'prop_3', value: { sourceType: 'cms', collectionId: 'col_abc123', fieldId: 'field_author' } }, // Disconnect binding and reset to component default { propId: 'prop_4', value: null }, ]) console.log(updated) } else { console.log('No component instance found') } ``` -------------------------------- ### Example: Get Variable Mode for Selected Element Source: https://developers.webflow.com/designer/reference/get-variable-mode-style Demonstrates how to get the variable mode name for the primary style of a selected element. Ensure `variableCollection` is defined. ```javascript // Get Selected Element const selectedElement = await webflow.getSelectedElement() if (selectedElement?.styles) { // Get Styles const styles = await selectedElement.getStyles() const primaryStyle = styles[0] // Get the primary style // Get Variable Mode if (primaryStyle && variableCollection) { const variableMode = await primaryStyle.getVariableMode(variableCollection) const variableModeName = await variableMode?.getName() console.log(variableModeName) } } ``` -------------------------------- ### Example: Create a New Variant Source: https://developers.webflow.com/designer/reference/create-variant Demonstrates how to create a new component variant and select it immediately. Also shows how name conflicts are handled by auto-incrementing. ```javascript const component = await webflow.getCurrentComponent() if (component) { // Create a variant and select it immediately const variant = await component.createVariant({ name: 'Secondary Hero', isSelected: true, }) console.log(variant) // { id: 'variant-123', name: 'Secondary Hero', isSelected: true } // Name conflicts auto-increment const variant2 = await component.createVariant({ name: 'Secondary Hero' }) console.log(variant2.name) // 'Secondary Hero 2' } // Name auto-increments on conflict const variant2 = await component.createVariant({ name: 'Secondary Hero' }); console.log(variant2.name); // 'Secondary Hero 2' ``` -------------------------------- ### Example Usage of getLaunchContext Source: https://developers.webflow.com/designer/reference/get-launch-context An asynchronous function demonstrating how to call webflow.getLaunchContext() and display a success notification based on the launch type. ```javascript async function getLaunchContext() { const context = await webflow.getLaunchContext(); if (context) { await webflow.notify({ type: "Success", message: `App was launched through ${context.type}` }); } } ``` -------------------------------- ### Initialize New Designer Extension Project Source: https://developers.webflow.com/designer/reference/webflow-cli Initializes a new Designer Extension project with a specified name and an optional template. ```bash webflow extension init [template] ``` -------------------------------- ### Example Usage of slot.getChildren() in Webflow Designer Source: https://developers.webflow.com/designer/reference/slot-instance-element/getChildren This example demonstrates how to get all component instances on a page, find a specific component instance, retrieve its slots, and then print the number of children in each slot using slot.getChildren(). ```typescript // Get a component instance on the page const elements = await webflow.getAllElements(); const componentInstance = elements.find(el => el.type === 'ComponentInstance'); if (componentInstance?.type === 'ComponentInstance') { // Get the slots on the instance const slots = await componentInstance.getSlots(); // Print the children of each slot for (const slot of slots) { const name = await slot.getDisplayName(); const children = await slot.getChildren(); console.log(`Slot "${name}" has ${children.length} children`); } } else { console.log('No component instance found'); } ``` -------------------------------- ### Example: Check if Current Page is Excluded from Search Source: https://developers.webflow.com/designer/reference/check-if-page-is-excluded-from-search Use this example to get the current page and then check if it's excluded from Webflow's internal site search. It logs a message to the console based on the result. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() // Check if page is excluded from webflow's internal site search const isExcluded = await currentPage?.isExcludedFromSearch() if (isExcluded){ console.log("Current page is excluded from Webflow's internal site search") } else { "Current page is included in included in Webflow's internal site search" } ``` -------------------------------- ### Example Usage of getVariableModes Source: https://developers.webflow.com/designer/reference/get-variable-modes-style Demonstrates how to get the selected element, its styles, and then retrieve the variable modes for the primary style. ```javascript // Get selected element const selectedElement = await webflow.getSelectedElement() if (selectedElement?.styles) { // Get styles const styles = await selectedElement.getStyles() if (styles) { // Get the primary style const primaryStyle = styles[0] // Get the variable modes const variableModes = await primaryStyle?.getVariableModes() console.log(variableModes) } } ``` -------------------------------- ### Get Current Theme Source: https://developers.webflow.com/designer/reference/get-theme Retrieve the current Designer theme and log it. This example also demonstrates conditionally applying a CSS class based on the theme. ```typescript const theme = await webflow.getTheme(); console.log('Current theme:', theme); if (theme === 'light') { document.body.classList.add('light-mode'); } ``` -------------------------------- ### Create a link Prop Source: https://developers.webflow.com/designer/reference/managing-components/create-prop This example shows how to create a link prop, which can be configured with a URL and an option to open in a new tab. ```typescript const component = await webflow.getCurrentComponent() if (component) { const ctaProp = await component.createProp({ type: 'link', name: 'CTA Link', group: 'Content', defaultValue: { mode: 'url', to: 'https://example.com/signup', openInNewTab: true, }, }) } ``` -------------------------------- ### Get Specific and Base Variants Source: https://developers.webflow.com/designer/reference/get-variant Demonstrates how to retrieve a specific component variant by its ID and how to fetch the base variant using 'base'. Includes example output for both. ```typescript const component = await webflow.getCurrentComponent() if (component) { // Get a specific variant by ID const variant = await component.getVariant('variant-123') console.log(variant) /* { id: 'variant-123', name: 'Secondary Hero', isSelected: true, } */ // Get the base variant const base = await component.getVariant('base') console.log(base) /* { id: 'base', name: 'Primary', isSelected: false, } */ } ``` -------------------------------- ### Create Navigation Menu Source: https://developers.webflow.com/designer/reference/bulk-add-elements This example demonstrates how to create a complete navigation menu with custom styles and multiple items using the element builder. It first defines styles for the container and items, then constructs the menu structure, and finally appends it to the selected parent element. ```javascript async function createNavMenu() { // Start by creating some styles that will be applied to the nav container. const navStyle = await webflow.createStyle('navContainer'); await navStyle.setProperties({ 'display': 'flex', 'row-gap': '20px', 'padding-left': '15px', 'padding-right': '15px', 'padding-top': '15px', 'padding-bottom': '15px', 'background-color': '#f5f5f5', 'border-radius': '8px' }); const navItemStyle = await webflow.createStyle('navItem'); await navItemStyle.setProperties({ 'color': '#333', 'text-decoration': 'none', 'padding-left': '12px', 'padding-right': '12px', 'padding-top': '8px', 'padding-bottom': '8px', 'border-radius': '4px', 'font-weight': '500' }); // Get the selected element as the container const selectedElement = await webflow.getSelectedElement(); // Create a nav container const navMenu = webflow.elementBuilder(webflow.elementPresets.DOM); navMenu.setTag('nav'); navMenu.setStyles([navStyle]); // Menu items to add const menuItems = ['Home', 'About', 'Services', 'Portfolio', 'Contact']; // Create all menu items at once and store references for later const menuItemRefs = []; menuItems.forEach(itemText => { const item = navMenu.append(webflow.elementPresets.DOM); item.setTag('a'); item.setAttribute('href', '#'); item.setTextContent(itemText); item.setStyles([navItemStyle]); // Store reference to set text later menuItemRefs.push(item); }); // Add the entire menu to the canvas in one operation if (selectedElement?.children) { await selectedElement.append(navMenu); console.log('Navigation structure with 5 items created in one operation'); } } ``` -------------------------------- ### Example Usage of setSearchTitle Source: https://developers.webflow.com/designer/reference/set-search-title Demonstrates how to get the current page, set its search engine title, and then retrieve the updated title. This snippet requires the `webflow` object to be available. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Set search engine title and print details await currentPage.setSearchTitle("My New Title") const searchTitle = await currentPage.getSearchTitle() console.log(searchTitle) ``` -------------------------------- ### Example: Fetching Components Source: https://developers.webflow.com/designer/reference/get-component-by-name Demonstrates how to fetch a component using its name only, and how to fetch a component when both its group and name are specified. The component's ID is logged to the console. ```typescript // Fetch a component by name only const heroSection = await webflow.getComponentByName('Hero'); console.log(heroSection.id); // Fetch a component scoped to a group const marketingHero = await webflow.getComponentByName('Marketing', 'Hero'); console.log(marketingHero.id); ``` -------------------------------- ### Run Designer Extension Locally Source: https://developers.webflow.com/designer/reference/designer-api/getting-started Start the development server for your Designer Extension. This command serves your extension on port 1337 and enables live updates during development. ```shell npm run dev ``` -------------------------------- ### Example: Remove All Variable Modes from a Style Source: https://developers.webflow.com/designer/reference/remove-all-variable-modes Demonstrates how to get the selected element, its styles, and then remove all variable modes from the primary style. Ensure the element has styles before proceeding. ```typescript // Get Selected Element const selectedElement = await webflow.getSelectedElement() if (selectedElement?.styles) { // Get Styles const styles = await selectedElement.getStyles() const primaryStyle = styles[0] // Get the primary style // Get Variable Modes const remove = await primaryStyle?.removeAllVariableModes() } ``` -------------------------------- ### Get Collection Name Example Source: https://developers.webflow.com/designer/reference/get-collection-name Use this snippet to retrieve the name of a default variable collection. Ensure you have initialized the webflow object and obtained the default variable collection first. ```typescript const defaultVariableCollection = await webflow.getDefaultVariableCollection(); const collectionName = await defaultVariableCollection?.getName() console.log(collectionName) ``` -------------------------------- ### Example: Setting Attributes on an Element Source: https://developers.webflow.com/designer/reference/attributes/setAttribute Demonstrates how to use element.setAttribute() to set attributes by name and by index. Ensure the element and its attributes are available before calling. ```javascript const element = await webflow.getSelectedElement() if (element && element.attributes) { // Set by name (string values only) await element.setAttribute('data-label', 'primary') // Set by index (supports bindings) await element.setAttribute(0, { name: 'data-label', value: 'primary' }) } ``` -------------------------------- ### Get style type using `style.getType()` Source: https://developers.webflow.com/designer/reference/style/get-type Retrieve a style's type. This method is synchronous and returns a `StyleType` string. It can be used to filter styles, for example, to find all global classes. ```typescript const styles = await webflow.getAllStyles(); const globalClasses = styles.filter((style) => style.getType() === "global"); ``` -------------------------------- ### Handle App Intent and App Connection Launches Source: https://developers.webflow.com/designer/reference/app-intents-and-connections Use this code to initialize your app and determine the launch context (App Intent or App Connection) to navigate the user to the correct section of your app. It fetches the launch context and selected element upon component mount. ```typescript import React from 'react'; import { useNavigate } from 'react-router-dom'; import { webflow } from '@webflow/webflow-sdk'; // Initialize state to store the launch context and selected element const [launchContext, setLaunchContext] = React.useState(null); const [selectedElement, setSelectedElement] = React.useState(null); const navigate = useNavigate(); React.useEffect(() => { // Define async function to fetch launch context and selected element async function onLoad() { // Get context from Webflow Designer when App is launched const context = await webflow.getLaunchContext(); setLaunchContext(context); // Update state with the received context // Get and set the selected element const element = await webflow.getSelectedElement(); setSelectedElement(element); // Handle different launch contexts if (context?.type === 'AppIntent') { // Handle App Intent launches if (context.value?.image === 'manage') { await element.setAppConnection('manageImageElement'); navigate('/image-manager'); } else if (context.value?.form === 'manage') { await element.setAppConnection('manageFormElement'); navigate('/form-manager'); } else { navigate('/'); } } else if (context?.type === 'AppConnection') { // Handle App Connection launches switch (context.value) { case 'manageImageElement': navigate('/image-manager'); break; case 'manageFormElement': navigate('/form-manager'); break; default: navigate('/'); } } else { // Handle direct launches (not from Intent or Connection) navigate('/'); } } // Call onLoad immediately when component mounts onLoad(); }, []); // Empty dependency array means this effect runs once on mount ``` -------------------------------- ### Get Form Name using getName() Source: https://developers.webflow.com/designer/reference/form-element/get-form-name Retrieves the name of the form element. Use this when you need to identify a specific form by its name, for example, to conditionally apply logic or display information. ```typescript const selectedElement = await webflow.getSelectedElement() if (selectedElement?.type === 'FormForm' || selectedElement?.type === 'FormWrapper'){ const name = await selectedElement.getName() console.log(name) } else { console.log("Selected Element is not a Form Element") } ``` -------------------------------- ### Example: Selecting Component Variants in Webflow Designer Source: https://developers.webflow.com/designer/reference/set-selected-variant Demonstrates how to select a component and then set its variant using different methods: by name, by ID (object), and by ID (string shorthand). Includes selecting the base variant. ```javascript // Select component const heroComponent = await webflow.getComponentByName('Hero') // Select variant by name await heroComponent.setSelectedVariant({ name: 'Secondary Hero' }); // Select variant by ID (object form) await heroComponent.setSelectedVariant({ id: 'secondary-hero' }); // Select variant by ID (string shorthand) await heroComponent.setSelectedVariant('secondary-hero'); // Select the base variant await heroComponent.setSelectedVariant({ id: 'base' }); await heroComponent.setSelectedVariant('base'); ``` -------------------------------- ### Create Component Instance Source: https://developers.webflow.com/designer/reference/create-component-instance This snippet demonstrates how to get the selected element, retrieve all available components, and then add an instance of the first component before the selected element on the canvas. ```javascript const selectedElement = await webflow.getSelectedElement() const allComponents = await webflow.getAllComponents() const firstComponent = allComponents[0] await selectedElement?.before(firstComponent) ``` -------------------------------- ### Get and Log User ID Token Source: https://developers.webflow.com/designer/reference/get-user-id-token This example demonstrates how to asynchronously retrieve the user's ID token using webflow.getIdToken() and then log it to the console. The ID token is valid for 15 minutes. ```javascript // Get ID Token const idToken = await webflow.getIdToken() // Print ID Token console.log(idToken) ``` -------------------------------- ### Get Folder Slug Example Source: https://developers.webflow.com/designer/reference/get-folder-slug Use this snippet to iterate through all pages and folders retrieved from the Webflow API and log the slug for each folder. Ensure you have initialized the `webflow` client and called `getAllPagesAndFolders()` beforehand. ```typescript const pagesAndFolders = await webflow.getAllPagesAndFolders() for (let folder of pagesAndFolders) { const folderSlug = await folder.getSlug() console.log("Slug", folderSlug) } ``` -------------------------------- ### Create and Name New Folder Source: https://developers.webflow.com/designer/reference/create-folder Demonstrates how to create a new folder and then set its name using the `webflow.createPageFolder()` method and the `setName()` method on the returned folder object. ```javascript // Create and name new folder const newFolder = await webflow.createPageFolder() await newFolder.setName(name) // Print details const folderName = await newFolder.getName() console.log(folderName) ``` -------------------------------- ### Get Resolved Settings for an Element Source: https://developers.webflow.com/designer/reference/element-settings/getResolvedSettings Retrieves the resolved values for all settings on a selected element. This example logs the resolved settings to the console. Note that CMS field bindings are returned as references, not resolved values. ```javascript const element = await webflow.getSelectedElement() if (element) { const settings = await element.getResolvedSettings() console.log(settings) /* { tag: 'h2', domId: 'my-heading', // prop binding resolved to its current value altText: 'A sunset photo', } */ } ``` -------------------------------- ### Example: Check if page uses Title as Open Graph title Source: https://developers.webflow.com/designer/reference/uses-title-as-open-graph-title Demonstrates how to get the current page and check if it uses its title as the Open Graph title using the `usesTitleAsOpenGraphTitle` method. It logs the result to the console. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Check if page is using the Title as the Open Graph title const isOpenGraphTitle = await currentPage.usesTitleAsOpenGraphTitle() // Print results if (isOpenGraphTitle) { console.log('Page uses Title as Open Graph Title') } else { console.log('This page has a custom Open Graph Title') } ``` -------------------------------- ### Prepend Element With Settings Source: https://developers.webflow.com/designer/reference/prepend This example shows how to prepend an image element with specific settings like `assetId` and `altText`, and a 'section' element with a custom `domId`. Settings are applied at the time of creation. ```javascript // Get Selected Element const el = await webflow.getSelectedElement(); // Check if element supports child elements if (el?.children) { // Prepend an image element with initial settings applied at creation time const newImg = await el.prepend(webflow.elementPresets.Image, { assetId: 'xxxx', altText: 'A sunset photo', }) // Prepend an element using a string tag, with a custom DOM ID const newSection = await el.prepend('section', { domId: 'my-section' }) console.log(JSON.stringify(newImg)) } ``` -------------------------------- ### Bundle Webflow Extension for Production Source: https://developers.webflow.com/designer/reference/app-structure Command to bundle the Webflow extension into a zip file for publishing. This is an alternative to 'npm run build' if the project was not initialized with the CLI. ```bash webflow extension bundle ``` -------------------------------- ### Set Variable Modes on Selected Element's Style Source: https://developers.webflow.com/designer/reference/set-variable-modes-style This example demonstrates how to get the variable modes from the style of the currently selected element and then apply them to a chosen style. It requires selecting an element and accessing its styles. ```typescript // This example gets variable modes from the style of the currently selected element, then sets them a chosen style // Get Selected Element const selectedElement = await webflow.getSelectedElement() if (selectedElement?.styles) { // Get Styles const styles = await selectedElement.getStyles() const primaryStyle = styles?.[0] // Get the primary style const variableModes = await primaryStyle?.getVariableModes() // Set Variable Modes on Selected Style if (variableModes) { await selectedStyle?.setVariableModes(variableModes) } } ``` -------------------------------- ### Initialize Webflow Extension Project Source: https://developers.webflow.com/designer/reference/app-structure Command to initialize a new Webflow Designer Extension project. It's recommended to use this command to set up the project structure and dependencies. ```bash webflow extension init ``` -------------------------------- ### Set and Reset Element Display Name Source: https://developers.webflow.com/designer/reference/set-display-name This example demonstrates how to get the selected element, set a custom display name, and then reset it to its default name. It also shows how to iterate through child elements and set their display names. ```javascript // Get the selected element const element = await webflow.getSelectedElement(); if (element?.displayName) { // Set a custom display name await element.setDisplayName('Hero Wrapper'); // Reset to the default name await element.setDisplayName(''); } // Bulk rename child elements for clarity const root = await webflow.getRootElement(); if (root) { const children = await root.getChildren(); for (let i = 0; i < children.length; i++) { if (children[i].displayName) { await children[i].setDisplayName(`Section ${i + 1}`); } } } ``` -------------------------------- ### Get Resolved Attributes of Selected Element Source: https://developers.webflow.com/designer/reference/attributes/getResolvedAttributes Retrieves all attributes of the currently selected element, with bindings resolved to their string values. This example logs the resolved attributes to the console. Ensure the element exists and has attributes before calling the method. ```javascript const element = await webflow.getSelectedElement() if (element && element.attributes) { const attributes = await element.getResolvedAttributes() console.log(attributes) // [{ name: 'data-label', value: 'primary' }] } ``` -------------------------------- ### Adapt UI Based on Mode Source: https://developers.webflow.com/designer/reference/get-current-mode Read the current mode when your extension launches and render the matching UI. This example demonstrates how to use a switch statement to conditionally render different tools or states based on the Designer's mode. ```javascript async function renderForCurrentMode() { const mode = await webflow.getCurrentMode(); switch (mode) { case "design": await renderDesignTools(); break; case "build": await renderContentEditingTools(); break; case "preview": case "edit": case "comment": await renderReadOnlyState(); break; default: await webflow.notify({ type: "Info", message: "The Designer is not in a public mode.", }); } } await renderForCurrentMode(); ``` -------------------------------- ### Get Variable Binding Value Source: https://developers.webflow.com/designer/reference/get-variable-binding Use `variable.getBinding()` to retrieve the binding value of a variable. This is useful when you need to reference a variable's binding, for example, when creating a new variable with a custom value derived from another variable's binding. ```javascript // Create a variable const webflowBlue = await collection?.createColorVariable( "blue-500", "#146EF5" ); // Get the binding value for a variable const binding = await webflowBlue.getBinding(); // binding = "var(--blue-500)" // Use the binding value to create a variable with a custom value const webflowBlue400 = await collection.createColorVariable("blue-400", { type: "custom", value: `color-mix(in srgb, ${binding}, white 50%)`, }); ``` -------------------------------- ### Get DOM Element Tag Source: https://developers.webflow.com/designer/reference/dom-element/getTag Retrieves the HTML tag of a DOM element. This example first finds all elements, then filters for a DOM element, and finally calls getTag() on it. It logs the tag to the console or a 'No DOM Element Found' message. ```javascript const elements = await webflow.getAllElements() const DOMElement = elements.find(element => element.type === "DOM") if (DOMElement?.type === "DOM") { // Get DOM Element's Tag const tag = await DOMElement.getTag() console.log(tag) } else { console.log('No DOM Element Found') } ``` -------------------------------- ### Prepend Component Instance to Slot Source: https://developers.webflow.com/designer/reference/slot-instance-element/prepend This example demonstrates how to find a component instance, access its first slot, retrieve a specific component by name, and then prepend that component to the slot. Ensure you have the necessary Webflow API methods available and that the component exists in the site's library. ```typescript const elements = await webflow.getAllElements(); const componentInstance = elements.find(el => el.type === 'ComponentInstance'); if (componentInstance?.type === 'ComponentInstance') { const slots = await componentInstance.getSlots(); const firstSlot = slots[0]; if (firstSlot) { const components = await webflow.getAllComponents(); const cardComponent = await webflow.getComponentByName('Card'); if (cardComponent) { await firstSlot.prepend(cardComponent); } } } else { console.log('No component instance found'); } ``` -------------------------------- ### Example: Setting a Page Description in TypeScript Source: https://developers.webflow.com/designer/reference/set-page-description Demonstrates how to retrieve the current page and then set its description using the `setDescription` method. This is useful for programmatically updating page metadata. ```typescript // Get Current Page const currentPage = await webflow.getCurrentPage() as Page // Set page Description await currentPage.setDescription("My New Description") console.log(pageDescription) ``` -------------------------------- ### element.getResolvedAttributes() Source: https://developers.webflow.com/designer/reference/attributes/getResolvedAttributes Gets all attributes on an element as an array of name/value pairs, with any bindings resolved to their current string values. This method returns the final output values for each attribute. Bindings are resolved to their actual values rather than returned as binding references. For example, an attribute value bound to a component prop returns the current value of that prop rather than a binding reference object. To get the raw attribute entries including binding references, use `element.getAttributes()`. ```APIDOC ## `element.getResolvedAttributes()` ### Description Gets all attributes on an element as an array of name/value pairs, with any bindings resolved to their current string values. ### Method `getResolvedAttributes(): Promise>` ### Returns **Promise >** A Promise that resolves to an array of attribute objects with all binding references resolved to their current string values. ### Example ```javascript const element = await webflow.getSelectedElement() if (element && element.attributes) { const attributes = await element.getResolvedAttributes() console.log(attributes) // Expected output: [{ name: 'data-label', value: 'primary' }] } ``` ### Designer Ability **canAccessCanvas** ``` -------------------------------- ### Example: Convert Element to Component Source: https://developers.webflow.com/designer/reference/create-component-definition Shows how to convert the currently selected element into a 'Hero Section' component within the 'Sections' group, replacing the original element. ```javascript // Convert an existing element into a component and replace the element with the component const selectedElement = await webflow.getSelectedElement() if (selectedElement) { const heroComponent = await webflow.registerComponent( { name: 'Hero Section', group: 'Sections', description: 'Main hero with heading and CTA' }, selectedElement ) } ``` -------------------------------- ### Get CSS Name of a Webflow Variable Source: https://developers.webflow.com/designer/reference/get-variable-css-name Use `variable.getCSSName()` to retrieve the custom property name of a variable. This is useful when you need to reference the variable's name directly, for example, to override its value in a custom stylesheet. The method returns a Promise that resolves to the CSS name string. ```typescript const webflowBlue = await collection?.createColorVariable( "blue-500", "#146EF5" ); const cssName = await webflowBlue.getCSSName(); // cssName = "--blue-500" ``` -------------------------------- ### Example: Duplicate a Component Source: https://developers.webflow.com/designer/reference/create-component-definition Illustrates duplicating an existing component. It retrieves all components, takes the first one as the source, and creates a copy named 'Card Copy'. ```javascript // Duplicate a component const [original] = await webflow.getAllComponents() const copy = await webflow.registerComponent({ name: 'Card Copy' }, original) ```