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);
```