TIBCO Spotfire® JavaScript API Overview
Last updated:
4:22am Apr 19, 2017

Back to Extending Spotfire page

Introduction

With the TIBCO Spotfire® JavaScript API it is possible to embed Spotfire visualizations and dashboards into web pages. The API supports customized layout and enables integration with external web applications.

The JavaScript API can be used for a diverse set of scenarios:

  • Embed Spotfire visualizations into a corporate web site.
  • Open an Spotfire analysis from a link, and configure the data or the analysis depending on the user.
  • Integrate Spotfire analyses with other web applications.

The JavaScript API supports opening multiple views against the same analysis, where all views are automatically linked together. This gives a lot of flexibility when creating a mashup.

The key capabilities or the JavaScript API include:

  • Interact with pages: get all pages, get or set active page.
  • Get or set currently marked rows.
  • Get data from marked rows.
  • Get information about or set the values of a filter column.
  • Get metadata for all data tables.
  • Get distinct values of a given data column.
  • Get or set document properties.
  • Apply bookmarks.
  • Call a custom tool.
  • Export to PDF or PowerPoint or call a custom export tool.
  • Register event handlers for events related to pages, data, markings, document properties and more.

This tutorial describes the important concepts and capabilities of the JavaScript API.

See Also

Getting Started

Embedding a Spotfire analysis into a web page can easily be done with just a few lines of code using the JavaScript API. This is illustrated by the following code sample:

<html> 
    <head>
        <script type="text/javascript" src="https://spotfire.cloud.tibco.com/spotfire/wp/GetJavaScriptApi.ashx?Version=7.5"></script>
        <script>
            var serverUrl = "https://spotfire.cloud.tibco.com/spotfire/wp/";
            var analysisPath = "/Gallery/Expense Analyzer Dashboard";

            window.onload = function()
            {				
                var app = new spotfire.webPlayer.Application(serverUrl, null, analysisPath);
                var doc = app.openDocument("container");
            }
        </script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

 

The resulting web page looks like this:

The sample can easily be customized to use other Spotfire analyses and be extended to use more advanced layout or to interact with external applications.  

See the Concepts section below for more details on the individual parts of the sample script and how to add JavaScript code for customization and integration

To run the sample, create a web page from the the code above and add the file to a web hosting container of choice (if you run on your local machine you can use Microsoft IIS, Apache HTTP Server or similar). 

Examples

  • Mashup example with mulitple views
    Shows how to use multiple views (document instances) to display the different parts of the Spotfire analysis.
     
  • Test utility example
    Learn how the JavaScript API works by setting parameters and inspecting results from different function calls.

Concepts

Access the API

The JavaScript API is accessed by the following:

<script type="text/javascript" src="https://spotfire.cloud.tibco.com/spotfire/wp/GetJavaScriptApi.ashx?Version=7.5"></script>

 

The version of the JavaScript API must be compatible with the version of the Spotfire Server (Web Player node) in which the code will run:

  • Use JavaScript version 7.5 for Spotfire Server versions 7.5, 7.6, 7.7, 7.8 and above.
  • Use JavaScript version 6.0 for Spotfire Server versions 6.5 and 7.0.

Open an Analysis

Create the Application Object

The Application object holds references to a specific analysis on a Spotfire server. The application is then used to create one or more Document instances, where all instances share one server side analysis instance.

spotfire.webPlayer.Application = function (webPlayerServerRootUrl, customizationInfo, analysisPath, parameters, reloadInstances)

 

Parameters:

webPlayerServerRootUrl 

The URL to the Web Player server (for example 'https://spotfire.cloud.tibco.com/spotfire/wp/')

customizationInfo

Instance of the Customization class.

analysisPath

The path in the library to the analysis to open.

parameters

Optional. Load parameters for the analysis. See “Set Parameters/Configuration Block”

reloadInstances

Optional. If true, the JavaScript API will try to reuse server side instances of loaded documents. During development this is normally set to false.

 

openDocument method

Opening a document is done via the openDocument method on the application instance.

spotfire.webPlayer.Application.prototype.openDocument = function (elementId, initialPage, customizationInfo)

 

Parameters:

elementId                                                               

The id of the DOM element where the document is displayed in the web page.

initialPage

Optional initial page. The page can either be expressed as an integer (0-based page index) or as a string (page name).

