### Complete HTML Example for PDF Export Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_export.html This example demonstrates how to export a PDF of all published worksheets in a workbook using `Viz.exportPDFAsync()`. It includes setting up the event listener for the first interactive event and handling the button click to trigger the export with specified options. ```html PDF Export
``` -------------------------------- ### Example: Using useTableauVizFirstInteractiveCallback for Viz Interaction Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_react.html This example demonstrates using the useTableauVizFirstInteractiveCallback hook to log a success message and the active sheet name when the viz loads and becomes interactive. It includes necessary imports and memoization with an empty dependency array. ```javascript import React from 'react'; import { Api, TableauViz, useTableauVizFirstInteractiveCallback } from '@tableau/embedding-api-react'; export default function MyViz() { const onFirstInteractive = useTableauVizFirstInteractiveCallback((event) => { const { target: viz } = event; console.log('---onFirstInteractive---'); console.log('Viz Embedding Successful!'); console.log(`Name of active sheet: ${viz.workbook.activeSheet.name}`); }, []); return ( ); } ``` -------------------------------- ### Install Tableau Embedding API v3 Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_get.html Installs the latest version of the Tableau Embedding API v3 library into the current directory's node_modules folder. ```bash npm i @tableau/embedding-api ``` -------------------------------- ### Full Example: Embedding Viz and Getting Sheet Info Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_react.html This example demonstrates embedding a TableauViz component in a React app and using the useTableauVizRef hook to access the viz's active sheet information upon a button click. ```javascript import React from 'react'; import { Api, TableauViz, useTableauVizRef } from '@tableau/embedding-api-react' export default function MyViz() { const vizRef = useTableauVizRef(); const getActiveSheetInfo = () => { const viz = vizRef.current; if (!viz) { throw new Error("TableauViz ref not assigned yet."); } const activeSheet = viz.workbook.activeSheet; const sheetName = activeSheet.name; const sheetType = activeSheet.sheetType; alert(`Active Sheet: ${sheetName}\nSheet Type: ${sheetType}`); }; return ( <>

Click the Get Sheet Info button to get the name and type of the active sheet.

); } ``` -------------------------------- ### Example using getFiltersAsync and getDomainAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_pulse_filter.html This code example demonstrates how to retrieve all filters using `tableauPulse.getFiltersAsync()` and then extract field values from the domains of categorical filters using `getDomainAsync()`. It covers retrieving all available field values, relevant field values, and field values that match a specific string, utilizing pagination for large datasets. ```APIDOC ## Example using `getFiltersAsync` and `getDomainAsync` The following code example shows how you might extract the field values from the domains of two categorical filters. The code shows an event handler for a ‘`getFilters`’ button click event. It performs the following steps: 1. Retrieves all filters using `tableauPulse.getFiltersAsync()`. 2. For the first filter, uses `filters[0].getDomainAsync()` and: * Retrieves all the available field values and logs the results. * Retrieves only the relevant field values and logs the results. 3. For the second filter, uses `filters[1].getDomainAsync()` and: * Retrieves only the relevant domain values and logs the results. * Retrieves only the relevant field values that include the string ‘`foo`’ and logs the results. The event handler uses pagination to retrieve all domain values in chunks (pages) until all values are retrieved. The initial page size is 100 and the page size adjusted based upon the total values available. ```javascript // assumes a Pulse object has been created // assumes there is a 'button' with the id 'getFilters' getFilters.onclick = async () => { const filters = await tableauPulse.getFiltersAsync(); console.log('filters', filters); let domain = []; let page = undefined; let pageSize = 100; do { page = await filters[0].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Database); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (database)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[0].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (relevant)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[1].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (relevant)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[1].getDomainAsync('foo', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (foo)', domain); }; ``` ``` -------------------------------- ### Handling UrlActionEvent Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/UrlActionEvent.html Example of how to listen for and handle the UrlActionEvent in JavaScript. ```APIDOC ```javascript function urlActionEventHandler(event) { console.log('URL: ' + event.detail.url); console.log('Target: ' + event.detail.target); } let viz = document.getElementById('tableauViz'); viz.addEventListener(TableauEventType.UrlAction, urlActionEventHandler); ``` ``` -------------------------------- ### Install Specific Version of Tableau React npm Package Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_react.html To install a specific version of the library, append the desired version number to the installation command. Ensure the version is compatible with your Tableau instance. ```bash npm i @tableau/embedding-api-react@3.12.1 Copy ``` -------------------------------- ### Install Tableau React npm Package Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_react.html Use this command to install the latest version of the Tableau Embedding API React library into your project's node_modules folder. ```bash npm i @tableau/embedding-api-react Copy ``` -------------------------------- ### Configure package.json for ES Module Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_get.html Example package.json configuration to enable ES module support, necessary when importing the Tableau Embedding API as an ES module. ```json { "name": "tableau-viz-demo", "version": "0.1.0", "private": true, "type": "module", "dependencies": { "@tableau/embedding-api": "~3.12.1", "etc. ....": "this example is not complete" } } ``` -------------------------------- ### Accessing the Tableau Web Component Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_interact.html Demonstrates how to get a JavaScript reference to the `` or `` web component using `document.querySelector` or `document.getElementById`. ```APIDOC ## Accessing the Tableau Web Component After adding a `` or `` component to your HTML, you can access it using JavaScript. ### Using `document.querySelector()` This method is faster and returns the first matching element. ```javascript const viz = document.querySelector("tableau-viz"); ``` ### Using `document.getElementById()` Use this method if you have multiple embedded views. Ensure you set an `id` for the web component. ```javascript const viz = document.getElementById('tableauViz'); ``` Without the `viz` object, further interaction with the embedded view is not possible. ``` -------------------------------- ### Get Summary Data Reader for All Rows Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Worksheet.html Demonstrates how to get and use the summary data reader to access all rows in a worksheet. Use await only inside an Async function. ```javascript let vizActiveSheet = viz.workbook.activeSheet; if (vizActiveSheet.sheetType === "worksheet") { const dataTableReader = await vizActiveSheet.getSummaryDataReaderAsync(); for (let currentPage = 0; currentPage < dataTableReader.pageCount; currentPage++) { const dataTablePage = await dataTableReader.getPageAsync(currentPage); // ... process current page .... } await dataTableReader.releaseAsync(); } ``` -------------------------------- ### Get All Parameters Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Workbook.html Retrieves a collection of all parameters used within the workbook. ```typescript workbook.getParametersAsync().then(parameters => { // Do something with the parameters }); ``` -------------------------------- ### revertAllAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/VizActions.html Restores the workbook to its starting state, equivalent to clicking the Revert All toolbar button. ```APIDOC ## revertAllAsync ### Description Restores the workbook to its starting state. ### Method revertAllAsync() ### Returns Promise ``` -------------------------------- ### Get All Parameter Names and Values Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_parameters.html Retrieve all parameters within a workbook and log their names and current values to the console. This is useful for inspecting the state of parameters. ```javascript async function getParameterNames() { let viz = document.getElementById("tableauViz"); const parameters = await viz.workbook.getParametersAsync(); parameters.forEach( (p) => { console.log(p.name, p.currentValue.value); }); }; ``` -------------------------------- ### Get All Parameter Names and Values Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_parameters.html Retrieves all parameters available in a workbook and logs their names and current values to the console using the `workbook.getParametersAsync()` method. ```APIDOC ## Get All Parameter Names and Values ### Description Retrieves an array of all parameter objects available in the workbook. ### Method `workbook.getParametersAsync()` ### Parameters None ### Response - **parameters** (Array): An array of parameter objects. ### Request Example ```javascript async function getParameterNames() { let viz = document.getElementById("tableauViz"); const parameters = await viz.workbook.getParametersAsync(); parameters.forEach( (p) => { console.log(p.name, p.currentValue.value); }); }; ``` ``` -------------------------------- ### Handle Promises with async/await for Mark Selection Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_about.html This example shows how to use the `async/await` syntax to handle promises returned by asynchronous methods like `getMarksAsync()`. This approach simplifies working with promises within asynchronous functions. ```javascript async function getSelectedMarks(event) { const marksSelected = await event.detail.getMarksAsync(); const numMarks = marksSelected.data[0].data.length; alert(`${numMarks} marks Selected`); // call additional asynchronous methods with the await keyword } ``` -------------------------------- ### Get Data from a Specific Logical Table Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/DataSource.html This example demonstrates how to retrieve data from a specific logical table within a data source using getLogicalTableDataAsync. It first finds the desired data source by name and then retrieves its logical tables to identify the target table's ID. Ensure you have the necessary methods to find the workbook and data source. ```javascript const dataSources = await worksheet.getDataSourcesAsync(); const dataSource = dataSources.find(datasource => datasource.name === "Sample - Superstore"); const logicalTables = await dataSource.getLogicalTablesAsync() const dataTable = await dataSource.getLogicalTableDataAsync(logicalTables[0].id); console.log(dataTable); ``` -------------------------------- ### launchAnalyticsAssistantAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/VizActions.html Launches the Analytics Assistant side pane. Use `isAnalyticsAssistantAvailableAsync` to check availability first. ```APIDOC ## launchAnalyticsAssistantAsync ### Description Use this method to launch the Analytics Assistant side pane. You can use the `isAnalyticsAssistantAvailableAsync()` method to check if the Analytics Assistant is available for use. ### Method launchAnalyticsAssistantAsync(): Promise ### Request Example ```javascript const isAnalyticsAssistantAvailable = await viz.isAnalyticsAssistantAvailableAsync(); if (isAnalyticsAssistantAvailable) { await viz.launchAnalyticsAssistantAsync(); } ``` ### Response #### Success Response (200) - **Promise** - Resolves when the Analytics Assistant is launched. ``` -------------------------------- ### Install Specific Version of Tableau Embedding API v3 Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_get.html Installs a specific version (e.g., 3.12.1) of the Tableau Embedding API v3 library. ```bash npm i @tableau/embedding-api@3.12.1 ``` -------------------------------- ### launchAnalyticsAssistantAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/AuthoringViz.html Launches the Analytics Assistant side pane. ```APIDOC ## launchAnalyticsAssistantAsync ### Description Use this method to launch the Analytics Assistant side pane. You can use the `isAnalyticsAssistantAvailableAsync()` method to check if the Analytics Assistant is available for use. ### Method `launchAnalyticsAssistantAsync()` ### Returns Promise ### Example ```javascript const isAnalyticsAssistantAvailable = await viz.isAnalyticsAssistantAvailableAsync(); if (isAnalyticsAssistantAvailable) { await viz.launchAnalyticsAssistantAsync(); } ``` ``` -------------------------------- ### Clone Existing Visualization Instance Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/VizSettings.html Use `instance-id-to-clone` to create a copy of an existing visualization instance, preserving the original state for continued analysis. ```html ``` -------------------------------- ### Launch Analytics Assistant Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/VizActions.html Launches the Analytics Assistant side pane. It's recommended to first check availability using `isAnalyticsAssistantAvailableAsync()` before calling this method. ```javascript const isAnalyticsAssistantAvailable = await viz.isAnalyticsAssistantAvailableAsync(); if (isAnalyticsAssistantAvailable) { await viz.launchAnalyticsAssistantAsync(); } ``` -------------------------------- ### getCustomViewsAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Workbook.html Gets the collection of CustomView objects associated with the workbook. ```APIDOC ## getCustomViewsAsync ### Description Gets the collection of CustomView objects associated with the workbook. ### Method getCustomViewsAsync ### Returns Promise ``` -------------------------------- ### Launch Analytics Assistant if Available Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/AuthoringViz.html Launches the Analytics Assistant side pane if it is available. It's recommended to check availability first using `isAnalyticsAssistantAvailableAsync()`. ```javascript const isAnalyticsAssistantAvailable = await viz.isAnalyticsAssistantAvailableAsync(); if (isAnalyticsAssistantAvailable) { await viz.launchAnalyticsAssistantAsync(); } ``` -------------------------------- ### Initialize Embedding API v3 using Web Component (HTML) Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_migration_guide.html This HTML snippet demonstrates initializing the Embedding API v3 using the `` web component. It simplifies initialization by configuring the viz directly in HTML. ```html Copy ``` -------------------------------- ### Invalid URL Error Example Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_troubleshoot.html This error indicates an incorrectly set src URL for the embedded viz. Use the 'Share' button and 'Copy Link' on Tableau for the correct URL. This example shows how the src might be set in JavaScript or within the `` web component. ```javascript viz.src = 'https://public.tableau.com/views/RegionalSampleWorkbook/Storms'; ``` ```html ``` -------------------------------- ### Export View as PNG Image Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_export.html Use the `exportImageAsync()` method to download the currently active view as a PNG image. This method requires access to the `TablaeuViz` object and places the file in the user's default download directory. ```html Export Image
``` -------------------------------- ### Open Download PDF Dialog Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_export.html This snippet demonstrates how to open the 'Download PDF' dialog box using the Viz.displayDialogAsync() method. It requires importing necessary Tableau API components and attaching an event listener to a button click after the viz is interactive. ```html Simple Export
``` -------------------------------- ### Get All Custom Views Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Workbook.html Retrieves a collection of all custom views associated with the workbook. ```typescript workbook.getCustomViewsAsync().then(customViews => { // Do something with the custom views }); ``` -------------------------------- ### Get Dashboard Filters Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Dashboard.html Retrieves the collection of filters currently applied to the dashboard. ```typescript getFiltersAsync(): Promise ``` -------------------------------- ### Apply Filters During Initialization with viz-filter Element Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_filter.html Alternatively, create a `viz-filter` element and append it to the `TableauViz` object before initialization to apply filters. This method is useful for setting a single filter value. ```javascript // assumes a viz object has been created const filter = document.createElement("viz-filter"); filter.setAttribute("field", "Region"); filter.setAttribute("value", "West"); viz.appendChild(filter); // render the view by appending it to "tableauViz" document.getElementById('tableauViz').appendChild(viz); ``` -------------------------------- ### Chained Asynchronous Operations Source: https://help.tableau.com/current/api/embedding_api/en-us/tutorial/tutorial.htm Demonstrates chaining multiple asynchronous operations using `async/await`. This example switches sheets, applies a range filter, and then selects marks, ensuring each step completes before the next begins. ```javascript async function switchTabsThenFilterThenSelectMarks() { const newSheet = await workbook.activateSheetAsync("GDP per capita by region"); activeSheet = newSheet; // It's important to await the promise so the next step // won't be called until the filter completes. await activeSheet.applyRangeFilterAsync( "Date (year)", { min: new Date(Date.UTC(2002, 1, 1)), max: new Date(Date.UTC(2008, 12, 31)), }, FilterUpdateType.Replace ); const selections = [ { fieldName: "AGG(GDP per capita (weighted))", value: { min: 20000, max: Infinity, }, }, ]; return await activeSheet.selectMarksByValueAsync(selections, SelectionUpdateType.Replace); } ``` -------------------------------- ### getUnderlyingDataAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Worksheet.html Gets the underlying data table for this worksheet. This method is deprecated and should be replaced with Worksheet.getUnderlyingTableDataReaderAsync or Worksheet.getUnderlyingTableDataAsync. ```APIDOC ## getUnderlyingDataAsync ### Description Gets the underlying data table for this worksheet. ### Method `getUnderlyingDataAsync(options?: GetUnderlyingDataOptions): Promise` ### Parameters #### Optional Parameters - **options** (GetUnderlyingDataOptions) - Collection of options to change the behavior of the call. ### Returns Promise - A data table containing the underlying data for the worksheet. ### Notes You can use the `GetUnderlyingDataOptions.maxRows` property to request the number of rows of data to return. If unspecified (maxRows == '0'), the call to `getUnderlyingDataAsync` requests all rows in the data source. Note that the maximum number of rows returned from the `getUnderlyingDataAsync()` method is limited to 10,000 rows. You can use the `DataTable` property, `isTotalRowCountLimited`, to test whether there is more data. ### Deprecated Use Worksheet.getUnderlyingTableDataReaderAsync or Worksheet.getUnderlyingTableDataAsync. ``` -------------------------------- ### Embedding Tableau Viz with Iframe Attributes and Resize Listener Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_configure.html This example embeds a Tableau visualization using a `tableau-viz` element, applies custom styling via iframe attributes and CSS, and includes a window resize listener to ensure the viz remains responsive. It demonstrates how to set iframe attributes like 'loading' and 'class', and apply inline styles. ```html
.red-border { border: 5px solid red !important; } .fun { box-shadow: 0px 0px 37px 0px #000000; transform: perspective(250px) rotateY(2deg) scale(0.75); }
``` -------------------------------- ### Export Summary Data from a Worksheet Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_export.html This example demonstrates how to export all summary data from the first worksheet of a dashboard. It utilizes `Viz.exportDataAsync()` and includes all available columns. Ensure the TableauViz element is present and interactive before calling this function. ```html Data Export
``` -------------------------------- ### Getting the Changed Parameter Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/ParameterChangedEvent.html Demonstrates how to use the getParameterAsync method to retrieve the parameter that triggered the ParameterChangedEvent. ```typescript getParameterAsync(): Promise ``` -------------------------------- ### Get all applied filters Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_pulse_filter.html Retrieves a list of all currently applied categorical filters on the Pulse metric. ```APIDOC ## Get Filters ### Description Retrieves a list of all currently applied categorical filters on the Pulse metric. Returns an array of `CategoricalPulseFilter` objects. ### Method `getFiltersAsync()` ### Response #### Success Response - **filters** (CategoricalPulseFilter[]) - An array of `CategoricalPulseFilter` objects representing the applied filters. ### Request Example ```javascript // assumes a Pulse object has been created // assumes there is a 'button' with the id 'getFilters' getFilters.onclick = async () => { const filters = await tableauPulse.getFiltersAsync(); console.log('filters', filters); } ``` ``` -------------------------------- ### Apply Filters During Initialization with addFilter() Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_filter.html Use the `addFilter()` method on the `TableauViz` object before rendering to apply filters. This method can take a comma-separated string of values for a single filter. ```javascript let url = 'https://public.tableau.com/views/Superstore_24/Overview'; // create the viz object const viz = new TableauViz(); viz.src = url; // configure the viz... // apply filters viz.addFilter('Region', 'Central,West'); // render the view by appending it to "tableauViz" document.getElementById('tableauViz').appendChild(viz); ``` -------------------------------- ### Get Filters in a Worksheet Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_filter.html Retrieves the list of filters applied to a specific worksheet within a workbook. ```APIDOC ## Get Filters in a Worksheet ### Description Retrieves the collection of filters used in a worksheet. This method returns all filters applied to the specified worksheet. ### Method `worksheet.getFiltersAsync()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript const sheetFilters = await worksheet.getFiltersAsync(); console.log(sheetFilters); ``` ### Response #### Success Response Returns an array of filter objects applied to the worksheet. #### Response Example ```json [ { "filterType": "Categorical", "appliedValues": ["CategoryA", "CategoryB"] } ] ``` ``` -------------------------------- ### Create and Configure Viz Object Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_about.html Instantiates a TableauViz object, sets its source and toolbar visibility, appends it to the DOM, and applies a filter to the active sheet. Ensure the 'tableau.embedding.3.latest.min.js' script is imported. ```javascript // create the viz object, assumes an
element exists with id="tableauViz" import { TableauViz, } from 'https://public.tableau.com/javascripts/api/tableau.embedding.3.latest.min.js'; const viz = new TableauViz(); viz.src = 'https://my-server/views/my-workbook/my-view'; viz.toolbar = 'hidden'; // add the viz object to the DOM document.getElementById('tableauViz').appendChild(viz); let sheet = viz.workbook.activeSheet; sheet.applyFilterAsync("Container", ["Boxes"], FilterUpdateType.Replace); Copy ``` -------------------------------- ### Get Filters from a Worksheet Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_filter.html Retrieves all filters applied to a specific worksheet and logs the list to the console. ```javascript const sheetFilters = await worksheet.getFiltersAsync(); console.log(sheetFilters); ``` -------------------------------- ### Get applied values of a Pulse filter Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_pulse_filter.html Retrieves the currently applied values for a specific categorical Pulse filter. ```APIDOC ### Get the applied values of a Pulse filter #### Description Retrieves the currently applied values for a specific categorical Pulse filter. The `appliedValues` property returns an array of filter values. #### Property - **appliedValues** (array) - An array containing the values currently applied to the filter. #### Request Example ```javascript // assumes a Pulse object has been created // assumes there is a 'button' with the id 'getFilters' getFilters.onclick = async () => { const filters = await tableauPulse.getFiltersAsync(); console.log(`The number of filters: ${filters.length} Filters: ${filters.map((s) => s.fieldName)}`); console.log('filter[0] applied values', filters[0].appliedValues); } ``` ``` -------------------------------- ### Handling URL Actions with UrlActionEvent Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/UrlActionEvent.html This snippet demonstrates how to listen for and handle URL actions using the UrlActionEvent. It logs the URL and target from the event details. ```javascript function urlActionEventHandler(event) { console.log('URL: ' + event.detail.url); console.log('Target: ' + event.detail.target); } let viz = document.getElementById('tableauViz'); viz.addEventListener(TableauEventType.UrlAction, urlActionEventHandler); ``` -------------------------------- ### Accessing Worksheets in v3 Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_migration_guide.html Example of how to access worksheets in a dashboard using the updated Embedding API v3 syntax. ```javascript // get the currently active sheet (dashboard in this case) const activeSheet = viz.workbook.activeSheet; const worksheets = activeSheet.worksheets; ``` -------------------------------- ### Configure `` Web Component with Options Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_ask_data.html This example shows how to embed an Ask Data lens using the `` web component with custom height, width, and options to show save and share buttons. Remember to include the Embedding API library. ```html ``` -------------------------------- ### Accessing Worksheets in v2 Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_migration_guide.html Example of how to access worksheets in a dashboard using the older JavaScript API v2 syntax. ```javascript // get the currently active sheet (dashboard in this case) // and get the worksheets in the dashboard. const sheets = viz.getActiveSheet().getWorksheets(); ``` -------------------------------- ### Apply Custom Parameters Using JavaScript Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_parameters.html Example of using JavaScript to add a custom parameter to hide the Share button on the toolbar. Custom parameter names require a colon prefix. Ensure parameters are added before the 'src' URL is assigned. ```javascript import { TableauViz } from "https://public.tableau.com/javascripts/api/tableau.embedding.3.latest.js"; // create viz object const viz = new TableauViz(); // add custom parameter const customParameter = document.createElement("custom-parameter"); customParameter.setAttribute("name", ":showShareOptions"); customParameter.setAttribute("value", "false"); viz.appendChild(customParameter); // set src URL viz.src="https://public.tableau.com/views/Superstore_800_600/Overview"; // add viz to HTML page document.getElementById("tableauViz").appendChild(viz); ``` -------------------------------- ### Get Domain of RangeFilter Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/RangeFilter.html Fetches the domain of the range filter, which represents the possible values. An optional domain type can be specified. ```typescript getDomainAsync(domainType?: FilterDomainType): Promise ``` -------------------------------- ### Get the domain of a categorical Pulse filter Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_pulse_filter.html Retrieves all possible values for a given categorical Pulse filter, with support for pagination. ```APIDOC ### Get the domain of a categorical Pulse filter #### Description Retrieves all possible values for a given categorical Pulse filter. This method supports pagination and returns values in chunks, along with a total count and a next page token. The maximum number of field values returned is 1000. #### Method `CategoricalPulseFilter.getDomainAsync(pageSize?: number, nextPageToken?: string, searchTerm?: string)` #### Parameters - **pageSize** (number) - Optional - The number of field values to retrieve per page. Defaults to 100. Maximum is 1000. - **nextPageToken** (string) - Optional - A token to retrieve the next page of results. - **searchTerm** (string) - Optional - A search term to filter the domain values. #### Response - **fieldValues** (array) - An array of field values for the current page. - **total** (number) - The total number of available field values. - **nextPageToken** (string) - A token to retrieve the next page of results. Empty if there are no more pages. #### Request Example ```javascript // Example: Get the first 100 values const firstPage = await pulseFilter.getDomainAsync(); // Example: Get the next 1000 values using a page token and specified page size const secondPage = await pulseFilter.getDomainAsync(1000, firstPage.nextPageToken); // Example: Search for values containing 'Sales' const searchResults = await pulseFilter.getDomainAsync(undefined, undefined, 'Sales'); ``` ``` -------------------------------- ### Viz Display Dialog Method Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_release_notes.html Opens a specific dialog for the Viz object, such as the Share dialog. ```APIDOC ## Viz Display Dialog Method ### Description Displays a specified dialog for the visualization. ### Method - `Viz.displayDialogAsync(TableauDialogType.Share)` ``` -------------------------------- ### Get Current Filters from Pulse Metric - JavaScript Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/PulseActions.html Retrieves a list of all currently applied filters on the Pulse metric. This is an asynchronous operation. ```javascript pulse.getFiltersAsync(); ``` -------------------------------- ### Syntax for Creating Custom Parameters in JavaScript Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_parameters.html This JavaScript code demonstrates how to programmatically create a custom parameter element and append it to a viz object. Add custom parameters before setting the 'src' URL. ```javascript const customParameter = document.createElement("custom-parameter"); customParameter.setAttribute("name", "parameter-name"); customParameter.setAttribute("value", "parameter-value"); viz.appendChild(customParameter); ``` -------------------------------- ### Handle First Viz Size Known Event Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/VizSettings.html Use the onFirstVizSizeKnown event to perform tasks like resizing surrounding elements once the Viz object's size is established. ```html ``` ```html ``` -------------------------------- ### Set Pulse Layout Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/PulseSettings.html Specify a custom layout for the Pulse metric using the `layout` attribute. Example values include 'card'. ```html Copy ``` -------------------------------- ### Get Summary Data Reader and Individual Pages Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Worksheet.html Replaces deprecated getSummaryDataAsync with getSummaryDataReaderAsync and getPageAsync for processing summary data page by page. ```javascript let vizActiveSheet = viz.workbook.activeSheet; if (vizActiveSheet.sheetType === "worksheet") { const dataTableReader = await vizActiveSheet.getSummaryDataReaderAsync(); for (let currentPage = 0; currentPage < dataTableReader.pageCount; currentPage++) { const dataTablePage = await dataTableReader.getPageAsync(currentPage); // ... process current page .... } await dataTableReader.releaseAsync(); } ``` -------------------------------- ### Interface ContextMenuOptions Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/ContextMenuOptions.html Information needed to insert and display an external context menu item. ```APIDOC ## Interface ContextMenuOptions ### Description Information needed to insert and display an external context menu item. ### Properties #### displayName - **displayName** (string) - Description of the display name property. ``` -------------------------------- ### Get Current Time Dimension from Pulse Metric - JavaScript Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/PulseActions.html Retrieves the current time dimension applied to the Pulse metric. This is an asynchronous operation. ```javascript pulse.getTimeDimensionAsync(); ``` -------------------------------- ### Extracting Filter Domain Values Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_pulse_filter.html This example shows how to retrieve all filters and then extract field values from the domains of two categorical filters. It demonstrates fetching database and relevant domain values, including pagination for large datasets. It also shows how to retrieve relevant domain values that contain a specific string. ```javascript // assumes a Pulse object has been created // assumes there is a 'button' with the id 'getFilters' getFilters.onclick = async () => { const filters = await tableauPulse.getFiltersAsync(); console.log('filters', filters); let domain = []; let page = undefined; let pageSize = 100; do { page = await filters[0].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Database); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (database)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[0].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (relevant)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[1].getDomainAsync('', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (relevant)', domain); domain = []; page = undefined; pageSize = 100; do { page = await filters[1].getDomainAsync('foo', pageSize, page?.nextPageToken, FilterDomainType.Relevant); domain = domain.concat(page.values); console.log(`Retrieved ${domain.length} of ${page.totalAvailable} field values`); pageSize = page.totalAvailable - domain.length; } while (page.nextPageToken); console.log('domain (foo)', domain); }; ``` -------------------------------- ### Change a Specific Parameter Value Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_parameters.html Demonstrates how to get a specific parameter object using `getParametersAsync()` and then change its value using the `parameter.changeValueAsync()` method. ```APIDOC ## Change a Specific Parameter Value ### Description Allows you to get a specific parameter object and then change its value asynchronously. ### Method `parameter.changeValueAsync(newValue)` ### Parameters - **newValue** (any) - Required - The new value for the parameter. Must match the allowable values for the parameter. ### Request Example ```javascript async function setParamFunc() { let viz = document.getElementById("tableauViz"); try { const parameters = await viz.workbook.getParametersAsync(); const baseSalary = parameters.find( (p) => p.name == "Base Salary"); newVal = await baseSalary.changeValueAsync("75000"); console.log(newVal); } catch (error) { console.log (error); } } ``` ### Response This method does not return a value upon success, but it may throw an error if the parameter cannot be changed. ``` -------------------------------- ### Retrieve Selected Data with `getAllPagesAsync` Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_data.html This method retrieves a specified number of rows (up to a limit) from a data source, preparing pages of a specified size. It's efficient for getting a large subset of data, especially when combined with options to only include native data values. ```APIDOC ## getLogicalTableDataReaderAsync and getAllPagesAsync ### Description Retrieves a large number of rows (up to a specified limit) from a data source by preparing pages of a given size. Can optimize performance by requesting only native data values. ### Method `getLogicalTableDataReaderAsync(logicalTableId, pageRowCount, options)` followed by `getAllPagesAsync(maxRowCount)` ### Parameters #### Path Parameters - **logicalTableId** (string) - Required - The ID of the logical table to read data from. - **pageRowCount** (number) - Optional - The number of rows per page. Defaults to 10,000. - **options** (object) - Optional - Additional options for data retrieval. `includeDataValuesOption` can be set to `tableau.IncludeDataValuesOption.OnlyNativeValues` for performance. - **maxRowCount** (number) - Optional - The maximum number of rows to retrieve with `getAllPagesAsync`. Defaults to a system limit. ### Request Example ```javascript const dataSources = await worksheet.getDataSourcesAsync(); const dataSource = dataSources.find(datasource => datasource.name === "Sample - Superstore"); const logicalTables = await dataSource.getLogicalTablesAsync() const dataTableReader = await dataSource.getLogicalTableDataReaderAsync(logicalTables[0].id, 10000, { includeDataValuesOption: tableau.IncludeDataValuesOption.OnlyNativeValues }); const dataTable = await dataTableReader.getAllPagesAsync(150000); console.log(dataTable); // release resources await dataTableReader.releaseAsync(); ``` ### Response #### Success Response - **DataTable** - A DataTable containing the retrieved data. #### Response Example (See Request Example for processing logic) ``` -------------------------------- ### Conditional Error Handling for Authentication Flows Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_auth.html Implement advanced error handling logic within a `VizLoadError` event listener. This example demonstrates how to conditionally switch to a previous authentication flow for 'unknown-auth-error' or prompt the user to log in for other errors by removing the token. ```javascript // Error handling logic tableauViz.addEventListener(TableauEventType.VizLoadError, (e) => { if (e.detail.errorCode == "unknown-auth-error") { e.target.iframeAuth = true; } else { e.target.removeAttribute("token"); // prompt user to login } }); ``` -------------------------------- ### Finding a Published Sheet in v2 Source: https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_migration_guide.html Example of how to find a specific published sheet by name using the older JavaScript API v2 syntax. ```javascript let sameSheet = workbook.getPublishedSheetsInfo().get("Sheet 1"); ``` -------------------------------- ### getSummaryDataReaderAsync Source: https://help.tableau.com/current/api/embedding_api/en-us/reference/interfaces/Worksheet.html Gets a summary data table reader for this worksheet. This is the recommended method for accessing summary data, especially for large datasets, as it supports pagination. ```APIDOC ## getSummaryDataReaderAsync ### Description Gets a summary data table reader for this worksheet. Only one active DataTableReader for summary data is supported. ### Method `getSummaryDataReaderAsync(pageRowCount?: number, options?: GetSummaryDataOptions): Promise` ### Parameters #### Optional Parameters - **pageRowCount** (number) - The number of rows per page. The default and maximum is 10,000 rows. - **options** (GetSummaryDataOptions) - Collection of options to change the behavior of the reader. ### Returns Promise - A data table reader to access the summary data for the worksheet. ``` -------------------------------- ### jQuery Ready Handler for Initialization Source: https://help.tableau.com/current/api/embedding_api/en-us/tutorial/tutorial.htm This jQuery code ensures that the `initializeViz` function is called only after the DOM is fully loaded and ready. ```javascript $(initializeViz); ```