Amazon QuickSight Embedding SDK

repository·master·Indexed 41 days ago

https://github.com/awslabs/amazon-quicksight-embedding-sdk

A JavaScript SDK (v2.11.3) for embedding Amazon QuickSight experiences—including Dashboards, Visuals, Generative Q&A, and the QuickSight console—directly into HTML applications. It provides a unified communication layer via an Embedding Context to manage iframe containers, handle lifecycle events, and programmatically control dashboard state, parameters, and navigation.

Tokens
29.6K
Snippets
65
Records
95
Agent score
52%

What's inside Amazon QuickSight Embedding SDK

  1. Handle Visual Experience messages via onMessage

    master

    The onMessage handler in contentOptions allows you to react to events emitted by the embedded visual. Supported eventNames include:

    • CONTENT_LOADED: Triggered when all visuals in the dashboard are fully loaded.
    • ERROR_OCCURRED: Triggered when a rendering error occurs. The message.errorCode will be:
      • Forbidden: The URL's authentication code expired.
      • Unauthorized: The session obtained from the authentication code expired. Note: If these occur, you must generate a new URL.
    • PARAMETERS_CHANGED: Triggered when parameters in the QuickSight dashboard change.
    • SIZE_CHANGED: Triggered when the size of the dashboard changes.
  2. How the Embedding Context works

    master

    The EmbeddingContext is the central object used to manage all QuickSight embedding experiences. It is created using the createEmbeddingContext method, which returns a Promise<EmbeddingContext>.

    Internal Mechanism: When you create the context, the SDK creates an additional zero-pixel iframe and appends it to the body element of your page. This iframe acts as a communication hub to centralize interaction between the SDK and the embedded QuickSight content.

    Available Embedding Methods: An IEmbeddingContext provides the following methods to embed specific experiences:

    • embedDashboard(frameOptions, contentOptions?)
    • embedVisual(frameOptions, contentOptions?)
    • embedConsole(frameOptions, contentOptions?)
    • embedQSearchBar(frameOptions, contentOptions?)
    • embedGenerativeQnA(frameOptions, contentOptions?)
    import { createEmbeddingContext } from 'amazon-quicksight-sdk';
    
    // Basic creation
    const embeddingContext = await createEmbeddingContext();
  3. Embed the Amazon QuickSight Console

    master

    Console embedding provides the QuickSight authoring experience within your application, allowing users to create QuickSight assets. User capabilities are controlled via custom permission profiles (e.g., restricting data source creation).

    To embed the console, use the embedConsole method on an EmbeddingContext instance. This method returns a ConsoleExperience object which allows you to interact with the embedded instance via the send method.

    // Example of embedding the console
    const embeddingContext = await createEmbeddingContext({
        onChange: (changeEvent, metadata) => {
            console.log('Context received a change', changeEvent, metadata);
        },
    });
    
    const frameOptions = {
        url: "<YOUR_EMBED_URL>",
        container: '#experience-container',
        height: "700px",
        width: "1000px",
        onChange: (changeEvent, metadata) => {
            // Handle FRAME_MOUNTED or FRAME_LOADED
        },
    };
    
    const contentOptions = {
        onMessage: async (messageEvent, experienceMetadata) => {
            // Handle messages from the console
        }
    };
    
    const embeddedConsoleExperience = await embeddingContext.embedConsole(frameOptions, contentOptions);
  4. Embed the Generative Q&A Experience

    master

    To embed the Amazon Q in QuickSight Generative Q&A experience, use the embedGenerativeQnA method on an existing embeddingContext. This method requires frameOptions (to define the container and URL) and contentOptions (to define the UI behavior and appearance). It returns a promise that resolves to a GenerativeQnAExperience object.

    const embeddedGenerativeQnExperience = await embeddingContext.embedGenerativeQnA(frameOptions, contentOptions);
  5. Embed a QuickSight Dashboard

    master

    To embed a QuickSight dashboard, use the embedDashboard method on an instance of the embedding context. This method returns a DashboardExperience object, which provides programmatic control over the dashboard's state, parameters, sheets, and visuals.

    Embedding requires two configuration objects:

    1. frameOptions: Defines the container, dimensions, and iframe behavior.
    2. contentOptions: Defines the dashboard content, such as initial parameters, sheet options, and toolbar visibility.
    const { createEmbeddingContext } = QuickSightEmbedding;
    
    const embeddingContext = await createEmbeddingContext({
        onChange: (changeEvent, metadata) => {
            console.log('Context received a change', changeEvent, metadata);
        },
    });
    
    const frameOptions = {
        url: '<YOUR_EMBED_URL>',
        container: '#experience-container',
        height: "700px",
        width: "300px",
        resizeHeightOnSizeChangedEvent: true,
    };
    
    const contentOptions = {
        parameters: [
            { Name: 'country', Values: ['United States'] }
        ],
        sheetOptions: {
            initialSheetId: '<YOUR_SHEETID>',
        },
    };
    
    const embeddedDashboardExperience = await embeddingContext.embedDashboard(frameOptions, contentOptions);
  6. Migrate Dashboard and Visual Event Callbacks to v2

    master

    Version 2.0 replaces specific callback functions (like parametersChangeCallback or loadCallback) with a unified onMessage handler within contentOptions. You must switch on the eventName to handle specific interactions.

    Event Mapping

    • Parameters Changed:
      • v1: parametersChangeCallback(data)
      • v2: onMessage with eventName: 'PARAMETERS_CHANGED'. The payload contains changedParameters with Name and Values keys.
    • Sheet Selection Changed:
      • v1: selectedSheetChangeCallback(data)
      • v2: onMessage with eventName: 'SELECTED_SHEET_CHANGED'.
    • Content Loaded:
      • v1: loadCallback()
      • v2: onMessage with eventName: 'CONTENT_LOADED'.
    // v2 Unified Message Handling
    const contentOptions = {
        onMessage: (messageEvent) => {
            switch(messageEvent.eventName) {
                case 'PARAMETERS_CHANGED':
                    console.log('Parameters changed', messageEvent.message);
                    break;
                case 'SELECTED_SHEET_CHANGED':
                    console.log('Selected sheet changed', messageEvent.message);
                    break;
                case 'CONTENT_LOADED':
                    console.log('Embedded content loaded', messageEvent.message);
                    break;
            }
        }
    };
  7. Migrate Dashboard Embedding Options from v1 to v2

    master

    In version 2.0, embedding options are split into frameOptions and contentOptions. Many v1 properties have been renamed or moved, and some have inverted boolean logic.

    Height and Resizing

    • v1: Uses height ('AutoFit' or string) and loadingHeight (string) within a single options object.
    • v2: Use height (string) and resizeHeightOnSizeChangedEvent (boolean) within frameOptions.

    Toolbar and UI Controls

    • Print: In v2, use contentOptions.toolbarOptions.export: true to enable printing.
    • Undo/Redo: In v1, undoRedoDisabled: true hides buttons. In v2, use contentOptions.toolbarOptions.undoRedo: true to show them (inverted logic).
    • Reset: In v1, resetDisabled: true hides the button. In v2, use contentOptions.toolbarOptions.reset: true to show it (inverted logic).

    Sheets and Tabs

    • Sheet ID: In v2, use contentOptions.sheetOptions.sheetId.
    • Single Sheet: In v1, sheetTabsDisabled: true hides tabs. In v2, use contentOptions.sheetOptions.singleSheet: true.
    • Resize on Change: In v1, iframeResizeOnSheetChange: true triggers resizing. In v2, use contentOptions.sheetOptions.emitSizeChangedEventOnSheetChange: true.
    • Footer Padding: In v1, footerPaddingEnabled: true adds padding. In v2, use contentOptions.attributionOptions.overlayContent: false to add padding (inverted logic).
    // v2 Example
    const frameOptions = {
        height: '300px',
        resizeHeightOnSizeChangedEvent: true
    };
    const contentOptions = {
        toolbarOptions: {
            export: true,
            undoRedo: true,
            reset: true
        },
        sheetOptions: {
            sheetId: '<YOUR_SHEET_ID>',
            singleSheet: true,
            emitSizeChangedEventOnSheetChange: true
        },
        attributionOptions: {
            overlayContent: false
        }
    };
  8. Migrate Dashboard Embedding Actions from v1 to v2

    master

    Most Dashboard actions in v2 are now asynchronous and return an acknowledgment (ack). Some method names have changed.

    Actionv1 Methodv2 Method
    Navigate to DashboardnavigateToDashboard({ dashboardId, parameters })await navigateToDashboard(dashboardId, { parameters })
    Navigate to SheetnavigateToSheet(sheetId)await setSelectedSheetId(sheetId)
    Get SheetsgetSheets(callback)await getSheets()
    PrintinitiatePrint()await initiatePrint()
    Get ParametersgetActiveParameterValues(callback)await getParameters()
    // v2 Dashboard Actions Examples
    
    // Navigate to a new dashboard
    await embeddedDashboardExperience.navigateToDashboard('<NEW_DASHBOARD_ID>', {
        parameters: [{ Name: 'usStates', Values: ['Arizona'] }]
    });
    
    // Change the current sheet
    await embeddedDashboardExperience.setSelectedSheetId('<NEW_SHEET_ID>');
    
    // Retrieve all available sheets
    const sheets = await embeddedDashboardExperience.getSheets();
    
    // Retrieve current parameter values
    const parameters = await embeddedDashboardExperience.getParameters();
  9. Embed Quick Chat experience

    master

    Use the embedQuickChat method on an embeddingContext instance to embed an Amazon Quick Suite chat bot assistant. This method returns a promise that resolves to a QuickChatExperience object, which allows you to interact with the chat programmatically via the sendPrompt method.

    To use this, you must first create an embedding context using createEmbeddingContext and provide frameOptions (defining the container and dimensions) and contentOptions (defining the chat behavior and UI).

    const embeddingContext = await createEmbeddingContext({
        onChange: (changeEvent, metadata) => {
            console.log('Context received a change', changeEvent, metadata);
        },
    });
    
    const frameOptions = {
        url: "<YOUR_EMBED_URL>",
        container: '#experience-container',
        height: "700px",
        width: "1000px",
    };
    
    const contentOptions = {
        agentOptions: {
            fixedAgentId: 'your-agent-id',
        },
        promptOptions: {
            initialPrompt: 'What is the total revenue for Q4?',
        },
    };
    
    const embeddedQuickChatExperience = await embeddingContext.embedQuickChat(frameOptions, contentOptions);
  10. Install the Amazon QuickSight Embedding SDK

    master

    You can install the SDK using one of two methods depending on your environment:

    Browser-based usage

    Include the SDK via a <script> tag from unpkg. This is suitable for direct inclusion in HTML files.

    Node.js or Bundler usage

    Install the package via npm:

    npm install amazon-quicksight-embedding-sdk

    Then, import it using one of the following syntaxes:

    • CommonJS (require): const QuickSightEmbedding = require("amazon-quicksight-embedding-sdk");
    • Named Import: import { createEmbeddingContext } from 'amazon-quicksight-embedding-sdk';
    • Wildcard Import: import * as QuickSightEmbedding from 'amazon-quicksight-embedding-sdk';
    <script src="https://unpkg.com/amazon-quicksight-embedding-sdk@2.11.3/dist/quicksight-embedding-js-sdk.min.js"></script>
    <script type="text/javascript">
        const onLoad = async () => {
            const embeddingContext = await QuickSightEmbedding.createEmbeddingContext();
        };
    </script>
    <body onload="onLoad()">
  11. Embed a QuickSight Visual

    master

    Visual Embedding provides an interactive read-only experience. To embed a dashboard visual, use the embedVisual method on an EmbeddingContext instance. This method requires frameOptions (to define the container and URL) and contentOptions (to define parameters and event handlers). It returns a VisualExperience object which allows you to programmatically control the visual (e.g., setting parameters, managing filters, or changing themes).

    const embeddingContext = await createEmbeddingContext({
        onChange: (changeEvent, metadata) => {
            console.log('Context received a change', changeEvent, metadata);
        },
    });
    
    const frameOptions = {
        url: "<YOUR_EMBED_URL>",
        container: '#experience-container',
        height: "700px",
        width: "1000px",
    };
    
    const contentOptions = {
        parameters: [
            { Name: 'country', Values: ['United States'] }
        ],
        locale: "en-US",
    };
    
    const embeddedVisualExperience = await embeddingContext.embedVisual(frameOptions, contentOptions);
  12. Understand the EmbeddingEvent hierarchy

    master

    The SDK uses a hierarchy of event classes to communicate state changes and messages between the embedded experience and your application. All events inherit from the base EmbeddingEvent class, which provides eventName, message, data, and eventTarget properties.

    Key event types include:

    • ChangeEvent: Used for changes in the embedding state. It includes an eventLevel (of type ChangeEventLevel) to specify the scope of the change.
    • EmbeddingMessageEvent: A general event used to carry messages.
    • TargetedMessageEvent: An event that includes an eventTarget (of type InternalExperiences), indicating which specific part of the QuickSight experience the event is directed at.
    • PostMessageEvent: A specialized TargetedMessageEvent used for cross-frame communication. It includes metadata for tracking: timestamp (number), version (string), and eventId (string).