customizationInfo      

Optional instance of a Customization instance. If set, this will override the customizationInfo instance held by the application.

Return value: An instance of the Document.

Using Multiple Document Instances

From TIBCO Spotfire 7.5 it is possible to view one instance of an analysis in multiple browser windows and utilize the full capabilities of marking, filtering, etc., across multiple pages, within a single analysis.

This capability is also available in the JavaScript API, giving the mashup author much more flexibility when it comes to presenting the right visualizations (or filters) in any context that is driven by user interaction. See code examples in Mashup example with mulitple views.

When creating multiple Document instances from a single Application, the HTML content will be placed in its own element, specified via the elementId argument. This allows you to easily show different parts of the analysis in different contexts, for example, having a popup details visualization driven by marking, or displaying a filter in a Text Area in a popup.

The openDocument method immediately returns the document instance containing the document related API; any usage of this will communicate with the corresponding server side web control tree. Prior to Spotfire 7.5, this document instance was received only in the onOpened callback. However, note that no API calls will be executed until the document is fully loaded and the onOpened callback is called, which is invoked once per document. Any API calls made prior to that callback will be queued and executed when the document is loaded on the server side.

Having one document instance per web control tree makes it possible to interact with each view separately, such as changing active page or receiving a callback when active page is changed. Methods that act on elements that do not have an active concept, such as setMarking (which explicitly specifies the marking name and data table name), can be called via any of the document instances with the same result. Equivalently, all callbacks registered via Marking.onChanged will be called when marking changes, thus, it is sufficient to register a callback for one document.

Customization - Show/Hide UI Components

When creating an Application object or when opening a document instance, it is possible to customize what UI components that are shown in the web view.

See the Customization class for available customization options.

Example 1: if we want to remove the toolbar, page navigation and status in the basic example above, to get a cleaner dashboard, this can easily be done by adding the following:

var customization = new spotfire.webPlayer.Customization();
customization.showStatusBar = false;
customization.showToolBar = false;
customization.showPageNavigation = false;
				
var app = new spotfire.webPlayer.Application(serverUrl, customization, analysisPath);
var doc = app.openDocument("container");

 

When using multiple documents it is possible to set different customization to different document instances. This is done by changing the values of the Customization instance before calling Application.openDocument. If the same settings should be applied on all views the Customization instance can be set once when creating the application instance.

Example 2: The Customization is set on the application instance and re-used for each document instance:

Customization customization = new Customization();
customization.showAbout = false;
customization.showAnalysisInformationTool = false;
customization.showAuthor = false;
customization.showClose = false;
customization.showCustomizableHeader = false;
customization.showDodPanel = false;
customization.showExportFile = false;
customization.showExportVisualization = false;
customization.showFilterPanel = false;
customization.showHelp = false;
customization.showLogout = false;
customization.showPageNavigation = false;
customization.showReloadAnalysis = false;
customization.showStatusBar = false;
customization.showToolBar = false;
customization.showUndoRedo = false;

var app = new spotfire.webPlayer.Application(serverUrl, customization, analysisPath);
var doc1 = app.openDocument("container1", 0);
var doc2 = app.openDocument("container2", 1);

 

Example 3: The filter panel is visible in the first document but hidden in the second document:

Customization customization = new Customization();
customization.showStatusBar = false;
customization.showToolBar = false;
customization.showPageNavigation = false;
customization.showFilterPanel = true;
var doc1 = app.openDocument("container1", 0, customization);

customization.showFilterPanel = false;
var doc2 = app.openDocument("container2", 1, customization);

Note: to be able to show the filter panel through customization, the filter panel must have been enabled in the saved analysis.

Set Parameters/Configuration Block

When creating an Application instance it is possible to specify a set of parameters called a configuration block.

A configuration block is used to configure the analysis before it becomes interactive to the user. It can contain parameter assignments (to document properties, information links etc) and configuration statements (set filter, apply bookmark etc).

Example:

var parameters = “myproperty=1; ApplyBookmark(bookmarkName=”bookmark1”);”
var app = new spotfire.webPlayer.Application(serverUrl, customization, analysisPath, parameters, reloadAnalysisInstance);

 

Read more about the available parameter assignments and configuration statements in Create a Configuration Block in TIBCO Spotfire®.

Register Event Handlers

