Power BI JavaScript Client Library

repository·master·Indexed 22 days ago

https://github.com/microsoft/powerbi-javascript

A JavaScript and TypeScript library for embedding Power BI reports, dashboards, tiles, visuals, and Q&A experiences into applications. Version 2.23.10 provides a service for embedding components and an object model to interact with them, including managing report bookmarks via BookmarksManager, controlling page filters, manipulating visuals, and handling lifecycle events like 'loaded' and 'rendered'.

Tokens
11.4K
Snippets
52
Records
58
Agent score
77%

What's inside powerbi-client

  1. Explore Power BI embedded analytics resources

    master

    To learn more about embedding Power BI and using the client APIs, use the following resources:

  2. Install the powerbi-client library

    master

    You can install the powerbi-client library using NPM or NuGet depending on your project environment.

    NPM Installation

    For standard JavaScript/TypeScript projects:

    npm install --save powerbi-client

    To install the latest beta version:

    npm install --save powerbi-client@beta

    NuGet Installation

    For .NET-based environments:

    Install-Package Microsoft.PowerBI.JavaScript
    npm install --save powerbi-client
  3. Include the library via ES6 modules or manual script tag

    master

    Depending on your build pipeline, you can consume the library using ES6 imports or by including it as a global script.

    Using ES6 Modules

    If you use a module loader or a compilation step (like Webpack or Vite), import the entire namespace:

    import * as pbi from 'powerbi-client';

    Using a Global Script Tag

    If you are not using a module loader, include the powerbi.js script before your closing </body> tag. This exposes the library as a global object.

    When included directly, the library provides two globals:

    1. powerbi-client: The library namespace.
    2. powerbi: An instance of the service.
    import * as pbi from 'powerbi-client';
  4. Embed a single Power BI visual using the Visual class

    master

    The Visual class allows you to embed a specific single visual from a Power BI report into an HTML element. When embedding a visual, you must provide the pageName and visualName in your configuration. Note that certain report-level operations, such as getPages() and setPage(), are not supported when embedding a single visual.

    To embed a visual, ensure your configuration includes:

    • pageName: The name of the page containing the visual.
    • visualName: The unique name of the visual to display.
    • accessToken: A valid Power BI access token.

    When a visual is embedded, the library automatically configures the layout to hide the navigation pane and filter pane, and sets the layout type to Custom to focus on the specific visual.

    // Note: This is a conceptual representation of the embedding requirement
    const config = {
      type: 'visual',
      pageName: 'YourPageName',
      visualName: 'YourVisualName',
      accessToken: 'YOUR_ACCESS_TOKEN',
      // ... other configuration
    };
    
    // The Visual instance is created via the service
    const visual = new Visual(service, element, config);
    visual.load();
  5. Understand the IVisualNode interface

    master

    The IVisualNode interface defines the structure of a node within the Power BI report hierarchy. It is implemented by the VisualDescriptor class. A visual node contains metadata about its identity, type, and location within the report structure.

    export interface IVisualNode {
      name: string;
      title: string;
      type: string;
      layout: IVisualLayout;
      page: IPageNode;
    }
  6. Initialize the Power BI Service

    master

    The Service class is the primary entry point for the Power BI Client SDK. It manages the lifecycle of all embedded components (Reports, Dashboards, Tiles, etc.) and handles communication between the host application and the embedded iframes. To use it, you typically instantiate it with the required communication factories (HPM, WPMP, and Router) and a configuration object.

    // Note: This requires providing factories for the communication layer
    // which are typically handled by the library's internal setup or specific integration patterns.
    const service = new Service(hpmFactory, wpmpFactory, routerFactory, {
      autoEmbedOnContentLoaded: false,
      onError: (error) => console.error(error)
    });
  7. Configure the Power BI Service

    master

    When instantiating the Service, you can provide an IServiceConfiguration object to control its behavior:

    KeyTypeDescription
    autoEmbedOnContentLoadedbooleanIf true, the service will automatically call init() on document.body when the DOM is loaded.
    onError(error: any) => anyA callback function invoked when an error occurs during embedding or service operation.
    versionstringThe version of the service.
    typestringThe type of the service.
    sdkWrapperVersionstringThe version of the SDK wrapper.
    logMessagesbooleanEnables logging of messages (part of IDebugOptions).
    wpmpNamestringThe name for the Window Post Message Proxy (part of IDebugOptions).
  8. Preload Power BI content

    master

    To improve perceived performance, use the preload method to load a Power BI iframe in the background. This creates a hidden iframe and triggers a preloaded custom event on the iframe once it has finished loading.

    const iframe = service.preload(config, element);
    
    iframe.addEventListener('preloaded', () => {
      console.log('Power BI content is preloaded and ready!');
    });
  9. Embed a Power BI component

    master

    Use the embed method to attach a Power BI component to a specific HTML element. You must provide an IComponentEmbedConfiguration which includes the embedUrl and the type of component (e.g., 'report', 'dashboard', 'tile', 'visual', or 'qna'). If the element already has a component attached, the service will reuse the existing instance and update it with the new configuration.

    // Assuming 'service' is an instance of Service and 'container' is an HTMLElement
    const config = {
      type: 'report',
      id: 'your-report-id',
      embedUrl: 'https://app.powerbi.com/reportEmbed...', 
      accessToken: 'YOUR_ACCESS_TOKEN'
    };
    
    const report = service.embed(container, config);
  10. Get the Dashboard ID from a Dashboard instance

    master

    The getId() method retrieves the unique identifier for the Power BI dashboard. It attempts to find the ID in the following order of precedence:

    1. The id property within the embed configuration object.
    2. The powerbi-dashboard-id attribute on the HTML element used for embedding.
    3. The dashboardId query parameter within the embedUrl.

    If no ID is found in any of these locations, the method throws an error stating that the dashboard ID is required.

    // Assuming 'dashboard' is an instance of the Dashboard class
    try {
      const id = dashboard.getId();
      console.log("Dashboard ID:", id);
    } catch (error) {
      console.error(error.message);
    }
  11. Extend Report Menus with Custom Commands

    master

    You can add custom commands to the report's context menus (right-click) or options menus. You can target specific visuals by name or type, and group commands together.

    // Add context menu extension command
    report.addContextMenuCommand(
      commandName, 
      commandTitle, 
      contextMenuTitle, 
      menuLocation, 
      visualName, 
      visualType, 
      groupName
    );
    
    // Add options menu extension command
    report.addOptionsMenuCommand(
      commandName, 
      commandTitle, 
      optionMenuTitle, 
      menuLocation, 
      visualName, 
      visualType, 
      groupName, 
      commandIcon
    );
    
    // Remove a context menu command
    report.removeContextMenuCommand(commandName, contextMenuTitle);
    
    // Remove an options menu command
    report.removeOptionsMenuCommand(commandName, optionsMenuTitle);