# tableau Api Tableau JavaScript API (js_api) - Full Documentation [Skip to main content](#main-content) # About Tableau Help ## Addressing Implicit Bias in Technical Language In an effort to align with one of our core company values, equality, we have changed terminology to be more inclusive where possible. Because changing terms in code can break current implementations, we maintain the current terminology in the following places: - Tableau APIs: methods, parameters, and variables - Tableau CLIs: commands and options - Installers, installation directories, and terms in configuration files - (Undefined variable: Variables.PT\_server\_long) (we plan to make changes to non-inclusive terminology in the web interface, error messages, and related documentation soon.) - Third-party systems documentation For more information about our ongoing effort to address implicit bias, see [Salesforce Updates Technical Language in Ongoing Effort to Address Implicit Bias](https://www.salesforce.com/news/stories/salesforce-updates-technical-language-in-ongoing-effort-to-address-implicit-bias/) on the Salesforce website. [Skip to main content](#main-content) # API Reference **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). This section describes classes and methods of the Tableau JavaScript API. The JavaScript API files are located on the server (including Tableau Cloud and Tableau Public). There is no separate download. To use the JavaScript API, you just specify the URL to the JavaScript API file in your web page. For more information, see [Access the API](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_concepts_get_API.htm). ## Style and Conventions Tableau's JavaScript API follows these JavaScript standards for formatting names: - **Classes** use PascalCase (initial capital letter, with each subsequent word capitalized). - **Namespaces, methods, parameters, and variables** use camelCase (initial lower-case letter, with each subsequent word capitalized). - **Constants and enum values** use UPPERCASE; multi-word names use UPPERCASE\_UNDERSCORE\_DELIMITED. - **Protected variables or method** start with an initial underscore ( \_ ) character, indicating that it should not be referenced by the programmer. Tableau does not provide support for programs that customers create that use the Tableau JavaScript API. For help with your code, submit questions and ask for help on the Tableau developer community forums. Tableau does provide support for potential bugs in the Tableau JavaScript API code itself, and for unmodified sample code that isn't working. ## Top-Level Class Diagram The following class diagram shows the relationships between the top-level classes, as well as the inheritance hierarchy for the `Sheet`, `Dashboard`, `Story` and `Worksheet` classes. Note that there's always a way to traverse back up the containment hierarchy with parent pointers. The exception of `VizManager`, because that's a static class and always accessible. ![](/tableau/next/en-us/api/js_api/en-us/Img/jsapi_toplevel.png) ## Asynchronous and Error Classes ### Promise Class Represents a promise to return a value from an asynchronous method in the future. The Tableau JavaScript API implements the [Promises/A](http://wiki.commonjs.org/wiki/Promises/A) specification. #### Methods

Name

Return Type

Description

then(callback: Function, errback: Function)

Promise

Creates a link in the asynchronous callable chain. The callback function is called on success. The errback function is called when there is an error. Both parameters are optional.

always(callback: Function)

Promise

Registers a callback that will be called when a promise is resolved or rejected. Shortcut for then(callback, callback).

otherwise(errback: Function) Promise Registers a rejection handler. Shortcut for then(null, errback).
### TableauException Class The `TableauException` class is not a real class, but simply adds an `id` field to the standard JavaScript `Error` object when an exception is thrown from within the API. This allows you to uniquely identify the error without having to parse the error string. It also allows you to add localized messages. #### Constructor There is no public constructor. The only way to get a reference to a `TableauException` object is within a `catch` block. #### Fields

Name

Type

Description

tableauSoftwareErrorCode

ErrorCode

Represents an ErrorCode enum value.

message

string

This is already defined on the standard Error object, but the message will contain a description of the exception that the API code specifies.

### ErrorCode Enum Here's a list of the different exceptions that the API can throw:

Name

Value

Description

BROWSER_NOT_CAPABLE

browserNotCapable

The browser is not capable of supporting the Tableau JavaScript API.

DOWNLOAD_WORKBOOK_ NOT_ALLOWED

downloadWorkbookNotAllowed

The permissions on a workbook or a view do not allow downloading the workbook.

FILTER_CANNOT_BE_ PERFORMED

filterCannotBePerformed

An error occurred while attempting to perform a filter operation.

INDEX_OUT_OF_RANGE

indexOutOfRange

Attempted to switch to a sheet by index that does not exist in the workbook.

INTERNAL_ERROR

internalError

An error occurred within the Tableau JavaScript API. Contact Tableau Support.

INVALID_AGGREGATION_ FIELD_NAME invalidAggregationFieldName An invalid aggregation was specified for the filter, such as setting a range filter to "SUM(Sales)" instead of "Sales".

INVALID_CUSTOM_VIEW_ NAME

invalidCustomViewName

An operation was attempted on a custom view that does not exist.

INVALID_DATE_PARAMETER

invalidDateParameter

An invalid date was specified in a method that required a date parameter.

INVALID_FILTER_ FIELDNAME

invalidFilterFieldName

A filter operation was attempted on a field that does not exist in the data source.

INVALID_FILTER_ FIELDNAME_OR_VALUE

invalidFilterFieldNameOrValue

Either a filter operation was attempted on a field that does not exist in the data source, or the value supplied in the filter operation is the wrong data type or format.

INVALID_FILTER_ FIELDVALUE

invalidFilterFieldValue

A filter operation was attempted using a value that is the wrong data type or format.

INVALID_PARAMETER

invalidParameter

A parameter is not the correct data type or format. The name of the parameter is specified in the Error.message field.

INVALID_SELECTION_DATE

invalidSelectionDate

An invalid date value was specified in a Sheet.selectMarksAsync() call for a date field.

INVALID_SELECTION_ FIELDNAME

invalidSelectionFieldName

A field was specified in a Sheet.selectMarksAsync() call that does not exist in the data source.

INVALID_SELECTION_VALUE

invalidSelectionValue

An invalid value was specified in a Sheet.selectMarksAsync() call.

INVALID_SIZE

invalidSize

A negative size was specified or the maxSize value is less than minSize in Sheet.changeSizeAsync().

INVALID_SIZE_BEHAVIOR_ ON_WORKSHEET

invalidSizeBehaviorOnWorksheet

A behavior other than SheetSizeBehavior.AUTOMATIC was specified in Sheet.changeSizeAsync() when the sheet is a Worksheet instance.

INVALID_URL

invalidUrl

The URL specified in the Viz class constructor is not valid.

MISSING_MAX_SIZE

missingMaxSize

The maxSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATMOST.

MISSING_MIN_SIZE

missingMinSize

The minSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATLEAST.

MISSING_MINMAX_SIZE

missingMinMaxSize

Either or both of the minSize or maxSize fields is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.RANGE.

MISSING_RANGEN_FOR_ RELATIVE_DATE_FILTERS

missingRangeNForRelativeDateFilters

The rangeN field is missing for a relative date filter of type LASTN or NEXTN.

NO_URL_FOR_HIDDEN_ WORKSHEET

noUrlForHiddenWorksheet

An attempt was made to access Sheet.getUrl() on a hidden sheet. Hidden sheets do not have URLs.

NO_URL_OR_PARENT_ ELEMENT_NOT_FOUND

noUrlOrParentElementNotFound

One or both of the parentElement or the URL parameters is not specified in the Viz constructor.

NOT_ACTIVE_SHEET

notActiveSheet

An operation was attempted on a sheet that is not active or embedded within the active dashboard.

NULL_OR_EMPTY_ PARAMETER

nullOrEmptyParameter

A required parameter was not specified, null, or an empty string/array.

SERVER_ERROR

serverError

A general-purpose server error occurred. Details are contained in the Error object.

SHEET_NOT_IN_WORKBOOK

sheetNotInWorkbook

An operation was attempted on a sheet that does not exist in the workbook.

STALE_DATA_REFERENCE

staleDataReference

An operation is performed on a CustomView object that is no longer valid (it has been removed).

UNSUPPORTED_EVENT_ NAME

unsupportedEventName

An unknown event name was specified in the call to Viz.addEventListener or Viz.removeEventListener.

VIZ_ALREADY_IN_MANAGER

vizAlreadyInManager

A Viz object has already been created as a child of the parentElement specified in the Viz constructor.

## Viz Classes ### VizManager Class Manages all of the `Viz` instances on the page. This is a static class, meaning that all properties and methods are static and there is only a single instance of the class. This class can manage views that have been created using Tableau 8.0 or later. It cannot manage views created using earlier versions of Tableau. #### Properties

Name

Type

Description

getVizs()

Viz[]

Collection of views on the hosting page.

### Viz Class Wraps an `iframe` element showing one or more sheets in a Tableau workbook. Contains all of the chrome surrounding the view. #### Constructor

Signature

Description

Viz(parentElement: domNode, url: string, options: VizCreateOptions)

Creates a new Tableau Viz inside of the given HTML container, which is typically a <div> element. Each option as well as the options parameter is optional. If there is already a Viz associated with the parentElement, an exception is thrown. Before reusing the parentElement you must first call dispose().

#### Properties

Name

Type

Description

getAreTabsHidden()

bool

Indicates whether the tabs are displayed in the UI. It does not actually hide individual tabs.

getIsToolbarHidden()

bool

Indicates whether the toolbar is displayed.

getIsHidden()

bool

Indicates whether the visualization is displayed on the hosting page.

getParentElement()

domNode

Returns the node that was specified in the constructor.

getUrl()

string

The URL of the visualization, as specified in the constructor

getWorkbook()

Workbook

One Workbook is supported per visualization.

getAreAutomaticUpdatesPaused()

bool

Indicates whether automatic updates are currently paused.

#### Events Events are added or removed via the following two calls.

Name

Return Type

Description

addEventListener(
type: TableauEventName,
listener: Function)

None

Adds an event listener to the specified event.

removeEventListener(
type: TableauEventName,
listener: Function)

None

Removes an event listener from the specified event.

#### Methods

Name

Type

Description

show()
hide()

None

Shows or hides the iframe element hosting the visualization.

dispose()

None

Cleans up any resources associated with the visualization, removes the visualization from the VizManager instance, and removes any DOM elements from the parentElement object. In effect, this method restores the page to what it was before a Viz object was instantiated.
Note Before you call this method, make sure you are done referencing any objects.

pauseAutomaticUpdatesAsync()
resumeAutomaticUpdatesAsync()
toggleAutomaticUpdatesAsync()

None

Pauses or resumes layout updates. This is useful if you are resizing the visualization or performing multiple calls that could affect the layout.

revertAllAsync()

None

Equivalent to clicking on the Revert All toolbar button, which restores the workbook to its starting state.

refreshDataAsync ()

None

Equivalent to clicking on the Refresh Data toolbar button.

showDownloadDialog() None Equivalent to clicking on Download from the toolbar, which shows the Download dialog box allowing the user to select the type of download.

showDownloadWorkbookDialog()

None

Equivalent to clicking on Download > Tableau Workbook from the toolbar, which downloads a copy of the original workbook.

showExportImageDialog()

None

Equivalent to clicking on Download > Image from the toolbar, which creates a PNG file of the current visualization.

showExportPDFDialog()

None

Equivalent to clicking on Download > PDF from the toolbar, which shows a dialog allowing the user to select options for downloading a PDF file.

showExportPowerPointDialog() None

Equivalent to clicking on Download > PowerPoint from the toolbar, which shows a dialog allowing the user to choose the sheets from the workbook or dashboard to download in a PowerPoint file.

showExportDataDialog( worksheetInDashboard: Sheet or SheetInfo or string) None Shows the Export Data dialog, which is currently a popup window. The worksheetInDashboard parameter is optional. If not specified, the currently active Worksheet is used. If there is no currently active Worksheet, the method throws an exception.
showExportCrossTabDialog( worksheetInDashboard: Sheet or SheetInfo or string) None Shows the Export CrossTab dialog. You can choose to download the crosstab data as a CSV file or to cancel the operation. The worksheetInDashboard parameter is optional. If not specified, the currently active Worksheet is used. If there is no currently active Worksheet, the method throws an exception.
exportCrossTabToExcel( worksheetInDashboard: Sheet or SheetInfo or string) None Downloads the crosstab data as an Excel file to the default location specified by the browser. The worksheetInDashboard parameter is optional. If not specified, the currently active Worksheet is used. If there is no currently active Worksheet, the method throws an exception.