To enable interaction between different parts of the web page or with external applications, it is possible to register event handlers to handle events that can occur on the Spotfire analysis, for example:

  • Active page change events
  • Document property value change events
  • Marking change events

Example showing one event handler that catch errors and one that handles page change events:

window.onload = function()
{
    var app = new spotfire.webPlayer.Application(serverUrl, customization, analysisPath);
    var doc = app.openDocument("container");

    // Register an error handler to catch errors.
    app.onError(errorCallback);

    // Register event handler for page change events.
    doc.onActivePageChanged(onActivePageChangedCallback);
}

function errorCallback(errorCode, description) 
{
    // Displays an error message if something goes wrong in the Web Player.
    alert(errorCode + ": " + description);
}

function onActivePageChangedCallback(pageState)
{
    alert("The new page has the title: " + pageState.pageTitle);
}

 

The table below lists all available event handlers:

Application.onOpened
Application.onOpenedCallback
Event raised when a document has finished loading.
Application.onClosed
Application.onClosedCallback
Event raised when the analysis has closed.
Application.onError
Application.onErrorCallback
Event raised when an error occurs in the analysis or API.
Document.onActivePageChanged
Document.onActivePageCallback
Event raised when the active page changes in the analysis.
Document.onDocumentPropertyChanged
onGetPropertyCallback
Event raised when the given property has changed value.
Document.onDocumentReady
Document.onDocumentReadyCallback
Event raised, when the document switches to the ready state (the round icon in the status bar becomes green).
Data.onRangeChanged
Data.onRangeChangedCallback
Event raised when filtered range in a data column is changed.
Marking.onChanged
Marking.onMarkingCallback
Event raised when marking has changed in the analysis.
DataTable.onDataTablePropertyChanged
onGetPropertyCallback
Event raised when a data table property has changed value.
DataColumn.onDataColumnPropertyChanged
onGetPropertyCallback
Event raised when a data column property has changed value.

Authentication

The JavaScript API can only be used with single-sign-on authentications; like Anonymous, NTLM and Kerberos. It can also be used for publicly shared analysis files in Spotfire Cloud.

Pages and Visualizations

A document instance created with the API is connected to a page in an analysis. The example above uses an analysis with several visualization laid out on a single page. For better flexibility when creating the web page layout it is recommended to prepare the analysis file to have a one visualization or a group of closely related visualizations on each page. See the Mashup example with mulitple views topic on how an analysis can be prepared for API use and how single visualizations (or other components like filters) can be displayed in separate parts of the web page, for example in popup views. 

Marking

A reference to the Marking class is retrieved from the Document.marking property.

The Marking class has the getMarking and setMarking, methods to get and set the current marking. A Spotfire analysis can include several markings. Each marking is identified by a unique name. The getMarkingNames method returns a list of all available markings,

function getMarking(markingName, dataTableName, dataColumnNames, maxRows, callback);
function setMarking(markingName, dataTableName, whereClause, markingOperation);
function getMarkingNames(callback);

 

Typically, a marking is changed by user interaction, for example the user selects markers in a Scatter Plot, lines in a Line Chart or rows in a Table Plot. Your program can respond to a marking changed event in an event listener, Marking.onMarkingCallback, which is setup with the Marking.OnChanged method.  A common scenario is to retrieve the data from the marked records and pass them on to other parts of the application.

doc.marking.onChanged(
                "Marking",
                "SpotfireExpenseAnalyzer",
                ["Department", “Month”, "Line Amount"],
                100,
                onMarkingChangedCallback);

function onMarkingChangedCallback(marking)
{
    // Iterate through all columns.
    for (var columnName in marking)
    {
        var rows = marking[columnName].length;
               
        // Iterate through all rows for each column.
        for (var i = 0; i < rows; i++)
        {
            // Get the marked data: marking[columnName][i]
        }
    }
}

 

Filtering

Functionality related to filtering is contained in the Filtering class. A reference to the Filtering class is retrieved from Document.filtering property.

From the Filtering class it is possible to get information about filter columns (FilterColumn class) with the methods getFilterColumn, getModifiedFilterColumns and getAllModifiedFilterColumns:

function getFilterColumn(filteringSchemeName, dataTableName, dataColumnName, includedFilterSettings, callback);
function getModifiedFilterColumns(filteringSchemeName, includedFilterSettings, callback);
function getAllModifiedFilterColumns(includedFilterSettings, callback);

 

