Subchapter 2.45
references/dashboard-page/DASHBOARD_API.mdMarkdown22 KBView on GitHub
Host Module ‘@wix/dashboard’ ‘navigate()’ method for navigating between dashboard pages.
Method parameters:
destination: Destinationoptions?: NavigationOptionsDestination object:
pageId (string): ID of the page to navigate torelativeUrl (string): Optional. URL segment appended to the base page URL. Can include path segments, query string, and fragment.Navigation options:
displayMode (“main” | “overlay” | “auto”): How to display the destination page. “auto” (default) loads in current context.history (“push” | “replace”): Optional. Whether to push a new history entry or replace the current one.Example:
import { dashboard } from '@wix/dashboard';
// Navigate to your own app's page with some internal state
dashboard.navigate({pageId: <your-page-id>, relativeUrl: "/an/internal/state?param=value"})
// Navigate to a relative URL within a page (pageId required even for relative paths)
dashboard.navigate({ pageId: '<your-page-id>', relativeUrl: "/some/internal/route" });
// Navigate to the Products List page
dashboard.navigate({ pageId: "0845ada2-467f-4cab-ba40-2f07c812343d" });
// Add a button that navigates to the Products List page (React/TSX)
const GoToProductsButton = () => (
<button onClick={() => dashboard.navigate({ pageId: "0845ada2-467f-4cab-ba40-2f07c812343d" })}>
Go to Products
</button>
);
// Open bookings settings page in an overlay page
dashboard.navigate(
{ pageId: "bcdb42a8-2423-4101-add6-cbebc1951bc2" },
{ displayMode: "overlay" },
);
// Navigate to the home page as a main page from inside an overlay page
dashboard.navigate(
{ pageId: "2e96bad1-df32-47b6-942f-e3ecabd74e57" },
{ displayMode: "main" },
);Common Wix dashboard page IDs useful for navigation. Use with dashboard.navigate({ pageId }).
Selection policy:
ID formats:
Aliases/synonyms (non-exhaustive):
Page IDs:
Host Module ‘@wix/dashboard’ ‘observeState()’ method to receive contextual state and environmental information for dashboard pages, widgets, and modals. The observer runs on initialization and whenever the state is updated.
Method parameters:
observer: Observer — callback receiving (componentParams, environmentState)Observer:
componentParams: P | PageParams — Data sent to your component by its host. For dashboard pages rendered by the platform, this is PageParamsenvironmentState: EnvironmentState — Information about the user’s environmentPage params:
location: PageLocation — Information about the location of the rendered pageEnvironment state:
locale (string): User’s locale (ISO 639-1)pageLocation (PageLocation): Deprecated. Information about the currently rendered page locationPage location:
pageId (string): ID of the current pagepathname (string): Any parts of the current URL path appended to the page’s base URL pathsearch (string, optional): Current URL query stringhash (string, optional): Current URL fragment identifierExample:
import { dashboard } from '@wix/dashboard';
// Receive state passed by your host
dashboard.observeState((componentParams, environmentState) => {
console.log(componentParams, environmentState);
});
// Receive user's locale
dashboard.observeState((_, { locale }) => {
console.log('locale:', locale);
});
// Handle internal page routes
dashboard.observeState((pageParams, environmentState) => {
// This value is logged on initialization and whenever either of the componentParams or environmentState objects change.
const { pathname, search } = pageParams.location;
if (pathname.startsWith("/list")) {
const queryParams = new URLSearchParams(search);
const sortBy = queryParams.get("sortBy");
console.log("Show items list sorted by", sortBy);
} else if (pathname.startsWith("/item")) {
const { itemId } = pathname.match("/item/(?<itemId>.*)").groups;
console.log("Show item with id", itemId);
}
console.log("Unknown route");
});Host Module ‘@wix/dashboard’ ‘showToast()’ displays a toast notification from a dashboard page or widget. Up to 3 toasts show at once; additional toasts may be queued.
Method parameters:
config: ToastConfig — Toast configuration optionsToast config:
message (string): Text to displaytype (“standard” | “success” | “warning” | “error”): Icon and message type. Default: standardpriority (“low” | “normal” | “high”): Display priority. Default: normaltimeout (“none” | “normal”): Auto-dismiss after ~6s if ‘normal’onToastSeen (() => void, optional): Called when the toast is seenonCloseClick (() => void, optional): Called when the toast close button is clickedaction (ToastAction, optional): call-to-action displayed in the toastToast action:
text (string): Text that appears in the call-to-action.uiType (“button” | “link”): The type of call-to-actiononClick (() => void): Callback function to run after the call-to-action is clicked.removeToastOnClick (boolean): Whether to remove the toast after clickReturns:
An object with a method to remove the toast programmatically
{ remove: () => void }
Example:
import { dashboard } from '@wix/dashboard';
// Display a success toast when a product is updated
dashboard.showToast({
message: "Product updated successfully!",
type: "success",
});
// Display an error toast with a 'Learn more' link
dashboard.showToast({
message: "Product update failed.",
timeout: "none",
type: "error",
priority: "low",
action: {
uiType: "link",
text: "Learn more",
removeToastOnClick: true,
onClick: () => {
// Logic to run when the user clicks the 'Learn more' link.
console.log("Learn more clicked!");
},
},
});
// Remove a displayed toast
const { remove } = dashboard.showToast({
message: "Product updated successfully!",
type: "success",
timeout: "none",
});
// Remove the toast.
remove();Host Module ‘@wix/dashboard’ ‘openModal()’ opens a dashboard modal extension on your app’s dashboard page.
Notes:
Method parameters:
modalInfo: ModalInfo — Information about the dashboard modal to openModal info:
modalId (string): ID of the dashboard modal extension to openparams (Record<string, any>, optional): Custom data to pass into the modal (accessible via observeState in the modal)Returns:
Promise that resolves when the modal is closed.
{ modalClosed: Promise<Serializable> }
Example:
import { dashboard } from '@wix/dashboard';
// Open a modal
await dashboard.openModal({
modalId: 'your-modal-id',
});
// Pass extra data when opening a modal
await dashboard.openModal({
modalId: 'your-modal-id',
params: { firstName: "Name" },
});
// Get notified when the modal is closed (continue after it closes)
const { modalClosed } = dashboard.openModal({
modalId: "1d52d058-0392-44fa-bd64-ed09275a6fcc",
});
modalClosed.then((result) => {
if (result) {
console.log("The modal was closed and returned the value:", result);
} else {
console.log("The modal was closed without any data.");
}
});Host Module ‘@wix/dashboard’ ‘navigateBack()’ navigates the user back to the previous dashboard page (equivalent to the browser back button).
Signature: No parameters.
Example:
import { dashboard } from '@wix/dashboard';
// Navigate back to the previous page
dashboard.navigateBack();Host Module ‘@wix/dashboard’ ‘getPageUrl()’ returns the full URL for a dashboard page.
Method parameters:
destination: Destination — URL destination detailsDestination object:
pageId (string): ID of the page to link torelativeUrl (string, optional): URL segment appended to the base page URL. Can include path segments, query string, and fragmentReturns:
The full URL (string) of the dashboard page with the provided relativeUrl appended.
Promise<string>
Example:
import { dashboard } from '@wix/dashboard';
// Get the URL of the dashboard's home page with a query string
const pageUrl = await dashboard.getPageUrl({
pageId: "0845ada2-467f-4cab-ba40-2f07c812343d",
relativeUrl: "?referral=widget",
});Host Module ‘@wix/dashboard’ ‘openMediaManager()’ opens the Wix Media Manager in a modal to let users pick media files. Developer Preview.
Method parameters:
options?: Options — Optional Media Manager optionsOptions:
category (string, optional): Media type to display. Supported: “IMAGE”, “VIDEO”, “MUSIC”, “DOCUMENT”, “VECTOR_ART”, “3D_IMAGE”. Default: all except “3D_IMAGE”multiSelect (boolean, optional): Whether multiple files can be selected. Default: falseReturns:
A promise that resolves to an object with a single key called items. The value of that key is an array of file descriptor objects for the selected media files.
Promise<{ items: Array<FileDescriptor> }>
File descriptor: FileDescriptor is the full schema describing a Media Manager file, including IDs, timestamps, media-type, URLs, status, labels, and a media-specific payload.
Typical fields:
_id (string): File GUID_createdDate (Date): Creation time_updatedDate (Date): Last update timedisplayName (string): File name as shown in Media ManagermediaType (ARCHIVE | AUDIO | DOCUMENT | IMAGE | MODEL3D | OTHER | UNKNOWN | VECTOR | VIDEO): Media file typeurl (string): Static URL of the filethumbnailUrl (string): Thumbnail URLsizeInBytes (string): File size in bytesparentFolderId (string): ID of the file’s parent folder.siteId (string): Site GUID where the media is storedprivate (boolean): Whether file is privateoperationStatus (FAILED | READY | PENDING): Upload/processing statusstate (DELETED | OK): File statehash (string): File hashlabels (string[]): User/AI labelssourceUrl (string): URL where the file was uploaded from.media (object): One of the following variants with specific fields
Example:
import { dashboard } from '@wix/dashboard';
// Open a media manager modal allowing multiple image selection
const chosenMediaItems = await dashboard.openMediaManager({
multiSelect: true,
});
console.log("You have chosen: ", chosenMediaItems.items);Host Module ‘@wix/dashboard’ ‘onBeforeUnload()’ registers a beforeunload handler for a dashboard page, modal, or plugin extension. The callback runs when the user is about to navigate away or the browsing context is unloading. Calling event.preventDefault() pauses navigation and shows a warning dialog about unsaved data.
Signature:
onBeforeUnload(callback: (event: { preventDefault: () => void }) => void): { remove: () => void }
Method parameters:
callback: (event: { preventDefault: () => void }) => void — Called when the beforeunload event firesNotes:
Returns:
An object with a remove() method to unregister the handler
{ remove: () => void }
Example:
import { dashboard } from '@wix/dashboard';
// Prompt for confirmation before unloading unsaved data
const { remove } = dashboard.onBeforeUnload((event) => {
// Check if there's unsaved data on the page
if (unsavedPageData) {
event.preventDefault();
}
});Host Module ‘@wix/dashboard’ ‘addSitePlugin()’ adds a site plugin to one of the slots supported in an app created by Wix. You can target a specific slot or rely on prioritized slots configured in your app’s dashboard.
Notes:
Method parameters:
pluginId: string — ID of your site plugin (from the extension’s settings in your app’s dashboard)options: addSitePluginOptions — Options for adding the site pluginAdd site plugin options:
placement?: PluginPlacement — Details of the slot to add the plugin to. If omitted, the plugin is added to the first available slot based on your installation settings. If all prioritized slots are occupied, it won’t be addedPlugin placement:
appDefinitionId: string — ID of the Wix app hosting the widget and slot (see list of apps created by Wix)widgetId: string — ID of the host widget in which the slot existsslotId: string — ID of the slot in the host widgetReturns:
Resolves on success. See Errors for possible rejection reasons
Promise<void>
Errors:
Example:
import { dashboard } from '@wix/dashboard';
// Add a site plugin to a specific slot
const pluginId = "975bffb7-3c04-42cc-9840-3d48c24e73d5";
const pluginPlacement = {
appDefinitionId: "13d21c63-b5ec-5912-8397-c3a5ddb27a97",
widgetId: "a91a0543-d4bd-4e6b-b315-9410aa27bcde",
slotId: "slot1",
};
dashboard
.addSitePlugin(pluginId, { placement: pluginPlacement })
.then(() => {
console.log("Plugin added successfully");
})
.catch((error) => {
console.error("Error adding plugin:", error);
});
// Add a site plugin without specifying a slot (uses prioritized slots)
const pluginId = "975bffb7-3c04-42cc-9840-3d48c24e73d5";
dashboard
.addSitePlugin(pluginId, {})
.then(() => {
console.log("Plugin added successfully");
})
.catch((error) => {
console.error("Error adding plugin:", error);
});Host Module ‘@wix/dashboard’ ‘setPageTitle()’ sets the title of the current dashboard page in the browser tab. This can only be called from dashboard pages (not plugin extensions). Pass null to reset the title to the default dashboard page title.
Method parameters:
pageTitle: string | null — Title to set (or null to reset)Returns: void
Example:
import { dashboard } from '@wix/dashboard';
// Set a static page title
dashboard.setPageTitle('Orders Overview');
// Reset to default dashboard page title
dashboard.observeState((_, environmentState) => {
// Use a regular expression to capture the productId value.
const queryParams = environmentState.pageLocation.search;
const productIdMatch = queryParams.match(/[?&]productId=([^&]+)/);
let productId;
if (productIdMatch) {
productId = productIdMatch[1];
}
// If a product ID was found, set the page title to the ID.
if (productId) {
dashboard.setPageTitle("Product: " + productId);
// If no product ID was found, reset the page title to default.
} else {
dashboard.setPageTitle(null);
}
});Host Module ‘@wix/dashboard’ ‘onLayerStateChange()’ registers a handler fired when a page, modal, or plugin extension moves between foreground and background. Use it to refresh data when coming to foreground and pause resource-intensive work when backgrounded.
Method parameters:
callback: (state: “foreground” | “background”) => void — Called whenever the layer state changesReturns:
An object with remove() to unregister the handler
{ remove: () => void }
Example:
import { dashboard } from '@wix/dashboard';
// Refresh/pause depending on visibility
const { remove } = dashboard.onLayerStateChange((state) => {
if (state === "foreground") {
refreshData();
}
});
// Remove the onLayerStateChange handler when the beforeUnload event is triggered.
dashboard.onBeforeUnload(() => {
remove();
});