showShareDialog()

None

Equivalent to clicking on the Share toolbar button, which displays a dialog allowing the user to share the visualization by email or by embedding its HTML in a web page.

setFrameSize(width: int, height: int)

None

Sets the size of the iframe element, which causes the visualization to expand or collapse to fit the iframe element if the visualization size (current sheet's size) is set to AUTOMATIC.

getCurrentUrlAsync()

String

Gets the URL of the visualization asynchronously.

redoAsync()

None

Redoes last action on a sheet, defaults to a single redo unless optional parameters is specified.

undoAsync()

None

Undoes action on sheet, defaults to a single undo unless optional parameters is specified.

### VizCreateOptions Record Defines options that are specified in the `Viz` constructor. #### Fields

Name

Type

Description

disableUrlActionsPopups

bool

Indicates whether to suppress the execution of URL actions. This option does not prevent the URL action event from being raised. You can use this option to change what happens when a URL action occurs. If set to trueand you create an event listener for the URL_ACTION event, you can use an event listener handler to customize the actions. For example, you can direct the URL to appear in an iframeon your web page. See URL Action Example.

hideTabs

bool

Indicates whether tabs are hidden or shown.

hideToolbar

bool

Indicates whether the toolbar is hidden or shown.

The toolbar is always shown if the view is hosted on Tableau Public.

instanceIdToClone string

Specifies the ID of an existing instance to make a copy (clone) of. This is useful if the user wants to continue analysis of an existing visualization without losing the state of the original. If the ID does not refer to an existing visualization, the cloned version is derived from the original visualization.

height

string

Can be any valid CSS size specifier. If not specified, defaults to the published height of the view.

width

string

Can be any valid CSS size specifier. If not specified, defaults to the published width of the view.

device

string

Specifies a device layout for a dashboard, if it exists. Values can be default, desktop, tablet, or phone. If not specified, defaults to loading a layout based on the smallest dimension of the hosting iframe element.

"filter name" string Apply a filter that you specify to the view when it is first rendered. For example, if you have an Academic Year filter and only want to display data for 2022, you might enter "Academic Year": "2022". For more information, see Filtering.

onFirstInteractive

callback(e: TableauEvent)

Callback function that is invoked when the Viz object first becomes interactive. This is only called once, but it’s guaranteed to be called. If the Viz object is already interactive, it will be called immediately, but on a separate "thread."

If a listener has been attached to the CUSTOM_VIEW_LOAD event, that event is raised after the callback function specified for onFirstInteractive has been called.

 Custom views are not guaranteed to be loaded when the viz becomes interactive. Use the getCustomViewsAsync method to make sure that all the views are loaded before you call the showCustomViewAsync method.

onFirstVizSizeKnown

callback(e: VizResizeEvent)

Callback function that's invoked when the size of the Viz object is known. You can use this callback to perform tasks such as resizing the elements surrounding the Viz object once the object's size has been established.

toolbarPosition

ApiToolbarPosition

Specifies the position of the toolbar, if it is shown. The values can be ApiToolbarPosition.Top or ApiToolbarPosition.Bottom.

#### InitViz Example The following example shows how the Viz object can be created in a initialization function. The initialization function can be called in your HTML page on page load. The Viz constructor takes three parameters: the div container on the hosting HTML page, the URL of the visualization on Tableau Server (includes Tableau Cloud and Tableau Public), and a set of options (see `VizCreateOptions`). For information about creating the Viz object, see [Initialize the API](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_concepts_initializing.htm). ``` ``` ### ApiToolbarPosition Enum #### Enumeration

Name

Description

TOP

Positions the toolbar along the top of the visualization.

BOTTOM

Positions the toolbar along the bottom of the visualization.

### ToolbarState Class Wraps the toolbar state. Using this class allows you to determine whether or not a toolbar button is enabled. See [Toolbar State Example](#Toolbar). #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the toolbar.

isButtonEnabled(toolbarButtonName)

bool

Gets a value indicating whether the specified toolbar button is enabled. The supported buttons are defined in the ToobarButtonName enum. Currently, only Undo and Redo are supported. Checking this property with a toolbar button that is not supported causes an InvalidToolbarButtonName error.

### ToolbarButtonName Enum #### Enumeration

Name

Description

UNDO

Specifies the Undo button in the toolbar.

REDO

Specifies the Redo button in the toolbar.

## Viz Event Classes ### TableauEventName Enum Defines strings passed to the `Viz.addEventListener` and `Viz.removeEventListener` methods. The values of the enums are all lowercase strings with no underscores. For example, `CUSTOM_VIEW_LOAD` is `customviewload`. Either the fully-qualified enum (`tableau.TableauEventName.FILTER_CHANGE`) or the raw string (`filterchange`) is acceptable.

Name

Event Class Passed in the Callback

Description

CUSTOM_MARK_CONTEXT_MENU

CustomMarkContextMenu

Raised when a custom mark context menu item is selected.

CUSTOM_VIEW_LOAD

CustomViewEvent

Raised when a custom view has finished loading. This event is raised after the callback function for onFirstInteractive (if any) has been called.

CUSTOM_VIEW_REMOVE

CustomViewEvent

Raised when the user removes a custom view.

CUSTOM_VIEW_SAVE

CustomViewEvent

Raised when the user saves a new or existing custom view.

CUSTOM_VIEW_SET_DEFAULT

CustomViewEvent

Raised when a custom view has been made the default view for this visualization.

FILTER_CHANGE

FilterEvent

Raised when any filter has changed state. The Viz object may not be interactive yet.

MARKS_SELECTION

MarksEvent

Raised when marks are selected or deselected.

PARAMETER_VALUE_CHANGE

ParameterEvent

Raised when any parameter has changed state.

STORY_POINT_SWITCH StoryPointSwitchEvent Raised after a story point becomes active.

TAB_SWITCH

TabSwitchEvent

Raised after the tab switched, but the Viz object may not yet be interactive.

TOOLBAR_STATE_CHANGE

ToolbarStateEvent Raised when the state of the specified toolbar button changes. See Toolbar State Example.
URL_ACTION UrlActionEvent

Raised when a URL action occurs. See the UrlActionEvent class and the URL Action Example.

VIZ_RESIZE

VizResizeEvent

Raised every time the frame size is calculated from the available size and the Viz object's published size.

### TableauEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

### CustomMarkContextMenu Class #### Properties

Name

Type

Description

getContextMenuId()

string

Gets the contextMenuId used to identify the menu item associated with the event.

### CustomViewEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

#### Methods

Name

Return Type

Description

getCustomViewAsync()

Promise<CustomView>

Gets the CustomView object associated with the event.

### FilterEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getWorksheet()

Worksheet

Gets the Worksheet object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

getFieldName()

string

Gets the name of the field.

#### Methods

Name

Return Type

Description

getFilterAsync()

Promise<Filter>

Gets the Filter object associated with the event.

### MarksEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getWorksheet()

Worksheet

Gets the Worksheet object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

#### Methods

Name

Return Type

Description

getMarksAsync()

Promise<Mark[]>

Gets the selected marks on the Worksheet that triggered the event.

### ParameterEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

getParameterName()

string

Gets the name of the parameter that changed.

#### Methods

Name

Return Type

Description

getParameterAsync()

Promise<Parameter>

Gets the Parameter object that triggered the event.

### StoryPointSwitchEvent Class Returned in the callback for the STORY\_POINT\_SWITCH event. #### Properties

Name

Type

Description

getViz() Viz Gets the Viz object associated with the event.
getEventName() TableauEventName Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum. In this case, it is STORY_POINT_SWITCH.
getOldStoryPointInfo() StoryPointInfo Gets the StoryPointInfo that was active before the story point switch event occurred. The returned object reflects the state of the story point before the switch occurred. The returned object reflects the state of the story point after the switch occurred.
getNewStoryPoint() StoryPoint Gets the StoryPoint that is currently active.
### TabSwitchEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

getOldSheetName()

string

Gets the name of the sheet that was active before the tab switch event occurred.

getNewSheetName()

string

Gets the name of the sheet that is currently active.

### ToolbarStateEvent Class An event class that can signal when a toolbar button or control becomes available or becomes unavailable. #### Properties

Name

Type

Description

getToolbarState()

ToolbarState

Returns the new ToolbarState.

#### Toolbar State Example The following example shows how a toolbar state change can be used to enable custom undo and redo buttons. Note that the toolbar is always shown if the view is hosted on Tableau Public. ``` Undo and Redo

``` ### UrlActionEvent Class An event class that can signal when a URL action occurs. #### Properties

Name

Type

Description

getURL()

String

Returns the URL object associated with event.

getTarget() String Returns the target attribute associated with URL (for example, the identifier associated with a browser tab).
#### URL Action Example The following code snippet shows how you might add an event handler for a URL action to the `initViz()` method. You can be use the event handler to add custom functions to your web page, such as using the event to open the URL in a special `iframe` in your web page. To add the new functionality, you need to suppress the default URL action by setting `disableUrlActionsPopups` to `true`. Note that this is not a complete example of all the JavaScript and HTML code you need. You also need a workbook that has a URL action and Tableau Server running 2020.1 or later. ``` function initViz() { var containerDiv = document.getElementById("vizContainer"), url = "https://path-to-viz-with-url-action", options = { disableUrlActionsPopups: true, hideTabs: true, onFirstInteractive: function () { viz.addEventListener(tableau.TableauEventName.URL_ACTION, urlActionEventHandler); console.log("Run this code when the viz has finished loading."); }, }; viz = new tableau.Viz(containerDiv, url, options); // Create a viz object and embed it in the container div. function urlActionEventHandler(event) { // Provide an event handler for the URL action to add a new feature to the dashboard. console.log("URL: ", event.getUrl()); console.log("Target: ", event.getTarget()); } } ``` ### VizResizeEvent Class #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object associated with the event.

getEventName()

TableauEventName

Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum.

GetAvailableSize()

Size

Gets the sheetSize record for the current sheet. For more information, see SheetSize Record.

## Workbook Classes ### Class Diagram ![](/tableau/next/en-us/api/js_api/en-us/Img/jsapi_workbookclass.png) ### Workbook Class A Workbook has a collection of Sheets represented as tabs. It also has associated objects like `DataSources` and `CustomViews`. #### Properties

Name

Type

Description

getViz()

Viz

Gets the Viz object that contains the workbook.

getActiveSheet()

Sheet

Gets the currently active sheet (the active tab)

getActiveCustomView()

CustomView

Gets the currently active custom view, or null if no custom view is active.

getPublishedSheetsInfo()

SheetInfo[]

Note that this is synchronous, meaning that all of the sheets are expected when loaded.

getName()

string

Gets the name of the workbook saved to the server. Note that this is not necessarily the file name.

#### Methods

Name

Return Type

Description

activateSheetAsync(sheetNameOrIndex: object) Promise<Sheet> Activates the sheet, either by name or index, and returns a promise of the sheet that was activated.

revertAllAsync()

Promise

Reverts the workbook to its last saved state.

getParametersAsync()

Promise<Parameter[]>

Fetches the parameters for this workbook.

changeParameterValueAsync(
name: string,
value: object)

Promise<Parameter>

Changes the value of the parameter with the given name and returns the new Parameter. The value should be the same data type as the parameter and within the allowable range of values. It also needs to be the aliased value and not the raw value. For more information and examples, see changeParameterValueAsync() Additional Information

getCustomViewsAsync()

Promise<CustomView[]>

Gets the collection of CustomView objects associated with the workbook.

showCustomViewAsync(
customViewName: string)

Promise<CustomView>

Changes the visualization to show the named saved state.

workbook.showCustomViewAsync("Awesome" ).then(function() { // do something });

To reset a custom view to the original view, pass in a null value for the customViewName parameter.

workbook.showCustomViewAsync().then(function() { // do something });

removeCustomViewAsync(
customViewName: string)

Promise<CustomView>

Removes the named custom view.

rememberCustomViewAsync(
customViewName: string)

Promise<CustomView> Remembers the current state of the workbook by assigning a custom view name.

setActiveCustomViewAsDefaultAsync()

None

Sets the active custom view as the default.

#### changeParameterValueAsync() Additional Information The value parameter needs to meet the following conditions: 1. The data type should be the same underlying JavaScript type as is returned in `Parameter.getCurrentValue()`. For example, if `Parameter.getDataType()` is `FLOAT` or `INTEGER`, the value parameter should be a native JavaScript Number. The following table maps the ParameterDataType values to native JavaScript types.
ParameterDataTypeNative JavaScript Type
FLOATNumber
INTEGERNumber
STRINGString
BOOLEANBoolean
DATEDate
DATETIMEDate
When the parameter is a `FLOAT`, if the browser locale uses a decimal separator other than a decimal point (`.`), you should pass a string with the correct locale separator. For example, if the locale uses the comma as a separator, use `"3,5"` instead of the number, `3.5`, as in `viz.getWorkbook().changeParameterValueAsync("FLOAT_PARAM", "3,5")` . 7. If the parameter is restricted to a list of allowable values, the value should be one of those values. Querying `Parameter.getAllowableValuesType()` will indicate if the parameter values are restricted by returning `tableau.ParameterAllowableValuesType.LIST`. 8. If the parameter is restricted to a range of values, the value should be within the minimum and maximum values, inclusive. Querying `Parameter.getAllowableValuesType()` will indicate if the parameter values are restricted by returning `tableau.ParameterAllowableValuesType.RANGE`. The minimum and maximum values are returned via `Parameter.getMinValue()` and `Parameter.getMaxValue()`. 9. The value needs to be the aliased value, and not the raw value. To view the raw and aliased values, go to the Edit Parameter dialog box inTableau Desktop. In that dialog, use the values in the **Display As** column and not the **Value** column, as shown below. ![](/tableau/next/en-us/api/js_api/en-us/Img/jsapi_changeParameterValueAsync.png) #### Examples The following examples will help illustrate these concepts.

// Change a parameter called "Product Type" to "Coffee" when the parameter is

// restricted to the following allowable values:

// "Coffee", "Espresso", "Tea"

workbook.changeParameterValueAsync("Product Type", "Coffee");

// Change a parameter called "Measure" to a value that is aliased, "Sale". This

// example corresponds to the screen shot above.

workbook.changeParameterValueAsync("Measure", "Sale");

// Change a date parameter named "DateParam" to January 1, 2014 (UTC):

workbook.changeParameterValueAsync("DateParam", new Date(Date.UTC(2014, 0, 1)));

### DataSource Class The `Workbook` contains one or more data sources. Each `Worksheet` will have a primary data source and can have multiple secondary data sources. #### Properties

Name

Type

Description

getName()

string

The name of the DataSource as seen in the UI.

getIsPrimary()

bool

Indicates whether this DataSource is a primary or a secondary data source.

getFields()

Field[]

Gets an array of Fields associated with the DataSource.

### Field Class A field contains information about what data source it belongs to, its role, and the type of aggregation it is. #### Properties

Name

Type

Description

getName()

string

Gets the field name (i.e. caption).

getAggregation()

FieldAggregationType

Gets the type of aggregation, which is one of the following values: SUM, AVG, MIN, MAX, STDEV, STDEVP, VAR, VARP, COUNT, COUNTD, MEDIAN, ATTR, NONE, PERCENTILE, TRUNC_YEAR, TRUNC_QTR, TRUNC_MONTH, TRUNC_WEEK, TRUNC_DAY, TRUNC_HOUR, TRUNC_MINUTE, TRUNC_SECOND, QUART1, QUART3, SKEWNESS, KURTOSIS, INOUT, SUM_XSQR, USER

getDataSource()

DataSource

Gets the data source to which this field belongs.

getRole()

FieldRoleType

One of the following values: DIMENSION, MEASURE, UKNOWN

### CustomView Class Represents a named snapshot of the workbook at a specific moment. #### Properties

Name

Type

Description

getName()
setName()

string

User-friendly name for the custom view

getAdvertised()
setAdvertised()

bool

Indicates whether the custom view is public or private.

getDefault()

bool

Gets or sets whether this is the default custom view.

getOwnerName()

string

Gets the user that created the custom view.

getUrl()

string

Unique URL to load this view again.

getWorkbook()

Workbook

Gets the Workbook to which this CustomView belongs.
#### Methods

Name

Return Type

Description

saveAsync()

Promise<CustomView>

After saveAsync() is called, the result of the getUrl method is no longer blank.

## Sheet Classes ### Class Diagram ![](/tableau/next/en-us/api/js_api/en-us/Img/jsapi_sheetclass.png) ### SheetInfo Class Contains information about a `WORKSHEET`, a `DASHBOARD`, or a `STORY` and no methods. Returned as part of `Workbook.getPublishedSheetsInfo()`. #### Constructor There is no public constructor. You can only get instances of this class from `Workbook.getPublishedSheetsInfo()`. #### Properties

Name

Type

Description

getName()

string

Gets the name of the sheet.

getIndex()

int

Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published.

getIsActive()

bool

Gets a value indicating whether the sheet is the currently active sheet.Due to a technical limitation, this will always return false if the object is a Worksheet instance that is part of a Dashboard.

getIsHidden()

bool

Gets a value indicating whether the sheet is hidden in the UI. Note that if the entire tab control is hidden, it does not affect the state of this flag. This sheet may still report that it is visible even when the tabs control is hidden.

getSheetType()

SheetType

Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET, DASHBOARD and STORY.

getSize()

SheetSize

Gets the size information that the author specified when publishing the workbook.

getUrl()

string

Gets the URL for this sheet.

getWorkbook()

Workbook

Gets the Workbook to which this Sheet belongs.

### Sheet Class #### Constructor There is no public constructor. You can only get instances of this class from `Workbook.getActiveSheet()`or `Dashboard.getObjects()`. #### Properties

Name

Type

Description

getName()

string

Gets the name of the sheet.

getIndex()

int

Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published.

getIsActive()

bool

Gets a value indicating whether the sheet is the currently active sheet.

getIsHidden()

bool

Gets a value indicating whether the sheet is hidden in the UI. Note that if the entire tab control is hidden, it does not affect the state of this flag. This sheet may still report that it is visible even when the tabs control is hidden.

getSheetType()

SheetType

Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET , DASHBOARD and STORY.

getSize()

SheetSize

Gets the size information that the author specified when publishing the workbook.

getUrl()

string

Gets the URL for this sheet.

getWorkbook()

Workbook

Gets the Workbook to which this Sheet belongs.

#### Methods

Name

Return Type

Description

changeSizeAsync(SheetSize)

Promise<SheetSize>

Sets the size information on a sheet. Note that if the sheet is a Worksheet, only SheetSizeBehavior.AUTOMATIC is allowed since you can’t actually set a Worksheet to a fixed size.

#### SheetSize Record Describes the way a Sheet should be sized. #### Fields

Name

Type

Description

behavior

SheetSizeBehavior

Contains an enumeration value of one of the following: AUTOMATIC, EXACTLY, RANGE, ATLEAST, and ATMOST.

maxSize

Size

This is only defined when behavior is RANGE or ATMOST.

minSize

Size

This is only defined when behavior is EXACTLY, RANGE, or ATLEAST.

### DataTable Class When you call the `getSummaryDataAsync`, `getUnderlyingDataAsync`, or `getUnderlyingTableDataAsync` methods on a worksheet, Tableau Server returns a `DataTable` object. #### Methods

Name

Return Type

Description

getName()

string

Either "Underlying Data Table" or "Summary Data Table".

getData() array A two-dimensional array of data without the sheet or column metadata. The first array index is the row index and the second array index is the column index.
getColumns() array<Column> The column information, including the name, data type, and index.
getTotalRowCount() int The number of rows in the returned data.
getIsSummaryData() bool Whether the data is summary data or underlying data. Returns true for summary data.
### LogicalTable Class Represents a logical table in the worksheet. In Tableau 2020.2 and later, a data source can have multiple logical tables, and a logical table can contain one or more physical tables. When you call the `getUnderlyingTablesAsync` method on a worksheet, Tableau Server returns an array of `LogicalTable` objects corresponding to the measures referenced by the worksheet. To get the underlying data from the table, you use the id returned by `getTableId()`when you call the `getUnderlyingTableDataAsync()` method. For an example of how these methods are used, see the [Get Underlying Table Data Example](#gettabledata). #### Properties

Name

Return Type

Description

getTableId()

string

The identifier that uniquely identifies the logical table. You use the table identifier to get data when you call the getUnderlyingTableDataAsync() method.

getCaption() string The name of the logical table as it appears to users in Tableau 2020.2 and later.
#### Get Underlying Table Data Example To get data from worksheets in Tableau 2020.2 and later, you need to use the `getUnderlyingTablesAsync()` and `getUnderlyingTableDataAsync()` methods. The following example is based on the [Get Data](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_samples_get_data.htm) sample. In this example, a call is made to `getUnderlyingTablesAsync()`to get the tables in the data source used by the worksheet. In this case, the workbook contains a data source that was created prior to Tableau 2020.2, so it does not use multiple logical tables. The data source of the worksheet only contains one table, and we use that table id (`tables[0].getTableId()`) to access the underlying data in the call to `getUnderlyingTableDataAsync()`. These two methods replace the `getUnderlyingDataAysnc()` method to get the data in Tableau 2020.2 and later. These methods are available in the `tableau-2.5.0.min.js` library starting with Tableau 2020.2. ``` getData() Basic Table Example -
``` ### Column Class When you call the `getColumns` method on a `DataTable` object, Tableau Server returns an array of `Column` objects. For a particular object in the array, you can call the following methods: #### Methods

Name

Return Type

Description

getFieldName()

string

The name of the column.

getDataType() string The data type of the column. Possible values are float, integer, string, boolean, date, and datetime.
getIsReferenced() bool Whether the column data is referenced in the visualization.
getIndex() int The number of rows in the returned data.
### Worksheet Class Represents a worksheet tab in the workbook or a dashboard object. These are two separate concepts: a worksheet and a worksheet instance. However, for simplicity in the API, they are both combined into the `Worksheet` class. #### Constructor There is no public constructor. You can only get instances of this class from `Workbook.getPublishedSheetsInfo()` or `Dashboard.getObjects()`. #### Properties

Name

Type

Description

getParentDashboard()

Dashboard

Returns the Dashboard object to which this Worksheet belongs (if it’s on a dashboard). Otherwise, it returns null.

getParentStoryPoint() StoryPoint Returns the StoryPoint object to which this Worksheet belongs (if it’s on a story sheet). Otherwise, it returns null. If the Worksheet instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
#### Methods

Name

Return Type

Description

getDataSourcesAsync()

Promise<DataSource[]>

Gets the primary and all of the secondary data sources for this worksheet. Note that by convention the primary data source should always be the first element.

getSummaryDataAsync(getSummaryDataOptions) Promise<DataTable> Gets aggregated data for the fields used in the currently active sheet and returns it as an object. You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type.
getUnderlyingDataAsync(getUnderlyingDataOptions) Promise<DataTable> Gets data for all fields in the data source used by the currently active sheet and returns it as an object. You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type. Available in Tableau 2020.1 and earlier.
getUnderlyingTablesAsync() Promise<LogicalTable[]> Gets the underlying logical tables used by the worksheet. The resulting logical tables are determined by the measures in the worksheet. If a worksheet's data source contains multiple logical tables and the worksheet contains only measures from one logical table, this method will return one logical table. This can only be called on sheets of the WORKSHEET type. Available in Tableau 2020.2 and later. See LogicalTable and the Get Underlying Table Data Example.
getUnderlyingTableDataAsync(tableID, getUnderlyingDataOptions) Promise<DataTable>

Gets data for all fields in the specified logical table used by the currently active sheet and returns it as an object. You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type. Available in Tableau 2020.2 and later. See DataTable and the Get Underlying Table Data Example.

AppendContextMenuAsync( targetMenu: ApiMenuType, config: ContextMenuOptions) Promise<string>

Appends a new menu item into the place specified by targetMenu. Currently, the only allowed location is ApiMenuType.Ubertip (the tooltip that appears when marks are selected). Use the config option to specify the name of the menu item (ContextMenuOptions Class). If successful, this method returns the menuItemId of the new menu item.

var config = { displayName: "myMenuItemName" };

menuId = worksheet.appendContextMenuAsync(tableauSoftware.MenuType.UBERTIP, config);

RemoveContextMenuAsync( targetMenu: ApiMenuType, menuItemId: string) Promise<void>

Removes the menu item specified by menuItemId from the designated context menu.

worksheet.removeContextMenuAsync(tableauSoftware.MenuType.UBERTIP, menuId);

ExecuteContextMenuAsync( targetMenu: ApiMenuType, menuItemId: string)

Promise<void> Executes the menu item specified by menuItemId from the designated context menu. You can use this method for testing the context menu item.
Filtering methods are described in [Worksheet Class (Filtering)](#worksheet_class_filtering). Marks selection methods are described in [Worksheet Class (Selecting Marks)](#_Worksheet_Class_\(Selecting). To use the `getSummaryDataAsync`, `getUnderlyingDataAsync`, `getUnderlyingTablesAsync`, or `getUnderlyingTableDataAsync` methods on a worksheet, you must have permission to download data for the worksheet in Tableau Server. Ensure that your Tableau Server user account has the Download Summary Data and Download Full Data permissions for the workbook that contains the worksheet you want to download data for. #### getSummaryDataOptions Record

Name

Value

Description

ignoreAliases bool Do not use aliases specified in the data source in Tableau. Default is false.
ignoreSelection bool Only return data for the currently selected marks. Default is false.
maxRows int

The number of rows of data that you want to return. Enter 0 to return all rows.

#### getUnderlyingDataOptions Record

Name

Value

Description

ignoreAliases bool Do not use aliases specified in the data source in Tableau. Default is false.
ignoreSelection bool Only return data for the currently selected marks. Default is false.
includeAllColumns bool Return all the columns for the data source. Default is false.
maxRows int

The number of rows of data that you want to return. Enter 0 to return all rows.

### Dashboard Class Contains a collection of `DashboardObject` instances and a notion of the active object. #### Constructor There is no constructor. You get an instance of this from `Workbook.getActiveSheet()`. #### Properties

Name

Type

Description

getObjects()

DashboardObject[]

Gets the collection of objects.

getWorksheets()

Worksheet[]

Gets the collection of worksheets contained in the dashboard. Note that this is a helper method and is equivalent to looping through getObjects() and collecting all of the DashboardObject.Worksheet pointers when DashboardObject.getType() === tableau.DashboardObjectType.WORKSHEET.

getParentStoryPoint() StoryPoint Returns the StoryPoint object to which this Dashboard belongs (if it’s on a story sheet). Otherwise, it returns null. If the Dashboard instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
### DashboardObject Class Represents one of a series of different areas of the dashboard. #### Constructor There is no constructor. You get an instance of this from `Dashboard.getObjects()`. #### Properties

Name

Type

Description

getObjectType()

DashboardObjectType

Gets what the object represents, which is an enum with the following values: BLANK, WORKSHEET, QUICK_FILTER, PARAMETER_CONTROL, PAGE_FILTER, LEGEND, TITLE, TEXT, IMAGE, WEB_PAGE.

getDashboard()

Dashboard

Gets the Dashboard object that contains this object.

getWorksheet()

Worksheet

If getType() returns WORKSHEET, this contains a pointer to the Worksheet object.

getPosition()

Point

Gets the coordinates relative to the top-left corner of the dashboard of the object.

getSize()

Size

Gets the size of the object.

### Story Class Contains a collection of StoryPoint instances and the ability to switch between them. Derives from the Sheet class. #### Constructor There is no constructor. You get an instance of this from `Workbook.getActiveSheet()`. #### Properties (Derived from Sheet)

Name

Type

Description

getName()

string

Gets the name of the sheet.

getIndex()

int

Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published.

getIsActive()

bool

Gets a value indicating whether the sheet is the currently active sheet.

getIsHidden()

bool

Gets a value indicating whether the sheet is hidden in the UI. Note that if the entire tab control is hidden, it does not affect the state of this flag. This sheet may still report that it is visible even when the tabs control is hidden.

getSheetType()

SheetType

Gets the type of the sheet, which should always be tableau.SheetType.STORY.

getSize() SheetSize Gets the size information that the author specified when publishing the workbook.
getUrl() string Gets the URL for this sheet.
getWorkbook() Workbook Gets the Workbook to which this Sheet belongs.
#### Properties

Name

Type

Description

getStoryPointsInfo()

StoryPointInfo[]

Gets an array (not a collection) of StoryPointInfo objects. Note that this is not a collection, since we don’t have a unique string key for a story point. We only need ordinal access to the story points (by index).

getActiveStoryPoint() StoryPoint Gets the currently active story point.
#### Methods (Derived from Sheet)

Name

Type

Description

changeSizeAsync(size: SheetSize)

Promise<SheetSize>

Sets the size information on a sheet.

#### Methods

Name

Type

Description

activateStoryPointAsync(index: int)

Promise<StoryPoint>

Activates the story point at the specified index and returns a promise of the activated StoryPoint. Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.

activateNextStoryPointAsync() Promise<StoryPoint> Activates the next story point if there is one. If the current story point is the last one, then is stays active.
activatePreviousStoryPointAsync() Promise<StoryPoint> Activates the previous story point if there is one. If the current story point is the first one, then it stays active.
revertStoryPointAsync(index: int) Promise<StoryPoint> Reverts the story point at the specified index and returns a promise of the reverted StoryPoint. Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.
### StoryPointInfo Class Contains information about a `StoryPoint` with no methods. Returned as part of `Story.getStoryPointsInfo()`. #### Properties

Name

Type

Description

getIndex()

int

Gets the zero-based index of this story point within the parent Story sheet.

getCaption() string Gets the content of the textual description for this story point.
getIsActive() Bool Gets a value indicating whether the story point is the currently active point in the story.
getIsUpdated() Bool Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was “captured”.
getParentStory() Story Gets the Story object that contains the story point.
### StoryPoint Class A `StoryPoint` is a distinct snapshot within a `Story` sheet. #### Properties

Name

Type

Description

getIndex()

int

Gets the zero-based index of this story point within the parent Story sheet.

getCaption() string Gets the content of the textual description for this story point.
getIsActive() Bool Gets a value indicating whether the story point is the currently active point in the story.
getIsUpdated() Bool Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was “captured”.
getContainedSheet() Sheet Gets the sheet that this story point contains. This will be null if the story point does not have a contained sheet.
getParentStory() Story Gets the Story object that contains this story point.
## Parameter Classes ### Parameter Class Contains information about a workbook parameter. To actually set a parameter’s value, call `workbook.changeParameterValueAsync()`. #### Properties

Name

Type

Description

getName()

string

A unique identifier for the parameter, as specified by the user.

getCurrentValue()

DataValue

The current value of the parameter.

getDataType()

ParameterDataType

The data type of the parameter can be one of the following: FLOAT, INTEGER, STRING, BOOLEAN, DATE, DATETIME.

getAllowableValuesType()

ParameterAllowableValuesType

The type of allowable values that the parameter can accept. It can be one of the following enumeration items: ALL, LIST, RANGE.

getAllowableValues()

DataValue[]

If the parameter is restricted to a list of allowable values, this property contains the array of those values. Note that this is not a standard collection, but a JavaScript array.

getMinValue()

DataValue

If getAllowableValuesType is RANGE, this defines the minimum allowable value, inclusive. Otherwise it’s undefined/null.

getMaxValue()

DataValue

If getAllowableValuesType is RANGE, this defines the maximum allowable value, inclusive. Otherwise it’s undefined/null.

getStepSize()

Number

If getAllowableValuesType is RANGE, this defines the step size used in the parameter UI control slider. Otherwise it’s undefined/null.

getDateStepPeriod()

PeriodType

If getAllowableValuesType is RANGE and getDataType is DATE or DATETIME, this defines the step date period used in the Parameter UI control slider. Otherwise it’s undefined/null.

## Filtering There is a difference between querying existing filter state and setting new or existing filters. Querying filters is done via `Worksheet.getFiltersAsync()`, which returns a collection of `Filter` classes used in the worksheet, or by using `Dashboard.getFiltersAsync()`, which returns a collection of `Filter` classes used in the dashboard. Setting filters is done via `Worksheet.applyFilterAsync` (and its variants) and `Dashboard.applyFilterAsync`. These are function calls that don't require you to instantiate a `Filter` class. When you specify fields in a filter, you should use the caption as shown in the UI, not the database field name. For example, use **Container** (the caption) instead of **Product Container** (the actual field name). The exception is hierarchical filters, which use the full hierarchical name (for example, `[Product].[All Product].[Espresso]`). Captions can use the optional `[]` delimiters around names. ### Class Diagram ![](/tableau/next/en-us/api/js_api/en-us/Img/jsapi_filterclass.png) ### Dashboard Class (Filtering) This methods are on the `Dashboard` class, but are listed here for convenience. #### Methods

Name

Return Type

Description

getFiltersAsync()

Promise<Filter[]>

Fetches the collection of filters used on the dashboard.

applyFilterAsync(
fieldName: string,
values: object[] or object,
updateType: FilterUpdateType,
options?: FilterOptions)

Promise<string>

Applies a simple categorical filter (non-date) to the dashboard. This method is similar to the method used for worksheets, but applies the filter to all the worksheets in the dashboard that have that same field. Note that the filter is ignored by a worksheet if the worksheet doesn't have the relevant field in its data source. The method eturns the fieldName that was filtered.
See the filtering examples for more details on these functions.

For example:

dashboard.applyFilterAsync("Region", "Central", tableau.FilterUpdateType.REPLACE)

### Worksheet Class (Filtering) These methods are on the `Worksheet` class, but are listed here for convenience. #### Methods

Name

Return Type

Description

getFiltersAsync()

Promise<Filter[]>

Fetches the collection of filters used on the sheet.

applyFilterAsync(
fieldName: string,
values: object[] or object,
updateType: FilterUpdateType,
options?: FilterOptions)

Promise<string>

Applies a simple categorical filter (non-date). See the filtering examples for more details on these functions. Returns the fieldName that was filtered.

For example:

worksheet.applyFilterAsync("Product Type", "Coffee", tableau.FilterUpdateType.REPLACE)

applyRangeFilterAsync(
fieldName: string,
range: RangeFilterOptions)

Promise<string>

Applies a quantitative filter to a field or to a date. If a range is specified that is outside of the domain min/max values, no error is raised and the command is allowed. Subsequent calls to getFiltersAsync[] will return these values even if they are outside of the bounds of the domain. This is equivalent to the behavior in Tableau when you use the Filter dialog box for dimensions and measures.

You can also specify NullOption values as part of the RangeFilterOptions Record to include or exclude null values.

applyRelativeDateFilterAsync(
fieldName: string,
options: RelativeDateFilterOptions)
Promise<string> Applies a relative date filter.
applyHierarchicalFilterAsync(
fieldName: string,
values: object,
options: HierarchicalFilterOptions)
Promise<string> Applies a hierarchical filter. The values parameter is either a single value, an array of values, or an object { levels: ["1", "2"] }.
clearFilterAsync(fieldName: string) Promise<string> Clears the filter, no matter what kind of filter it is. Note that the filter is removed as long as no associated quick filter is showing for the field. If there is a quick filter showing, then the filter is kept, but it’s reset to the “All” state (effectually canceling the filter). For relative date filters, however, an error is returned since there is no “All” state for a relative date filter. To clear a relative date filter with a quick filter showing, you can call applyRelativeDateFilter() instead using a range that makes sense for the specific field.
### FilterOptions Record Passed into the `applyFilter` methods to control advanced filtering options. #### Fields

Name

Type

Description

isExcludeMode

bool

Determines whether the filter will apply in exclude mode or include mode. The default is include, which means that you use the fields as part of a filter. Exclude mode means that you include everything else except the specified fields.

### RangeFilterOptions Record Passed into the `applyRangeFilterAsync` method to control advanced filtering options. These options reflect the options for dimensions and measures as shown in the Filter dialog box in Tableau. #### Fields

Name

Type

Description

min

int or date

Minimum value for the range (inclusive). Optional. Leave blank if you want a <= filter.

max

int or date

Maximum value for the range (inclusive). Optional. Leave blank if you want a >= filter.

nullOption

NullOption

Specifies whether to include null values. The options are as follows.

To only include null values: tableauSoftware.NullOption.NULL_VALUES

To only include non-null values:  tableauSoftware.NullOption.NON_NULL_VALUES

To include all values, null and non-null:
tableauSoftware.NullOption.ALL_VALUES

**Examples:** ``` worksheet.applyRangeFilterAsync("SUM(Sales)", {min: 2000, max: 4000}); ``` ``` worksheet.applyRangeFilterAsync("Date", {min: new Date(Date.UTC(2010, 3, 1)), max: new Date(Date.UTC(2010, 12, 31))}); ``` ``` worksheet.applyRangeFilterAsync("AVG(Verbosity)", { min: "5.0", max: "10", nullOption: tableauSoftware.NullOption.ALL_VALUES }); ``` ``` worksheet.applyRangeFilterAsync("AVG(Verbosity)", {nullOption: tableauSoftware.NullOption.NON_NULL_VALUES }); ``` ### RelativeDateFilterOptions Record Passed into the `applyRelativeDateFilterAsync` method to control advanced filtering options. #### Fields

Name

Type

Description

anchorDate

Date

The UTC date from which to filter.

periodType

PeriodType

Year, quarter, month, etc.

rangeType

DateRangeType

LAST, LASTN, NEXT, etc.

rangeN

int

The number used when the rangeType is LASTN or NEXTN.

### Filter Class An abstract base class for all of the filter types. #### Properties

Name

Type

Description

getWorksheet()

Worksheet

Gets the parent worksheet

getFilterType()

FilterType

Gets the type of the filter. See FilterType Enum for the values in the enum.

getFieldName()

string

Gets the name of the field being filtered. Note that this is the caption as shown in the UI and not the actual database field name.

#### Methods

Name

Return Type

Description

getAppliedWorksheetsAsync()

Promise<string[]>

Gets the list of worksheets that have the filter applied.

getFieldAsync()

Promise<Field>

Gets the field that is currently being filtered.

setAppliedWorksheetsAsync(applyToWorksheets: string[] ) Promise<string[]> Applies the filter to the specified list of worksheets. If the worksheet(s) do not exist or do not contain the field in their data sources, an exception is thrown.
### NullOption Enum An enumeration that indicates what to do with null values for a given filter or mark selection call. #### **Enumeration**

Name

Description

NULL_VALUES

Only include null values in the filter.

NON_NULL_VALUES

Only include non-null values in the filter.

ALL_VALUES

Include null and non-null values in the filter.

### CategoricalFilter Class #### Properties

Name

Type

Description

getIsExcludeMode()

bool

Gets a value indicating whether the filter is exclude or include (default).

getAppliedValues()

DataValue[]

Gets the collection of values that are currently set on the filter. This is a native JavaScript array and not a keyed collection. If more than 5000 values are selected, only the first 200 are returned.

getIsAllSelected()

bool Gets a value indicating whether all values for the filter are selected. Returns true if all values in the filter are selected.
### QuantitativeFilter Class #### Properties

Name

Type

Description

getDomainMin()

DataValue

Gets the minimum value as specified in the domain.

getDomainMax()

DataValue

Gets the maximum value as specified in the domain.

getMin()

DataValue

Gets the minimum value, inclusive, applied to the filter.

getMax()

DataValue

Gets the maximum value, inclusive, applied to the filter.

getIncludeNullValues()

bool

Indicates whether null values are included in the filter.

### RelativeDateFilter Class #### Properties

Name

Type

Description

getPeriod()

PeriodType

The date period of the filter. See PeriodType Enum for the values in the enum.

getRange()

DateRangeType

The range of the date filter (years, months, etc.). See DateRangeType Enum for the values in the enum.

getRangeN()

int

When getRange returns LASTN or NEXTN, this is the N value (how many years, months, etc.).

### DataValue Record A DataValue contains both the raw and formatted value for a filter or parameter. Date values are always expressed in UTC dates. #### Fields

Name

Type

Description

value object Contains the raw native value as a JavaScript type, which is one of String, Number, Boolean, or Date

formattedValue

string

The value formatted according to the locale and the formatting applied to the field or parameter.

### FilterType Enum An enumeration of the valid types of filters that can be applied. #### **Enumeration**

Name

Description

CATEGORICAL

Categorical filters are used to filter to a set of values within the domain.

QUANTITATIVE

Quantitative filters are used to filter to a range of values from a continuous domain.

HIERARCHICAL

Hierarchical filters are used to filter to a set of values organized into a hierarchy within the domain.

RELATIVE_DATE

Relative date filters are used to filter a date/time domain to a range of values relative to a fixed point in time.

### FilterUpdateType Enum An enumeration of the valid types of filtering that can be done. #### **Enumeration**

Name

Description

ALL

Adds all values to the filter. Equivalent to checking the (All) value in a quick filter.

REPLACE

Replaces the current filter values with new ones specified in the call.

ADD

Adds the filter values as specified in the call to the current filter values. Equivalent to checking a value in a quick filter.

REMOVE

Removes the filter values as specified in the call from the current filter values. Equivalent to unchecking a value in a quick filter.

### PeriodType Enum An enumeration of a date period used in filters and in parameters. #### **Enumeration**

Name

YEARS

QUARTERS

MONTHS

WEEKS

DAYS

HOURS

MINUTES

SECONDS

### DateRangeType Enum An enumeration of the valid date ranges for a relative date filter. #### **Enumeration**

Name

Description

LAST

Refers to the last day, week, month, etc. of the date period.

LASTN

Refers to the last N days, weeks, months, etc. of the date period.

NEXT

Refers to the next day, week, month, etc. of the date period.

NEXTN

Refers to the next N days, weeks, months, etc. of the date period.

CURRENT

Refers to the current day, week, month, etc. of the date period.

TODATE

Refers to everything up to and including the current day, week, month, etc. of the date period.

## Marks Selection Selecting marks is almost identical to filtering. For filtering, you use one of the `Worksheet.applyFilterAsync()` methods. For selecting marks, you use `Worksheet.selectMarksAsync()`. The parameters for marks selection are almost identical to those used for filtering.This provides a very simple, easy to learn, and consistent way to accomplish the two most common use cases for the API: filtering and selection. ### Worksheet Class (Selecting Marks) These methods are on the `Worksheet class`, but are shown here for convenience. #### Methods

Name

Return Type

Description

clearSelectedMarksAsync()

void

Clears the selection for this worksheet.

getSelectedMarksAsync()

Promise<Mark[]>

Gets the collection of marks that are currently selected.

selectMarksAsync(
fieldName: string,
value: object or object[],
updateType: SelectionUpdateType)

void

Selects the marks and returns them.

For example, a single field (dimension) and value:


worksheet.selectMarksAsync("Product", "Mint", tableau.SelectionUpdateType.REPLACE);


Or single field and multiple values:


worksheet.selectMarksAsync("Product", ["Chamomile", "Mint"], tableau.SelectionUpdateType.REPLACE);

Or select marks based upon range:


sheet.selectMarksAsync( {"College": [ "Business", "Engineering" ], "Total Score": { min:1600, max:2300 } }, tableau.SelectionUpdateType.REPLACE );

selectMarksAsync(
fieldValuesMap: object,
updateType: SelectionUpdateType)

void

Allows selection based on this syntax for the first parameter:
{
"Field1": value,
"Field2": [1, 2, 3]
}

For example, selecting by product and state.


worksheet.selectMarks({"Product": ["Caffe Latte", "Caffe Mocha"],"State": ["California","Florida"]},tableauSoftware.FilterUpdateType.ADD);

For more examples of how you can use this method, see Selecting Marks and the Select Marks sample.

selectMarksAsync(
marks: Mark[],
updateType: SelectionUpdateType)

void

Selects an array of marks. See the Mark Class and the following example.

**Example of selectMarksAsync using the Mark class:** ``` (function (marks) { // filter out only the Washington and Oregon marks var onlyWashingtonAndOregon = []; for (var i = 0, len = marks.length; i < len; i++) { var m = marks[i]; var pair = m.getPairs().get("State"); if (pair && (pair.value === "Washington" || pair.value === "Oregon")) { onlyWashingtonAndOregon.push(m); } } return worksheet.selectMarksAsync( onlyWashingtonAndOregon, tableau.SelectionUpdateType.REPLACE); }) ``` ### Mark Class A mark represents a single data point on the visualization. It is independent of the type of visualization (bar, line, pie, etc.). #### Constructor

Signature

Description

Mark(pairs: Pair[])

Creates a new Mark with the specified pairs.

#### Properties

Name

Type

Description

getPairs()

Pair[]

Gets a collection of field name/value pairs associated with the mark.

### Pair Class A pair contains a field name and a value (both the raw and formatted values). #### Constructor

Signature

Description

Pair(fieldName: string, value: object)

Creates a new Pair with the specified field name/value pairing

#### Fields

Name

Type

Description

fieldName string The field name to which the value is applied.
value object Contains the raw native value for the field as a JavaScript type, which is one of String, Number, Boolean, or Date.

formattedValue

string

The value formatted according to the locale and the formatting applied to the field.

### SelectionUpdateType Enum An enumeration of the valid types of marks selection that can be done. #### **Enumeration**

Name

Description

REPLACE

Replaces the current marks values with new ones specified in the call.

ADD

Adds the values as specified in the call to the current selection. Equivalent to control-clicking in desktop.

REMOVE

Removes the values as specified in the call from the current selection. Equivalent to control-clicking an already selected mark in desktop.

## Other Classes ### Size Record Represents a width and height in pixels. This is implemented as a plain JavaScript object (it’s not a class). #### Fields

Name

Type

Description

width

int

Expressed in pixel units.

height

int

Expressed in pixel units.

### Point Record Represents an x/y coordinate in pixels. This is implemented as a plain JavaScript object (it’s not a class). #### Fields

Name

Type

Description

x

int

Expressed in pixel units.

y

int

Expressed in pixel units.

### ContextMenuOptions Class Represents the options for the menu item that appears in the custom context menu. You can use the context menu to run commands outside of Tableau. Fields

Name

Type

Description

displayName

string

The name of the custom menu item as you want it to appear in Tableau.

### ApiMenuType Enum Represents the location of a context menu where users can add external menu items. Fields

Name

Type

Description

Ubertip

string

The custom menu item will appear in the marks selection tooltip (also known as an "ubertip").

[Skip to main content](#main-content) # Basic Embed **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Embed a visualization in a `div` element. * * * ``` Basic Embed
``` [Skip to main content](#main-content) # Concepts **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). This section provides background information about how to use the Tableau JavaScript API and how it works. ## Other articles in this section [Skip to main content](#main-content) # Dynamic Load **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Dynamically load and remove visualizations. Click the Previous and Next buttons to display other visualizations in a predefined list. Previous Next * * * ``` Dynamic Load
``` [Skip to main content](#main-content) # Export **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Export the current visualization. This sample show how you can export the visualization in different formats: as a PDF file, as an image file, as a CSV file, as an Excel file, or as a PowerPoint file. You can also open the Download dialog box to let the user choose. Export to PDF Export to Excel Export to CSV Export to Image Export to PowerPoint Show Download Dialog * * * ``` Export
``` [Skip to main content](#main-content) # Filter **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Apply a filter to a visualization using controls on the page. Year: All20132014 * * * ``` Filter
Year:
``` [Skip to main content](#main-content) # Get Data **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Get the underlying data for the currently active sheet. To download data for a workbook, your Tableau Server user account must have the Download Summary Data and Download Full Data permissions. Get Data * * * ``` getData() Basic Example
``` [Skip to main content](#main-content) # Requirements **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). The requirements for the Tableau JavaScript API are as follows: **Access to a Tableau server:** To program with the Tableau JavaScript API you need to have access to Tableau Server, Tableau Cloud, or Tableau Public, and a published workbook on that server. Your web application shouldn’t be on the same computer as the server, but it needs to be able to access the server. For information about the API and accessing it, see [Concepts](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_concepts.htm). **A supported browser:** Your end-users can experience the web application you create in most web browsers supported by [Tableau Server](https://www.tableau.com/products/techspecs#server) and [Tableau Cloud](https://www.tableau.com/products/techspecs#online). [Skip to main content](#main-content) # Resize **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Resize a visualization to a size that you specify. Worksheets automatically resize to fill the `div` container for the visualization. However, dashboards and stories do not resize automatically unless you create them with the automatic size option in Tableau Desktop. Scroll down to see how to change the size of a visualization that contains a dashboard or story. Resize * * * ``` Resizing
``` To change the size of a visualization that contains a dashboard or story, use the following function instead. ``` function vizResize() { var width = document.getElementById("resizeWidth").value; var height = document.getElementById("resizeHeight").value; var sheet = viz.getWorkbook().getActiveSheet(); sheet.changeSizeAsync( {"behavior": "EXACTLY", "maxSize": { "height": height, "width": width }}) .then(viz.setFrameSize(parseInt(width, 10), parseInt(height, 10))); } ``` [Skip to main content](#main-content) # Respond to Events **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Display information about marks as you select them. Information about selected marks displays here. * * * ``` Respond to Events

Information about selected marks displays here.
``` [Skip to main content](#main-content) # Samples **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). View a list of JavaScript API samples below. Feel free to copy, modify, and redistribute the code in these samples. **Note**: Tableau does not provide support for programs that customers create that use the Tableau JavaScript API. For help with your code, submit questions and ask for help on the Tableau developer community forums. Tableau does provide support for potential bugs in the Tableau JavaScript API code itself, and for unmodified sample code that isn't working. ## Other articles in this section [Skip to main content](#main-content) # Select Marks **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Select a set of marks in a visualization. Select marks Add to the selection Clear all * * * ``` Select Marks

``` [Skip to main content](#main-content) # Tableau JavaScript API > [!WARNING] > > **Important changes for the Tableau JavaScript API** > As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. The Embedding API v3 improves upon the previous library by offering features you expect for modern JavaScript development, including support for ES6 modules, web components, and availability as an NPM package. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). For information about switching from an older version of the Embedding API, see [Upgrade from Tableau JavaScript API v1 and v2](https://help.tableau.com/current/api/embedding_api/en-us/docs/embedding_api_migration_guide.html). You can embed interactive Tableau views into web pages, blogs, wiki pages, web applications, and intranet portals. Embedded views update as the underlying data changes, or as their workbooks are updated on Tableau Server or Tableau Cloud. Use the Tableau JavaScript API to integrate Tableau visualizations into your own web applications. Here are some of the things that you can do with the JavaScript API: - Display visualizations from Tableau Server, Tableau Public, and Tableau Cloud in web pages. - Dynamically load and resize visualizations. - Filter the data displayed in visualizations with HTML controls in the page. - Select marks in visualizations. - Respond to events in visualizations. - Export visualizations to an image or PDF file. For information on the latest features of the JavaScript API, see [What's New in the JavaScript API](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_whats_new.htm). ## Get Started 1. Create a web page and include the JavaScript API file from the Tableau Server that hosts your visualizations: ``` ``` 2. Create a `div` element in the page `body` where you want to insert the Tableau visualization: ```
``` 3. Write a function in a JavaScript file to display the visualization: ``` function initViz() { var containerDiv = document.getElementById("vizContainer"), url = "https://YOUR-SERVER/views/YOUR-VISUALIZATION"; var viz = new tableau.Viz(containerDiv, url); } ``` 4. Call the function when the page is done loading: ``` initViz(); ``` The result is below. To view the full code sample, see [Basic Embed](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_sample_basic_embed.htm). [Skip to main content](#main-content) # Access the API **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). The JavaScript API runs on Tableau Cloud, Tableau Public, and Tableau Server versions 10.5 and later. To use the JavaScript API, you need to include the JavaScript API file in your web page. The JavaScript API files are located on the server (including Tableau Cloud and Tableau Public). There is no separate download for the files. You just specify the URL to the JavaScript API file in your web page, as described in the following section. The JavaScript API file is a library that contains functions for interacting with the JavaScript API. The JavaScript API file is available in multiple versions, and each version of the Tableau JavaScript library corresponds to a specific version of Tableau Server. Additionally, for each version of the JavaScript API file, there is also a minified file that you can use in production environments to reduce the amount of data that browsers need to download. ## JavaScript API Versions The following table lists the JavaScript API library files and the corresponding versions of Tableau Server. For compatibility, you should use the version of the library that matches the version of Tableau you are using. | Tableau Server version | JavaScript API files | | --- | --- | | 2022.1 | `tableau-2.9.1.min.js`. | | 2021.4 | `tableau-2.9.0.min.js` | | 2021.3 | `tableau-2.8.3.min.js` | | 2021.2 | `tableau-2.8.2.min.js` | | 2021.1 | `tableau-2.8.0.min.js` | | 2020.4 | `tableau-2.7.0.min.js` | | 2020.3 | `tableau-2.6.0.min.js` | | 2020.2 | `tableau-2.5.0.min.js` | | 2020.1 | `tableau-2.4.0.min.js` | | 2019.4 | `tableau-2.3.0.min.js` | | 2019.3 | `tableau-2.3.0.min.js` | | 2019.2 | `tableau-2.2.2.min.js` | | 2019.1 | `tableau-2.2.2.min.js` | | 2018.3 | `tableau-2.2.2.min.js` | | 2018.2 | `tableau-2.2.2.min.js` | | 2018.1 | `tableau-2.2.2.min.js` | | 10.5 | `tableau-2.2.1.min.js` | For Tableau Cloud and Tableau Public, use the latest version of the JavaScript API file. ### Versioning Notes - Starting with Tableau Server 9.1, you can link to the JavaScript API file using only the major version number. Tableau Server returns the latest minor version of the JavaScript API file available. For example, if you link to the `tableau-2.js` file on Tableau Server 2020.1, Tableau Server returns the `tableau-2.4.0.js` file. Use the major version of the file to avoid updating code references for minor version changes. However, you can still get a specific minor version of the JavaScript API file by linking to it directly. - The version numbers for JavaScript API files has changed since the first release. Starting with Tableau Server 9.0, the version of the JavaScript API file is independent of the Tableau Server version. Each version uses the following convention: `tableau_major-release.minor-release.update-release.js` Previously, JavaScript API file versions matched the version of Tableau Server. For example, the `tableau_v8.js` file corresponded to Tableau Server 8.0. - Starting with Tableau Server 9.0, you can get the JavaScript API file from any location, including your own server, Tableau Public, and Tableau Cloud. JavaScript API files in all these locations are identical for a given version of the JavaScript API file. Use the version of the JavaScript API that corresponds to the version of Tableau Server you are on. The easiest way to make sure you're using the correct version is to use the JavaScript API library from the Server you are using. - Starting with Tableau Server 9.0, minified versions of the JavaScript API file are designated with the `.min` naming convention. Previously, the minified version did not use a naming convention. Instead, the full version of the file was designated with the `.debug` naming convention. - You can access non-minified versions of the library by removing `.min` from the filename. For example, for the latest version, you can use `tableau-2.js` ## Where to Get the JavaScript API File Starting with Tableau Server version 9.0, you can get the JavaScript API file from multiple locations, including Tableau Cloud and Tableau Public. However, if you get the JavaScript API file from the same server that hosts your visualizations, you can ensure that you always use a version of the file that is compatible with the server. Additionally, for versions of Tableau Server before 9.0, you must get the JavaScript API file from the same server that hosts your visualizations. Otherwise, the code may not work. Add the following code to a web page to get the JavaScript API file: ``` ``` For example, you might enter the following code: ``` ``` For Tableau Cloud and Tableau Public, enter one of the following: ``` ``` ``` ``` On Tableau Server, the JavaScript API files are stored in the following location: `Program Files\Tableau\Tableau Server\2022.4\wgserver\public\javascripts\api` [Skip to main content](#main-content) # Behavior of Asynchronous Calls **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). By default, calls are asynchronous since many of them may require a roundtrip to the server. Methods use the following naming convention: - Asynchronous calls are indicated by an `Async` suffix on the method name, for example, `Worksheet.applyFilterAsync()`. - Asynchronous calls return a `Promise` object, allowing chaining. The Tableau JavaScript API uses the [CommonJS Promises/A standard](http://wiki.commonjs.org/wiki/Promises/A). The premise behind Tableau's implementation is that asynchronous methods return an object that has a `then` method in the following form: ``` .then(fulfilledHandler, errorHandler) ``` The `fulfilledHandler` is called when the promise is fulfilled (on success). The `errorHandler` is called when a promise fails. All arguments are optional and non-function values are ignored. ## Chaining Promises The promised result of an asynchronous method is passed as the parameter to the next `then()` method. For example: ``` var activeSheet; viz.getWorkbook().activateSheetAsync("Sheet 1") .then(selectLemon).then(filterToLemonAndMint); function selectLemon(sheet) { activeSheet = sheet; return sheet.selectMarksAsync("Product", "Lemon", "replace"); } function filterToLemonAndMint() { return activeSheet.applyFilterAsync("Product", ["Lemon", "Mint"], "replace"); } ``` The result of `activateSheetAsync()` is a promise to eventually return the `Sheet` object that was activated, which is passed as the first parameter to the `selectLemon()` method. Notice that the `selectLemon()` method returns a `Promise` object (the return value of the `selectMarksAsync()` method), not the result after the marks have been selected. However, since it's a `Promise` object, the next `then()` method is not called until that promise is fulfilled. If a link in the chain is added after the promise has been fulfilled, the callback will be immediately called with the value that was previously returned. As the programmer, this means you don't need to determine if the response has already been received from the server. The asynchronous methods will always be called, whether it's now or later. ``` var promise = viz.getWorkbook().activateSheetAsync("Sheet 1"); // Pretend that activatSheeteAsync() has already returned from the server. promise.then(callback); // callback will be called immediately using the Sheet object // returned from activateSheetAsync() ``` ## Return Values of Then() Methods Whatever is returned in a `then()` method will get passed as the first parameter to the next `then()` method. It can be a scalar value (`Number`, `Boolean`, `String`, etc.), an object, or another `Promise`. The infrastructure will automatically wrap non-`Promise` values into a `Promise` value so that they can be chained. ``` viz.getWorkbook().activateSheetAsync("Sheet 1") .then(function (sheet) { return "First link"; }) .then(function (message) { if (message === "First link") { alert("Expected"); } // no return value here means nothing is passed to the next link }) .then(function () { }); ``` ## Breaking Out of a Chain Technically, there's no way to break out of a chain since that would invalidate the guarantee that subsequent links in the chain will be called. If there is an exception thrown in part of the chain, the rest of the chain is run but the `errorHandler` is called instead of the `fulfilledHandler`. If a link in the chain depends on the results of earlier links, then you should write an `if` statement to check your condition. Here's an example: ``` viz.getWorkbook().activateSheetAsync("Sheet 1") .then(function (sheet) { // I'm returning a Promise return sheet.selectMarksAsync("Product", "NoProduct", "replace"); }) .then(function () { return viz.getWorkbook().getActiveSheet().getSelectedMarksAsync(); }) .then(function (marks) { // The getSelectedMarksAsync call succeeded, but no marks were selected // because there are not any marks corresponding to "NoProduct". if (marks.length === 0) { throw new Error("No marks selected"); } var firstMarkValue = marks[0].getPairs().get("Product").value; return sheet.applyFilterAsync("Product", firstMarkValue, "replace"); }) .then(function (filterName) { // applyFilterAsync succeeded }, function(err) { if (err.message === "No marks selected") { alert("This was caused by the first link above"); } }) .otherwise(function (err) { alert("We handled the error above, so it's not propagated to this handler."); }); ``` If a callback is not provided (or is null or undefined), then the results are passed to the next link in the chain: ``` viz.getWorkbook().activateSheetAsync("Sheet 1") .then() .then(function (sheet) { // this is called }); ``` In this way, you can specify a single `otherwise` function to handle all errors in the chain. The `always` function works the same way, but it is called regardless of success or failure. The `then/otherwise/always` functions work similarly to a `try/catch/finally` block. ``` viz.getWorkbook().activateSheetAsync("Sheet 1") .then(function () { return sheet.selectMarksAsync(...); }) .then(function (marks) { // Do something with the marks. }) .otherwise(function (err) { // I'm handling all errors in one place. console.log(err.message); }) .always(function () { // Do some cleanup or logging }); ``` [Skip to main content](#main-content) # Authentication **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). The normal authentication protocol applies for accessing views on a server. If your code is getting a view from Tableau Public, no authentication is required. However, if your code is getting a view from a hosted instance of Tableau Server, authentication is typically required. If the user is not already signed in to the server, Tableau Server redirects the request for a view to the server sign in page, and the user must provide a username and password. After the user has signed in, the browser caches session information, and the user doesn't have to sign in again unless he or she has explicitly signed out of the server, or until the session token expires. ## Trusted Authentication If you are working with Tableau Server, and if the server is configured to [use trusted authentication](https://help.tableau.com/current/server/en-us/help.htm#trusted_auth.htm), specify the ticket in the URL by first adding `trusted` after the server name, followed by the ticket. For example: ``` var placeholderDiv = document.getElementById("tableauViz"); var url = "http://tabserver/trusted/Etdpsm_Ew6rJY-9kRrALjauU/views/workbookname/viewname"; var options = { hideTabs: true, width: "800px", height: "700px" }; var viz = new tableau.Viz(placeholderDiv, url, options); ``` Trusted Authentication is not used with Tableau Cloud. [Skip to main content](#main-content) # Collections **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Many classes have collections of items, where each item has a key (typically an ID or a name). Examples include a collection of sheets keyed by name or the list of parameters on a sheet keyed by name. Collections are publicly immutable, exposing read-only functionality. Each Collection array is keyed with its elements' identifiers. For example, the result of `Workbook.getPublishedSheetsInfo()` is an array with the index corresponding to the position of the sheet in the workbook. ``` var sheet = workbook.getPublishedSheetsInfo()[0]; ``` It is also keyed by the sheet name so that you can access it like this: ``` var sameSheet = workbook.getPublishedSheetsInfo().get("Sheet 1"); ``` ## Collection Interface

Name

Return Type Description

get(key : string)

Collection item type

Gets the element in the collection associated with the key, or undefined if there is nothing associated with it.

has(key : string)

bool

Returns true if there is an element in the collection associated with the key; otherwise, false.

[Skip to main content](#main-content) # Events **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). The `Viz` class acts as the central event hub. This way you only have to go to one place for all events. It also means that events can be raised on an object that may not have been created yet. For example, the `marksselection` event can be raised for a particular sheet even though the `Sheet` object hasn't been created yet. Each event contains an anonymous object with information pertaining to that event, such as the sheet the event occurred on. Listening to an event is done by calling `Viz.addEventListener(type, callback)` and passing in a function callback. Here's an example of listening to an event: ``` viz.addEventListener("marksSelection", function (marks) { changeMySelectionUI(marks); }); ``` Removing a listener is done by calling `Viz.removeEventListener(type, listener)` and passing in the same callback function that was passed into `Viz.addEventListener()`. For example: ``` function changeMySelectionUI(marks) { viz.removeEventListener("marksSelection", changeMySelectionUI); } viz.addEventListener("marksSelection", changeMySelectionUI); ``` Events are multicast delegates, meaning that multiple listeners are supported. The order in which notifications are called is not specified. Every event callback takes a single object containing a pointer to the `Viz` that raised the event. Each event also adds additional fields to the event, as specified in the [API Reference](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm). [Skip to main content](#main-content) # Filtering **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Apply filters to display a subset of the data available for a view. You can either apply filters before a visualization has been loaded or after. When you specify fields in a filter, you should use the caption as shown in the user interface, not the database field name. In some cases, Tableau Desktop renames fields after they've been dragged to a shelf. For example the **Date** field might be renamed to **YEAR(Date)** after being dragged to the rows shelf. In this case, you should use **YEAR(Date)** as the parameter. The exception is hierarchical filters, which use the full hierarchical name (for example, `[Product].[All Product].[Espresso]`). Captions can use the optional `[]` delimiters around names. ## Apply Filters Before Loading the Visualization To apply filters before a visualization has loaded, specify the filters as options during initialization. For example, if you have a filter named **Container** and you only want to view data for **Boxes**, then you might use the following code to initialize the visualization: ``` var containerDiv = document.getElementById("vizContainer"), url = "http://YOUR-SERVER/views/YOUR-VIEW", options = { "Container": "Boxes" }; viz = new tableau.Viz(containerDiv, url, options); ``` ## Apply Filters After Loading the Visualization Use the `applyFilterAsync` function to apply filters after your visualization has loaded. You can use the following code to filter a single value: ``` worksheet.applyFilterAsync("Container", "Boxes", tableau.FilterUpdateType.REPLACE); ``` There is a difference between querying existing filter state and setting new or existing filters. Querying filters is done via `Worksheet.getFiltersAsync()`, which returns a collection of `Filter` classes, or by using `Dashboard.getFiltersAsync()`, which returns a collection of `Filter` classes used in the dashboard. Setting filters is done via `Worksheet.applyFilterAsync`(and its variants) and and `Dashboard.applyFilterAsync`. These are function calls that don't require you to instantiate a `Filter` class. Here are examples of several types of filtering: ``` var worksheet; viz.getWorkbook().activateSheetAsync("Sheet 4").then(function (sheet) { worksheet = sheet; }) // Single value .then(function () { return worksheet.applyFilterAsync("Product Type", "Coffee", tableau.FilterUpdateType.REPLACE); }) // Multiple values .then(function () { return worksheet.applyFilterAsync( "Product Type", ["Coffee", "Tea"], tableau.FilterUpdateType.REPLACE); }) // Multiple Values - adding and removing .then(function () { return worksheet.applyFilterAsync("Product", ["Lemon", "Mint"], tableau.FilterUpdateType.ADD); }) .then(function () { return worksheet.applyFilterAsync("Product", ["Caffe Latte", "Green Tea"], tableau.FilterUpdateType.REMOVE); }) // All values .then(function () { return worksheet.applyFilterAsync("Product Type", "", tableau.FilterUpdateType.ALL); }) // Date Range .then(function () { return worksheet.applyRangeFilterAsync("Date", { min: new Date(Date.UTC(2010, 3, 1)), max: new Date(Date.UTC(2010, 12, 31)) }); }) // Clearing a Filter .then(function () { return worksheet.clearFilterAsync("Date"); }) // Relative Date .then(function () { return worksheet.applyRelativeDateFilterAsync("Date", { anchorDate: new Date(Date.UTC(2011, 5, 1)), periodType: tableau.PeriodType.YEAR, rangeType: tableau.DateRangeType.LASTN, rangeN: 1 }); }) // Quantitative Filters // SUM(Sales) > 2000 and SUM(Sales) < 4000 .then(function () { return worksheet.applyRangeFilterAsync("SUM(Sales)", { min: 2000, max: 4000 }); }) // SUM(Sales) > 1000 .then(function () { return worksheet.applyRangeFilterAsync("SUM(Sales)", { min: 1000 }); }) // SUM(Sales) < 1000, excluding null values .then(function () { return worksheet.applyRangeFilterAsync("SUM(Sales)", { max: 1000, nullOption: tableauSoftware.NullOption.NON_NULL_VALUES }); }) // Hierarchical Filters - selecting all on a level .then(function () { return worksheet.applyHierarchicalFilterAsync("[Product].[Product Categories]", { levels: [0, 1] }, tableau.FilterUpdateType.ADD); }, function (err) { /* ignore errors */ }) // Hierarchical Filters - adding one item .then(function () { return worksheet.applyHierarchicalFilterAsync( "[Product].[Product Categories].[Product Name]", "Accessories.Bike Racks.Hitch Rack - 4-Bike", tableau.FilterUpdateType.REPLACE); }, function (err) { /* ignore errors */ }) // Hierarchical Filters - adding multiple items .then(function () { return worksheet.applyHierarchicalFilterAsync( "[Product].[Product Categories].[Product Name]", [ "Accessories.Bike Racks.Hitch Rack - 4-Bike", "Accessories.Bike Stands.All-Purpose Bike Stand" ], tableau.FilterUpdateType.REPLACE); }, function (err) { /* ignore errors */ }) .otherwise(function (err) { console.log(err); }); ``` [Skip to main content](#main-content) # Initialize the API **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). The Tableau JavaScript API uses an object model. The entry point into the object model is to instantiate a new `Viz` object as follows: ``` var viz = new tableau.Viz( /* params omitted */ ); ``` For most Tableau objects you can navigate back to the object's parent by means of parent properties. ## Create a Viz Object There is only one entry point into the API: instantiating a new `Viz` object, which creates the HTML necessary to embed a Tableau visualization. To instantiate a new `Viz` object, call the `Viz` constructor and pass a reference to the div container on the HTML page, the URL of the visualization on Tableau Server, and a set of options. ``` var placeholderDiv = document.getElementById("tableauViz"); var url = "http://my-server/views/my-workbook/my-view"; var options = { hideTabs: true, width: "800px", height: "700px", onFirstInteractive: function() { // The viz is now ready and can be safely used. } }; var viz = new tableau.Viz(placeholderDiv, url, options); ``` ## Get the visualization URL Not sure where to get the visualization URL? Navigate to your visualization on Tableau Server and then edit the URL from this: http://my-server/#/views/my-workbook/my-view To this: http://my-server/views/my-workbook/my-view If you do not remove the `#` symbol from the URL, you might see the following browser error: Refused to display `'http://my-server/#/views/my-workbook/my-view'` in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. ## Specify Options When you initialize a `Viz` object, you can pass options that specify how the view is initially rendered. The following list describes some of the some of the types of options that you can specify: - Set a width and height for the visualization. - Show or hide the toolbar and tabs. - Apply filters. - Call a callback function when the visualization becomes interactive or when the width and height are known. For a full reference of the options that you can specify, see the [VizCreateOptions](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#vizcreateoptions_record) record of the `Viz` constructor. ## Copy (Clone) an Existing Instance When you initialize a `Viz` object, you can specify that the new instance should be copied (cloned) from an existing instance. This is useful if a user is working with a visualization but wants to try some new options or filters without affecting the state of the original visualization. To clone an instance, you specify the `instanceIdToClone` option in the [VizCreateOptions](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#vizcreateoptions_record) record for the `Viz` constructor. The cloned instance is assigned a new ID. The following example shows how you can use this option. ``` function clone(instanceId) { var url = "http://MY-SERVER/views/clone/demo"; var newVizElement = $('
') .appendTo('.content'); var viz = new tableau.Viz(newVizElement[0], url, { instanceIdToClone: instanceId, usePublishedSize: true, hideToolbar: true }); newVizElement.find('button').click(function() { clone(viz.getInstanceId())}); } $(function() { clone(0); }); ``` ## Get Notification When the Viz Object is Ready One of the options you can pass when you instantiate a `Viz` object is the `onFirstInteractive` parameter. This parameter references a callback function that's invoked when the `Viz` object has finished instantiating. This is an asynchronous callback, so your code can continue to run while the `Viz` object is instantiating. The state of the `Viz` object is not valid until after the `onFirstInteractive` function is called. If you want to perform operations on the `Viz` object that require it to be fully initialized (for example, counting the number of sheets in the workbook), run your code after the `onFirstInteractive` callback has been invoked, like this: ``` var viz; var options = { hideTabs: true, onFirstInteractive: function () { var sheetCount = viz.getWorkbook().getPublishedSheetsInfo().length; }; viz = new tableau.Viz(div, url, options); ``` Some operations that you might do with the `Viz` object do not require it to be completely initialized, such as adding event listeners to a `Viz` object. In those cases, you don't need to wait until the `onFirstInteractive` callback in order to run code to add the listeners. The following example shows code that adds a listener for the event that occurs when marks are selected. Notice that the code can run right after the `Viz` object initialization code, and doesn't need to be in the `onFirstInteractive` function. ``` var viz = new tableau.Viz(...); viz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, function (e) { // do something with the marks }); ``` [Skip to main content](#main-content) # Property Getters and Setters **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Getters and setters are always functions that start with `get` or `set`. They can be called multiple times with little performance impact (in other words, they should simply return cached fields or do very simple calculations). Properties are always synchronous and return immediately with the value, rather than having a callback function. [Skip to main content](#main-content) # Selecting Marks **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). Selecting marks is almost identical to filtering. For filtering,you use one of the `Worksheet.applyFilterAsync()` methods. For selecting marks, you use `Worksheet.selectMarksAsync()`. The parameters for mark selection are almost identical to those used for filtering. ``` worksheet.selectMarksAsync("Product", "Caffe Latte", tableau.SelectionUpdateType.REPLACE); ``` Here are samples of other types of selecting you can use: ``` var worksheet; viz.getWorkbook().activateSheetAsync("Sheet 4").then(function (sheet) { worksheet = sheet; }) // Single dimensions work just like filtering // Single dimension - single value .then(function () { return worksheet.selectMarksAsync("Product", "Mint", tableau.SelectionUpdateType.REPLACE); }) // Single dimension - Multiple values .then(function () { return worksheet.selectMarksAsync( "Product", ["Chamomile", "Mint"], tableau.SelectionUpdateType.REPLACE); }) // Single dimension - Multiple values (delta) .then(function () { return worksheet.selectMarksAsync("Product", ["Lemon", "Earl Grey"], tableau.SelectionUpdateType.ADD); }) .then(function () { return worksheet.selectMarksAsync( "Product", ["Chamomile", "Earl Grey"], tableau.SelectionUpdateType.REMOVE); }) // Quantitative selection .then(function () { return worksheet.selectMarksAsync({ "State": ["Florida", "Missouri"], "SUM(Sales)": { min: 3000, max: 4000 } }, tableau.SelectionUpdateType.REPLACE); }) // Hierarchical dimensions .then(function () { return worksheet.selectMarksAsync( "[Product].[Product Categories].[Category]", "Bikes", tableau.SelectionUpdateType.REPLACE); }, function (err) { /* ignore errors */ }) // Multiple dimensions - multiple values // ((State = Washington OR Oregon) AND Product = Lemon) // OR // (State = Oregon AND Product = Chamomile) .then(function () { return worksheet.selectMarksAsync({ "State": ["Washington", "Oregon"], "Product": "Lemon" }, tableau.SelectionUpdateType.REPLACE); }) .then(function () { return worksheet.selectMarksAsync({ "State": "Oregon", "Product": "Chamomile" }, tableau.SelectionUpdateType.ADD); }) // Round-tripping selection .then(function () { return worksheet.selectMarksAsync( "Product", "Lemon", tableau.SelectionUpdateType.REPLACE); }) .then(function () { return worksheet.getSelectedMarksAsync(); }).then(function (marks) { // filter out only the Washington and Oregon marks var onlyWashingtonAndOregon = []; for (var i = 0, len = marks.length; i < len; i++) { var m = marks[i]; var pair = m.getPairs().get("State"); if (pair && (pair.value === "Washington" || pair.value === "Oregon")) { onlyWashingtonAndOregon.push(m); } } return worksheet.selectMarksAsync( onlyWashingtonAndOregon, tableau.SelectionUpdateType.REPLACE); }) .otherwise(function (err) { console.log(err); }); ``` [Skip to main content](#main-content) # What's New in the JavaScript API **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). ## Changes in the JavaScript API for Tableau 2022.1 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2022.1. JavaScript API version: `tableau-2.9.1.min.js`. - Bug fixes. ## Changes in the JavaScript API for Tableau 2021.4 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2021.4. JavaScript API version: `tableau-2.9.0.min.js`. - Bug fixes. - Added the `AppendContextMenuAsync`, `RemoveContextMenuAsync`, and `ExecuteContextMenuAsync` methods and `ContextMenuOptions` to support adding custom commands to the Uber tooltip (the tooltip that appears when marks are selected). - Added a new event type (`CustomMarkContextMenuEvent`) that is raised when a custom context menu item is selected. You can provide a _CustomMarkContextMenuEventHandler_ to handle the event and trigger the custom action. ## Changes in the JavaScript API for Tableau 2021.3 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2021.3. JavaScript API version: `tableau-2.8.3.min.js`. Fixed a defect that could cause an error message to appear when applying an Ask Data Lens (`Uncaught TypeError: bn.handleVizListening` is not a function" and `Uncaught TypeError: bn.handleVizLoad`. ## Changes in the JavaScript API for Tableau 2021.2 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2021.2. JavaScript API version: `tableau-2.8.2.min.js`. Bug fixes. ## Changes in the JavaScript API for Tableau 2021.1 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2021.1. JavaScript API version: `tableau-2.8.0.min.js`. You can now open the Download dialog box using the `viz.showDownloadDialog` method. For an example, see the [Export](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_sample_export_to_pdf.htm) sample. ## Changes in the JavaScript API for Tableau 2020.4 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2020.4. JavaScript API version: `tableau-2.7.0.min.js`. You can now apply filters to dashboards, in addition to worksheets. To support dashboard filtering, the JavaScript API provides the following new methods: `Dashboard.applyFilterAsync`, `Dashboard.getFiltersAsync`, `Filter.getAppliedWorksheetsAsync`, `Filter.setAppliedWorksheetsAsync`. ## Changes in the JavaScript API for Tableau 2020.3 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2020.3. JavaScript API version: `tableau-2.6.0.min.js`. - To support the ability to export the crosstab data from a worksheet directly to Excel, the JavaScript API added the `exportCrossTabToExcel` method. This method performs the same function as the **Worksheet > Export > Crosstab to Excel** operation in Tableau. The method generates the `.xlsx` file and downloads it to your default location. - The `applyRangeFilterAsync` method now correctly supports `NullOption` enumeration. The method supports the equivalent functions of the Filter dialog box for dimensions or measures. You can include or exclude null values from a range, or set a special filter for all null or non-null values. - The `GetFiltersAsync` method, now correctly checks for the **Only Relevant Values** option when evaluating other filter settings that might be set, and returns only the values that pass those filters. The method now accurately returns all the filters used in a sheet. - When a Tableau view is embedded in a Salesforce org page, the drop-down menus in the view now work as expected. - When you click column or row headers in an embedded Tableau view, selection events now fire correctly. ## Changes in the JavaScript API for Tableau 2020.2 This section lists the changes that were made for the version of the JavaScript API that ships with Tableau 2020.2. JavaScript API version: `tableau-2.5.0.min.js`. - To support the [Tableau Data Model](https://help.tableau.com/current/pro/desktop/en-us/datasource_datamodel.htm) introduced in Tableau 2020.2, the Tableau JavaScript API provides new APIs and data structures that support the logical and physical tables in the data model. Use these new methods to get the underlying data from worksheets. The new methods replace `getUnderlyingDataAsync`. Starting in Tableau 2020.2, a data source can have multiple logical tables, and a logical table can contain one or more physical tables. If you have an existing embedding solution that use the deprecated `getUnderlyingDataAsync()` method to get underlying data, the method call could fail if the data source contains more than one logical table. You should update your embedding solution to use these new methods. | Interface/Method | Tableau 2020.2 and later | | --- | --- | | Worksheet.getUnderlyingDataAsync | Deprecated | | Worksheet.getUnderlyingTablesAsync | New | | Worksheet.getUnderlyingTableDataAsync | New | - To support the data model, the JavaScript API also includes the `LogicalTable` class that has two properties: `getCaption()` and `getTableId()`. The `getCaption` returns the name of the table as it appears in Tableau. To get the underlying data from the table, you use the id returned by `getTableId()` when you call the `getUnderlyingTableDataAsync()` method. For more information about getting underlying data from worksheets, see the [Get Underlying Table Data Example](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#gettabledata). - New method showExportPowerPointDialog() that displays the Export to Power Point dialog box, which shows a dialog allowing the user to choose the sheets from the workbook or dashboard to download in a PowerPoint file. ## Changes in the JavaScript API for Tableau 2020.1 This section lists changes that were made for the version of the JavaScript API that ships with Tableau 2020.1. - Support for URL action events (`URL_ACTION`). You can now use the addEventListener() method to add an event listener for URL actions. For more information, see [URL Action Example](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#urlaction). - The selectMarksAsync() method now correctly initiates the URL action associated with the selection. ## Changes in the JavaScript API for Tableau 2019.3 This section lists changes that were made for the version of the JavaScript API that ships with Tableau 2019.3. - There is a new property for categorical filters. The getIsAllSelected() property returns true if all values in the filter are selected. - The getAppliedValues() property now correctly returns the selected values if the number of selected values is under 5000. The getAppliedValues() property previously placed a 5000 value limit to the full domain of the filter, so if the filter domain had more than 5000 values, only the selected values from the first 200 values were returned. Now the return set is first filtered to the selected values before the limit of 5000 values is applied. Therefore, if the number of selected values is less than 5000, the complete set of selected values is returned. If the number of selected values is over 5000, only the first 200 selected values are returned. For more information, see [CategoricalFilter Class](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#Categori). ## Changes in the JavaScript API for Tableau Server 10.3 This section lists changes that were made for the version of the JavaScript API that ships with Tableau Server 10.3. ### Toolbar Functions You can now access toolbar buttons so that you can customize the controls for the visualization. In this release, you can call methods to control the Undo and Redo buttons and set up an event listener to monitor toolbar state changes. For more information, see [Toolbar State Example](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm#Toolbar). ## Added to the JavaScript API for Tableau Server 10.0 This section lists changes that were made for the version of the JavaScript API that ships with Tableau Server 10.0. ### Get Data for Visualizations You can now get the data that was used to create the currently displayed visualization. Use the `getSummaryDataAsync` method and the `getUnderlyingDataAsync` method to get data for the currently active sheet. The `getSummaryDataAsync` method displays aggregated data for the fields used in the current view, that is, it displays data only for the measures and dimensions used to create the view. The `getUnderlyingDataAsync` method displays data for all fields in the data source that is used by the current view. For more information, see [Get Data](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_samples_get_data.htm) and the [API Reference](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_ref.htm). ## Added to the JavaScript API for Tableau Server 9.1 This section lists changes that were made for the version of the JavaScript API that ships with Tableau Server 9.1. ### Easier way to load the latest version of the API You can load the JavaScript API library using a file name that contains only the major version number, such as `tableau_2.min.js`. This in turn loads the most recent version of the library. For details, see [Accessing the API](https://help.tableau.com/v0.0/api/js_api/en-us/JavaScriptAPI/js_api_concepts_get_API.htm). [Skip to main content](#main-content) # Third Party Demos **Important changes for the Tableau JavaScript API** As of February 2024, the Tableau JavaScript API is deprecated. Use the Embedding API v3 instead for embedding interactive views into web pages and applications. For guidance on embedding Tableau views, see the [Tableau Embedding API v3 Help](https://help.tableau.com/current/api/embedding_api/en-us/index.html). View a list of third-party demos to get an idea of what you can do with the JavaScript API. The following examples are neither created by nor endorsed by Tableau. - [Animations](http://blog.pluralsight.com/tableau-animation) - [D3.js integration](https://www.interworks.com/blog/rrouse/2014/10/02/create-next-level-dashboards-tableau-and-d3js) - [Snake game](http://tfoldi.github.io/cljs-tableau-cnake/)