A filter column has the following properties:

A Spotfire analysis can contain one or several filtering schemes, represented by the FilteringScheme class and retrieved by the getFilteringScheme and getActiveFilteringScheme methods. The getFilteringSchemes method can be used to list all available filtering schemes in the analysis.

function getFilteringScheme(filteringSchemeName, callback);
function getActiveFilteringScheme(callback);
function getFilteringSchemes(callback);

 

It is possible the set the values of a filter column with the setFilter and setFilters methods.

function setFilter(column, operation);
function setFilters(columns, operation);

where the operation argument is filteringOperation enumeration.

All filters can be reset to the default values with the resetAllFilters method.

function resetAllFilters();

 

Data - Tables and Columns

Functionality related to the data in the analysis is contained in the Data class. A reference to the Data class is retrieved from the Document.data property.

A Spotfire analysis contains one or more data tables, retrieved by the getDataTablegetActiveDataTable and getDataTables methods.

function getDataTable(dataTableName, callback);
function getActiveDataTable(callback);
function getDataTables(callback);

 

Each data table contains one or more data columns, retrieved by the getDataColumn,  getDataColumns and searchDataColumns.

function getDataColumn(dataColumnName, callback);
function getDataColumns(callback);
function searchDataColumns(searchExpression, callback);

 

From the DataColumn class it is possible to retrieve metadata, such as column name and data type. It is also possible to get a list of the unique values in the data column with the getDistinctValues method.

function getDistinctValues(startIndex, responseLimit, callback);

 

Document Metadata

Information about the Spotfire analysis can be retrieved by the Document.getDocumentMetadata method. 

function getDocumentMetadata(callback);

 

The resulting DocumentMetadata class has the following properties:

  • The path to the analysis
  • The title of the analysis
  • The description of the analysis
  • The content size in bytes
  • A DateTime describing when the analysis was created in the Spotfire library.
  • A DateTime describing then the last modification was made to this analysis in the Spotfire library.

Bookmarks

A Spotfire analysis may contain bookmarks. The IDs or names of the available bookmarks can be retrieved by the Document.getBookmark or the Document.getBookmarkNames method.

function getBookmarks(callback);
function getBookmarkNames(callback);

 

A bookmark can be applied by calling the Document.applyBookmark or the Document.applyBookmarkById method.

function applyBookmark(bookmarkName);
function applyBookmarkById(id);

Bookmark names is not guaranteed to be unique in an analysis, and if two bookmarks have the same name, the applyBookmarkId method is the recommended method to use..

Document, Table and Column Properties

In a Spotfire analysis it is possible to define properties on document, table and column level. A property is a name-value pair that is globally defined in the document and can be used to define metadata or as a global variable. The analysis can respond to property changes, for example in visualizations or triggering IronPython scripts, which makes properties a powerful tool when creating interactive dashboard.

The JavaScript API contains methods to get and set the value of a document property,  Document.getDocumentProperty and Document.setDocumentProperty, and to get a list of available properties, Document.getDocumentProperties.

function getDocumentProperty(propertyName, callback);
function setDocumentProperty(propertyName, value);
function getDocumentProperties(callback);

 

For data tables properties, the the corresponding methods are DataTable.getDataTablePropertyDataTable.setDataTableProperty and  DataTable.getDataTableProperties.

function getDataTableProperty(propertyName, callback);
function setDataTableProperty(propertyName, value);
function getDataTableProperties(callback);

 

For data column properties, the the corresponding methods are: DataColumn.getDataColumnProperty, DataColumn.setDataColumnProperty and DataColumn.getDataColumnProperties.

function getDataColumnProperty(propertyName, callback);
function setDataColumnProperty(propertyName, value);
function getDataColumnProperties(callback);

 

A property is represented by the Property class, that has the following fields:

  • The name of the property
  • The value of the property, which can be a string or an array of strings formatted in the users locale.

Print and Export

The JavaScript API contains several options to print and export the Spotfire analysis:

Custom Tools

A custom tool is a Spotfire extension creating with the SDK. If a custom tool has been deployed on the Spotfire Server it is possible to execute the tool from the JavaScript API, using the Document.executeCustomTool method.

function executeCustomTool(toolName);