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(Link opens in a new window).

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.

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.

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(Link opens in a new window) 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.


<script type="text/javascript">
    function initViz() {
	    var containerDiv = document.getElementById("vizContainer");
	    var url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms";
	    var options = {
                hideTabs: true,
                onFirstInteractive: function () {
                    console.log("Run this code when the viz has finished loading.");
                }
            };
        var viz = new tableau.Viz(containerDiv, url, options);
        // Create a viz object and embed it in the container div.
    }
</script>	

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.

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 occured.
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.


<!DOCTYPE html>
<html>

<head>
<title>Undo and Redo</title>

<script type="text/javascript" src="https://public.tableau.com/javascripts/api/tableau-2.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>

<script type="text/javascript" >
var viz;
function initViz() {
    var containerDiv = document.getElementById("vizContainer"),
    url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms",
    options = {
        hideTabs: false,
        hideToolbar: true,
        onFirstInteractive: function () {
		    // Listen for toolbar events
            viz.addEventListener(tableau.TableauEventName.TOOLBAR_STATE_CHANGE, onToolbarStateChange);
        }
    };
	viz = new tableau.Viz(containerDiv, url, options);
}

function onToolbarStateChange(toolbarEvent) {
    // when event occurs, get state and update custom buttons
    var toolbarState = toolbarEvent.getToolbarState();
    updateToolbarState(toolbarState)
}

function updateToolbarState(toolbarState) {
    $('#undoButton').prop('disabled', !toolbarState.isButtonEnabled(tableau.ToolbarButtonName.UNDO));
    $('#redoButton').prop('disabled', !toolbarState.isButtonEnabled(tableau.ToolbarButtonName.REDO));
}


function redo() {
    viz.redoAsync().then(function(t) {
        console.log("redo");
	});
}

function undo() {
    viz.undoAsync().then(function(t) {
        console.log("undo");
	});
}

</script>
</head>

<body onload="initViz() ;">
    <div id="undoRedo">
    <button id="undoButton" onclick="undo()" class="btn" disabled>Undo</button>
    <button id="redoButton" onclick="redo()" class="btn" disabled>Redo</button>
    </div>
    <div id="vizContainer" style="width:800px; height:700px;"></div>
        <br />
</body>
</html>
			

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

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.
  2. ParameterDataType Native JavaScript Type
    FLOAT Number
    INTEGER Number
    STRING String
    BOOLEAN Boolean
    DATE Date
    DATETIME Date

    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") .

  3. 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.
  4. 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().
  5. 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.

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

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.

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 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.


<!DOCTYPE html>
<html>
    <head>
      <title>getData() Basic Table Example</title>
      <!-- Tableau JavaScript library on Tableau 2020.2 and later -->
      <script type="text/javascript" src="https://public.tableau.com/javascripts/api/tableau-2.5.0.min.js"></script> -
      <script type="text/javascript">
      var viz, sheet, table;
      function initViz() {
          var containerDiv = document.getElementById("vizContainer"),
          url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms",
          options = {
            hideTabs: true,
     	     hideToolbar: true,
            onFirstInteractive: function () {
              document.getElementById('getData').disabled = false; // Enable our button
            }
	   };
          viz = new tableau.Viz(containerDiv, url, options);
	}

       function getUnderlyingData(){
         sheet = viz.getWorkbook().getActiveSheet().getWorksheets().get("Storm Map Sheet");
	       // If the active sheet is not a dashboard, then you can just enter:
	       // viz.getWorkbook().getActiveSheet();
         options = {
		maxRows: 10, // Max rows to return. Use 0 to return all rows
		ignoreAliases: false,
		ignoreSelection: true,
		includeAllColumns: false
	  };

	  sheet.getUnderlyingTablesAsync().then(tables => {
	        // Get the first logical table and use that
		return sheet.getUnderlyingTableDataAsync(tables[0].getTableId(), options).then(dataTable => {
    	          var tgt = document.getElementById("dataTarget");
                 tgt.innerHTML = "<h4>UnderlyingTableData:</h4><p>" + JSON.stringify(dataTable.getData()) + "</p>";
               });
         });
     }
 </script>
 </head>

 <body onload="initViz();">
     <div class="page-header">
        <h1>getData() Basic Example</h1>
          <p>Click the "Get Data" button to get underlying data for the viz.</p>
          <button id="getData" onclick="getUnderlyingData()" class="btn" disabled>Get Data</button>
        </div>
        <div id="vizContainer" style="width:600px; height:600px;"></div>
        <div id="dataTarget"></div>
    </body>
</html>

			

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). Marks selection methods are described in Worksheet Class (Selecting Marks).

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

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").


Thanks for your feedback!Your feedback has been successfully submitted. Thank you!