0% found this document useful (0 votes)
27 views278 pages

Javascript API Overview Powerbi

The document provides an overview of Power BI embedded analytics, detailing how to embed Power BI content like reports and dashboards into applications using Client APIs. It outlines two main embedding solutions: 'Embed for your customers' and 'Embed for your organization', along with their respective authentication methods and licensing requirements. Additionally, it includes guidance on using the Client API for controlling embedded content and offers various resources for developers to enhance their Power BI integration experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views278 pages

Javascript API Overview Powerbi

The document provides an overview of Power BI embedded analytics, detailing how to embed Power BI content like reports and dashboards into applications using Client APIs. It outlines two main embedding solutions: 'Embed for your customers' and 'Embed for your organization', along with their respective authentication methods and licensing requirements. Additionally, it includes guidance on using the Client API for controlling embedded content and offers various resources for developers to enhance their Power BI integration experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 278

Tell us about your PDF experience.

Power BI embedded analytics Client


APIs
A client side library for embedding Power BI using JavaScript or TypeScript.

Get started

e OVERVIEW

What is Power BI embedded analytics?

Understanding the different embedding solutions

b GET STARTED

Embed a report

Embed a report visual

Embed a paginated report

Embed a dashboard

Embed a Power BI item in a Jupyter notebook

Embed a Power BI item in a React application

Client APIs

p CONCEPT

How to handle events

Refresh the access token

Use bootstrap for better performance

c HOW-TO GUIDE

Control report filters

Configure report settings

Create, edit, and save a report


Report bookmarks

Personalize a report layout

Optimize a Power BI report for mobile layout

References and resources

i REFERENCE

Power BI embedded analytics playground

Power BI Client on GitHub

Power BI Report Authoring on GitHub

Power BI embedded analytics documentation

Developer samples and scripts

Embedding setup tool

Stack Overflow

Power BI REST APIs


What is Power BI embedded analytics?
Article • 01/08/2023

Power BI embedded analytics allows you to embed Power BI content such as reports,
dashboards and tiles, in a web app or in a website.

With Power BI embedded analytics you can:

Deliver compelling data experiences for your end users, and enable them to act
based on insights from your solutions data.

Use and brand Power BI as your own to quickly and easily provide exceptional
customer-facing reports, dashboards, and analytics in your own app.

Reduce developer resources by automating the monitoring, management, and


deployment of analytics, while getting full control of Power BI features and
intelligent analytics.

What are the Power BI embedded analytics


solutions?
Power BI embedded analytics offers two solutions:

Embed for your customers - Allows you to build a an app that uses non-
interactive authentication against Power BI. Your customers are likely to be external
users, and they don't need to sign in using Power BI credentials to view the
embedded content. Typically, this solution is used by independent software
vendors (ISVs) who are developing applications for third parties. For a tutorial, see
Embed Power BI content using a sample embed for your customers application.

Embed for your organization - Allows you to build an app that requires signing in
using Power BI credentials. Once signed in users can only consume embedded
content they have access to on Power BI service. This solution is aimed at big
organizations that are building an app for internal users. For a tutorial, see Embed
Power BI content into an application for your organization.

Comparing the solutions


The following table provides a comparison between the two Power BI embedded
analytics solutions.
Embed for your customers Embed for your organization

Also known as app owns data Also known as user owns data

Aimed at external users Aimed at internal users

To authenticate app users, use your own App users authenticate against Azure AD
authentication method

App users don't need a license Each app user needs a Power BI license

Non-interactive authentication, your app uses a Interactive authentication, your app uses
service principal or a master user to authenticate the app user credentials to authenticate

What are Power BI capacities?


Capacity is a set of resources reserved for exclusive use. It enables you to publish
dashboards, reports, and datasets to users, without having to purchase per-user
licenses. It also offers dependable, consistent performance for your content.

There are two types of Power BI embedded analytics offerings, each requiring a different
capacity:

Power BI Embedded - An Azure offer that requires A SKUs, and is associated with
the embed for your customers solution.

Embedding with Power BI - A Microsoft Office offer that requires P or EM SKUs.

When you're ready to go to production, review the capacity planning article.

Next steps
What is the Power BI embedded analytics Client API?
Understanding the different embedding solutions
Power BI embedded analytics playground
What is the Power BI embedded
analytics Client API?
Article • 04/27/2023

 Tip

To experiment with APIs in real time, using your own report or a sample report, visit
the Power BI embedded analytics playground

The Power BI Client API is a client side library that allows you to programmatically
control your embedded Power BI content, by using JavaScript or TypeScript.

Use the client APIs to communicate between Power BI items (such as reports and
dashboards) and the application code. This gives you the flexibility to build an end user
experience according to your design.

How does the Client library work?


The Client APIs communicate with an embedded Power BI item, such as a report or
dashboard. The iframe creates a separation between the hosting app and the Power BI
item, making sure the data is secured.

Client application - The entire screenshot is an example of a client application.

Embedded report - The embedded report currently displayed in the application.


iFrame boundary - The embedded report is hosted inside an iFrame. The diagram
outlines its boundary.

Client APIs - Use the Client APIs to communicate between the web application and
the embedded component. For example, when calling report.setPage(…) the
active page of the report will be changed. After the page is changed a
pageChanged event will be emitted by the report, and you can add additional code
in the event handler. For more information, see page navigation.

What does this documentation set include?


This documentation set lists the APIs for the following components:

powerbi-client - The main Power BI Client library which includes all the Power BI
Client APIs except for powerbi-report-authoring. This library defines the classes for
the different Power BI items that can be embedded. The powerbi-client library
allows you to control the content you're embedding.

powerbi-models - Contains the object models for the Power BI Client APIs. For
each model there is a TypeScript interface, a JSON schema definition, and a
validation function to ensure a given object is a valid model.

powerbi-report-authoring - An extension of the client library. These APIs help


with creating visuals and authoring the report after it's loaded. The powerbi-report-
authoring library allows you to programmatically edit your embedded reports.

The documentation set also includes articles that explain how to use the APIs, alongside
code examples. The articles are divided into the following sections:

Overview - Additional information about Power BI embedded analytics.

Playground showcases - Learn how to use embedded analytics in your apps


quickly using the Power BI embedded analytics playground.

Start embedding - Learn how to embed each of the Power BI items such as reports
and dashboards.

Basic concepts - Learn about some of the concepts every developer should be
familiar with.

Report embedding - Additional embedding concepts applicable only for reports.

Report operations - Tweak your embedded report so that it provides a better user
experience for your customers.
Embed reports for your organization - Create better embedded reports when
embedding using the embed for your organization solution.

Report authoring - Articles dedicated to the powerbi-report-authoring APIs,


allowing you to create and personalize visualizations after the report is loaded.

The Resources entry includes resources useful for Power BI developers.

7 Note

It's recommended to review these articles while experimenting with the Power BI
embedded analytics playground .

Next steps
Understanding the different embedding solutions

Power BI embedded analytics playground


Understanding the different embedding
solutions
Article • 05/09/2022

Embedding Power BI items (such as reports, dashboards and Q&A) into your application
allows you to integrate stunning, fully interactive analytics without having to build your
own data visualizations and controls from scratch. The Power BI analytics that you
embed can either present data that your app owns through your own Power BI account,
or data that the user owns through their Power BI accounts.

Application scenarios
There are two different scenarios for embedding a Power BI report in an application.

Embed for your organization (also known as user owns data): The application
allows you to integrate data, reports, dashboards, and tiles that are accessible to
users in your organization when they sign in using their own Power BI accounts. In
this type of application, the users own the data that you embed.
Embed for your customers (also known as app owns data): The application
presents the data, reports, dashboards, or tiles that you uploaded to your own
Power BI account. In this type of application, you are using your own account, so
your application owns the data for your customers. Your customers don't need
their own Power BI account.

The application scenario that you use determines how you retrieve an access token that
allows you to access data and embed content in your application.

The type of content that you embed is specified by the value of the embedUrl parameter.
To retrieve an embed URL for a particular type of content, call the corresponding Power
BI REST API. For example, call Get Reports to retrieve the embed URL for embedding a
report.

The following sections show you how to retrieve an access token and embed a report
for each of these application scenarios.

Embed for your organization


In this scenario, users of your application sign in using their Power BI accounts. This
gives you the access token for accessing their data and embedding their reports,
dashboards, and tiles.
In the embedConfiguration , set tokenType to TokenType.Aad .

JavaScript

// Get models so you can use the TokenType enum.


let models = window['powerbi-client'].models;

let embedConfiguration = {
type: 'report',
id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Aad,
accessToken: 'e4...rf'
};

let reportContainer = $('#reportContainer')[0];


let report = powerbi.embed(reportContainer, embedConfiguration);

Embed for your customers


In this scenario, you create a dedicated identity that has access to all the Power BI items.
Then, you generate an Embed Token for the reports, dashboards, or tiles that you want
to embed by calling the Power BI REST API Embed Token. Once you have an embed
token, use the following code to embed the report:

In the embedConfiguration , set tokenType to TokenType.Embed .

JavaScript

// Get models so you can use the TokenType enum.


let models = window['powerbi-client'].models;

let embedConfiguration = {
type: 'report',
id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Embed,
accessToken: 'h4...rf'
};

let reportContainer = $('#reportContainer')[0];


let report = powerbi.embed(reportContainer, embedConfiguration);

Next steps
Tutorial: Embed Power BI content using a sample embed for your customers
application

Tutorial: Embed Power BI content into an application for your organization

Considerations when generating an embed token


Go from insights to quick action
showcase
Article • 01/08/2023

The Power BI playground's Go from insights to quick action demonstrates an app that
creates meaningful customer campaigns based on real-time analytics. Users can slice
and filter Power BI embedded report data to discover insights, then configure and start
a customer discount or coupon campaign instantly from within the report.

This showcase demonstrates how an app uses the following commands:

The extend menu command API to add a custom command and menu item to a
report.
Event handling to communicate between report events and application code.
The exportData API to export the underlying data of a report visual.

Go from insights to quick action showcase


experience
Contoso, a fictitious sales company, uses the Go from insights to quick action
showcase to generate insights and kick off campaigns directly from within a Power BI
embedded report. The embedded report presents customers' purchases by customer
name and region, purchase category, days since last purchase, and amount spent.

The report has table, column graph, and donut chart visualizations, and several slicing,
filtering, and sorting mechanisms. For this report, Contoso is most interested in the past
30 days' higher-end purchases of $500-$799, so the report loads with those slicer
ranges applied.
Generate insights
To gain insights about the sales results, report users can filter or slice the data further by
selecting specific values and ranges in the drop-down lists, visualizations, and slicers. For
example, a Sales Manager for Professional Services selects several different regions, and
realizes that although the Professional Services category had the highest total spend
overall, it had the lowest spends in the MEA, UK, and United States regions, and no
purchases in LATAM or Canada.

Create a campaign
The Sales Manager decides to promote Professional Services sales to Canada, LATAM,
MEA, UK, and United States customers. To kick off a campaign any time using the
current customer list, the Sales Manager can either select the Create a campaign button,
or select Start campaign from the customer table visual's More options (...) menu.
Create a targeted customer list
Report users can use the report drop-down lists, visualizations, and slicers to narrow
down the customer list to targeted recipients. In this case, the Sales Manager selects
Canada, LATAM, MEA, UK, and United States from the Region drop-down list, and the
customer table now lists customers from only those regions. When the customer list is
ready, the Sales Manager selects Create a campaign.
Create a discount campaign
The Campaign distribution list popup opens, listing the targeted recipients' names and
contact information, and offering the choice to Send discount or Send coupon. The
Sales Manager selects Send discount.

In the Send discount to distribution list dialog box, the Sales Manager writes a message
offering the targeted customers a 10% discount on Contoso professional services, and
then selects Send.
The app sends the discount offer emails to the distribution list, and displays a Sent
notification.

The Sales Manager could also send a coupon to customers by selecting Send coupon
on the distribution list screen.

Go from insights to quick action showcase


code
The code for implementing the showcase is in the PowerBI-Embedded-Showcases
GitHub repository.

The application HTML code builds the embedded report container and elements,
dialog boxes, text fields, and buttons.

The report JavaScript code embeds the report and defines all the visualization
interactions, data exports, and button handling functions.

Add the campaign command to the report


The report embedConfiguration uses the extend menu command API to add a campaign
command to the report, which appears at the top of the More options menu of the
table visual.

JavaScript

let config = {
...
settings: {
...
extensions: [
{
command: {
name: "campaign",
title: "Start campaign",
icon: base64Icon,
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: tableVisualGuid
},
extend: {
visualOptionsMenu: {
title: "Start campaign",
menuLocation: models.MenuLocation.Top,
}
}
}
},
...
}
}

Handle the Start campaign command


The following code handles the commandTriggered event for the campaign command. The
code listens for the Start campaign menu item selection event, and sends the current
filtered customer list data from the table visual.

JavaScript

// Adding onClick listener for the custom menu in the table visual in the
report
reportShowcaseState.report.on("commandTriggered", async function (event) {
if (event.detail.command === "campaign") {

// Populate data according to the current filters on the table


visual
const result = await
tableVisual.exportData(models.ExportDataType.Underlying);
handleExportData(result);
onStartCampaignClicked();
}
});

Handle the Create a campaign button click


The following code handles the Create a campaign button click event. The code listens
for the Create a campaign button selection event, and sends the current filtered
customer list data from the table visual.

JavaScript

// Adding onClick listener for the button in the report


reportShowcaseState.report.on("buttonClicked", async function () {

// Populate data according to the current filters on the table visual


const result = await
tableVisual.exportData(models.ExportDataType.Underlying);
handleExportData(result);
onStartCampaignClicked();
});

Next steps
Modify menu commands
How to handle events
Export data from a visual
Power BI Embedded Analytics Playground
Personalize top insights showcase
Article • 01/08/2023

The Personalize top insights showcase in the Power BI embedded analytics


playground (preview) uses the custom layout API to let users select which
visualizations and layouts to see during their report viewing session.

Power BI embedded custom report layouts control the size, position, and visibility of
visuals on a report page. Use custom layouts to present different views to different
users, or to let users personalize their own views. Custom layouts help users focus on
their most important visualizations and insights.

You can also use custom layouts to resize visuals when window size changes, or to
present different layouts for desktop, tablet, or mobile screens.

Custom layout showcase experience


In the Personalize top insights showcase, an imaginary conglomerate named Contoso
uses a Power BI embedded report to show business data to their stakeholders. The
embedded report loads with all nine available visualizations appearing in a two-column
layout.

Select visuals
To choose only the visuals they most want to see, report users select the Choose visuals
button. The Choose visuals drop-down list box opens, with all nine available visuals
selected.

Users can clear the check boxes next to the visuals they don't want to see. Only the
selected visuals appear in the report for the rest of that viewing session.
Selecting Choose visuals again closes the drop-down box. Users can select Choose
visuals again to select different visuals or all nine visuals.

Select a layout
Users can also select Choose layout to drop down a palette of five different visualization
layout choices. Selecting a layout option applies the selected layout and closes the
palette.
Visuals and layout interaction
The Choose visuals and Choose layout controls in the application code are
independent, but they interact. For example, if only one visual is showing, the one-
column layout displays the visual at a larger size than the three-column layout.

Custom layout showcase code


The code for implementing the showcase application is in the PowerBI-Embedded-
Showcases GitHub repository.

The application HTML code builds the report container, Choose visuals button
and drop-down list, and Choose layout button and drop-down palette.

The report JavaScript embeds the report, calculates and configures the custom
layout objects, and implements the default and personalized custom layouts.

To create a custom report layout, you pass a custom layout object to the settings
property of the report embed configuration. To enable custom layouts, the report
JavaScript uses the layoutType property with value models.LayoutType.Custom .

The customLayout object specifies the report canvas page size, canvas scaling, and page
layout. Page layouts specify a default visual layout for the report, and visual layouts for
each visual.

JavaScript

let settings = {
...
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: models.PageSizeType.Custom,
width: reportWidth - 10,
height: reportHeight - 20
},
displayOption: models.DisplayOption.FitToPage,
pagesLayout: pagesLayout
}
};

To display selected visualizations and layouts, the showcase JavaScript dynamically


creates the settings object and updates the embed configuration. The report loads
with the selected visuals showing and the custom layout implemented.

Next steps
Personalize a report layout
Power BI Embedded Analytics Playground
Customize report colors and mode
showcase
Article • 01/08/2023

The Power BI embedded theme API defines and applies color palettes and other styles
to Power BI reports. Use the themes feature to apply customized themes for different
report users, or to let users choose their own look and feel.

The Customize report colors and mode showcase in the Power BI embedded analytics
playground uses the theme API to let users choose different colors and background
modes when viewing a Power BI embedded analytics report.

The showcase report uses the theme feature to:

Define report color themes and background modes.


Apply a specific color theme on report load.
Let users change themes and background modes during their report viewing
sessions.

For more information about report themes, see Use report themes in Power BI Desktop.

Theme showcase experience


In the Customize report colors and mode showcase, an imaginary conglomerate
named Contoso uses a Power BI embedded report to show business data to their
stakeholders. The embedded report loads with the Default color theme and default
background mode applied. All visuals in the report use the theme colors.
Select a theme and mode
Report viewers can select the Choose theme button to apply a different color theme or
mode. The Choose theme drop-down box opens, listing the available theme names and
color palettes, with the current theme selected.

Viewers can select a different theme from the list and see the immediate changes in
data, label, and other element colors. The selected theme affects all the embedded
visuals in the report.
Viewers can also toggle Dark mode to produce a dark report background with light-
colored text, independent of the color theme selection.

Selecting Choose theme again closes the drop-down box. The new selected theme and
background mode remain in effect during the report viewing session, unless the viewer
changes them again.

Theme showcase code


The code for implementing the showcase application is in the PowerBI-Embedded-
Showcases GitHub repository.

The HTML page builds the report container and Choose theme button and
dialog box, and loads the themes JSON objects .

The report JavaScript embeds the report, loads the default theme, and
implements the theme switching experience.

Define themes with report theme JSON objects


You can customize almost all Power BI formatting elements through report theme JSON
objects. The showcase themes.js file defines jsonDataColors objects that specify
available color theme names and properties.

The following jsonDataColors object defines the showcase Tidal theme. The asterisk *
applies a setting globally to all the visuals in the report.

JSON
const jsonDataColors = [
...
{
"name": "Tidal",
"dataColors": ["#094782", "#0B72D7", "#098BF5", "#54B5FB", "#71C0A7",
"#57B956", "#478F48", "#326633"],
"tableAccent": "#094782",
"visualStyles": {
"*": {
"*": {
"background": [{ "show": true, "transparency": 3 }],
"visualHeader": [{
"foreground": { "solid": { "color": "#094782" } },
"transparency": 3
}]
}
},
"group": { "*": { "background": [{ "show": false }] } },
"basicShape": { "*": { "background": [{ "show": false }] } },
"image": { "*": { "background": [{ "show": false }] } },
"page": {
"*": {
"background": [{ "transparency": 100 }],
}
}
}
}
...
]

For more information about report theme JSON object file format and properties, see
Report theme JSON file format.

Define background modes

The themes.js file also defines themes objects that describe the Light and Dark
background modes. To define Light and Dark background modes, the themes object
specifies one theme with a white background, and another theme with a contrasting,
dark-colored background. The dark-background object also sets the values for other
structural and text colors so they're visible against the dark background.

Apply themes with embed configuration and applyTheme


The showcase themeJson parameter defines several color themes. The embedded report
JavaScript uses the Report class applyTheme method to apply themes on report load
and during report runtime.
To enable themes, the report embed configuration specifies a theme attribute, with a
themeJson parameter pointing to the themes JSON object. The showcase embed
configuration applies the Default theme, which has data-color ID 0 , on report load:

JavaScript

let config = {
...
theme: { themeJson: jsonDataColors[0] },
};

If the viewer selects a different theme or mode during their session, the applyTheme
function defines and applies a new theme object based on the selected data color and
mode. The following code shows the showcase applyTheme function:

JavaScript

async function applyTheme() {

// Get active data-color ID


activeDataColorId = Number($("input[name=data-color]:checked", "#theme-
dropdown")[0].getAttribute("id").slice(-1));

// Get the theme state from the slider toggle


let activeThemeSlider = $("#theme-slider").get(0);

// Get the index of the theme based on the state of the slider
// 1 => Dark theme
// 0 => Light theme
const themeId = (activeThemeSlider.checked) ? 1 : 0;

// Create new theme object


let newTheme = {};

// Append the data colors and the mode


$.extend(newTheme, jsonDataColors[activeDataColorId], themes[themeId]);

// Apply the theme to the report


await themesShowcaseState.themesReport.applyTheme({ themeJson: newTheme
});
}

Next steps
Apply report themes
Power BI Embedded Analytics Playground
Capture report views showcase
Article • 01/08/2023

Power BI report bookmarks capture the current state of an embedded report page,
including the state of its visuals and any slicing or filtering. Users can return the report
to that state by accessing the captured or shared bookmark. You can use the Power BI
Client APIs to save bookmarked views with reports, and to let report users capture and
share their own bookmarks.

The Capture report views showcase in the Power BI embedded analytics playground
uses the bookmarks API to let users access, capture, save, and share bookmarks.

Users can:

See bookmarked views saved as part of the report.


Use filters, slicers, and other controls to create a customized report view.
Capture the current view by saving a bookmark.
Share the captured view with others by sending them a link.
Return to bookmarked views they created during the current viewing session.

Capture report views showcase experience


In the Capture report views showcase, an imaginary conglomerate named Contoso
shows their performance data in a Power BI embedded report. The report uses a Q&A,
two multirow cards, a matrix, and column charts to show 2014 data for all their
manufacturers, products, and regions. The visuals have filter and slicer controls, so users
can narrow down and view parts of the data.

Configure a view
A Sales Manager in the West region selects West to view only West region data, and
uses the date slider to narrow down the timeframe to the second half of the year.
The Sales Manager can save or share the configured view by selecting Capture view. A
pop-up dialog box gives the option to Save to 'My Views' or Copy Link.

Save a bookmark
To save a bookmark, the Sales Manager selects Save to 'My Views', enters a name for
the view, and selects Save.

The dialog box closes, and a panel showing the saved bookmarks list appears, with the
new saved bookmark highlighted. Selecting any bookmark in the list highlights the
bookmark and displays that view. Selecting the close symbol or the Saved views button
closes the bookmarks panel.

Share a bookmark
To get a link to the view to send to stakeholders, the Sales Manager selects Copy Link in
the Capture view dialog box, and then selects Copy to copy the link. Selecting the close
symbol or selecting anywhere outside of the dialog box closes it.
See a bookmarked view
To go to any saved bookmark view during the current report viewing session, users can
select Saved views to drop down the bookmark list, and select the view they want to
see. The bookmark name highlights, and the report displays the bookmarked view.

Bookmarks you save on report creation are available for all users in all sessions. You can
also save user-created bookmarks between sessions, but in this showcase, bookmarks
that users create are available only during the same viewing session, or by direct URL.

Recipients of shared bookmark links can use the links in their browsers to open reports
directly to the bookmarked views.

Capture report views showcase code


The code for implementing the showcase is in the PowerBI-Embedded-Showcases
GitHub repository.

The application HTML code builds the report container and elements, Saved
views button and drop-down list, and the Capture view button and dialog box.

The report JavaScript embeds the report with a saved list of bookmarks, loads
the report with the first, All Year 2014 bookmarked view active, and implements
the bookmark capturing, saving, sharing, and selection functions.

In the report BookmarksManager class, apply applies a previously saved bookmark by


name, capture captures and returns a string that represents the current state of the
report, and applyState applies a previously captured state. When applying a saved
bookmark, you can specify the bookmark either by name or by state .
For more information about bookmark operations and APIs, see Report bookmarks.

Apply a bookmarked view on report load


The showcase code decodes the bookmark name from the view URL id argument and
gets that bookmark from local storage. The showcase uses local storage for simplicity,
but you can use any database. The bookmark attribute in the report embedConfiguration
applies the bookmark on load.

JavaScript

async function embedSharedBookmarkReport() {


...
// Get the bookmark name from url param
let bookmarkName = getBookmarkNameFromURL();

// Get the bookmark state from local storage


let bookmarkState = localStorage.getItem(bookmarkName);

// Embed configuration used to describe the what and how to embed


let config = {
...
// Adding bookmark attribute will apply the bookmark on load
bookmark: {
state: bookmarkState
}
};

Capture a view and save it to the bookmarks list


The showcase code captures the current report state, adds the new bookmark name to
the bookmark list, and opens the drop-down bookmark list with the new bookmark
active.

JavaScript

// Capture the report's current state with personalized visuals


const capturedBookmark = await
bookmarkShowcaseState.report.bookmarksManager.capture({ personalizeVisuals:
true });

// Build bookmark element


let bookmark = {
name: "bookmark_" + bookmarkShowcaseState.bookmarkCounter,
displayName: capturedViewname,
state: capturedBookmark.state
}
// Add the new bookmark to the HTML list
bookmarksList.append(buildBookmarkElement(bookmark));

// Open the bookmarks list div and show the applied bookmark
bookmarksList.addClass("show position");

bookmarksDropdown.addClass(displayClass);
...

// Set the captured bookmark as active


const newBookmark = "bookmark_" +
bookmarkShowcaseState.bookmarkCounter;
setBookmarkActive($(newBookmark));

Show a selected view from the bookmark list


This code sets a selected bookmark as active, highlights it in the bookmark list, and
applies the active state.

JavaScript

function onBookmarkClicked(element) {

// Set the clicked bookmark as active


setBookmarkActive($(element));

// Apply respective color to the label of the bookmark


applyColor(element.id);

// Get bookmark ID from HTML


const bookmarkId = $(element).attr("id");

// Find the bookmark in the bookmarks array


let currentBookmark = getBookmarkByID(bookmarkId);

// Apply the bookmark state

bookmarkShowcaseState.report.bookmarksManager.applyState(currentBookmark.sta
te);
}

Next steps
Enhance your users' experience with bookmarks
Power BI Embedded Analytics Playground
Quickly create personalized visuals
showcase
Article • 01/08/2023

In the Power BI embedded Quickly create personalized visuals showcase application,


users can edit existing report visuals and create their own personalized visuals, even if
they don't have previous Power BI experience. The showcase code demonstrates how to
use the Power BI report authoring APIs to create and edit several types of visualizations
at runtime. For more information about using the report authoring APIs, see the Report
authoring overview.

Quickly create personalized visuals showcase


experience
Contoso, a fictitious company, uses the Quickly create personalized visuals showcase
to present a Power BI embedded report with several visualizations of their sales data. A
column chart, area graph, bar chart, pie chart, and line graph show revenue and
opportunities as functions of industry type, salesperson, and opportunity status.

The embedded report has a Create quick visual button that users can select to create
new visuals based on the data.

Create a new quick visual


Report users can select the Create quick visual button anytime during their viewing
session to create new visuals based on the Contoso sales data.
For example, if a user wants to see a column chart that shows Actual Revenue based on
Opportunity Status, they select Create quick visual to open the Create quick visual
dialog box. The dialog box, which is defined in the application code, contains an
embedded report visual preview on the right.

In the Create quick visual dialog box, under Choose visual type, the user selects
Column chart. Different fields and values are available depending on which visual type
the user selected. For the column chart, the user selects Opportunity Status for the Axis
field and Actual Revenue for Values. Optionally, they select Estimated Revenue for
Tooltips.

After they fill out the Axis and Values fields, the user can select various formatting
options, like whether to display actual values and labels. They can also write and format
a title for the visual.

The embedded report preview in the dialog box shows the visualization as the user
builds it.

When the visual is complete, the user selects Create, and the new visualization appears
in the report.
A tooltip appears when a user hovers over a data point in visualizations. Since the user
specified Estimated Revenue under Tooltips when they created the visual, that field's
data appears in the tooltips. If the user doesn't specify a tooltip, only the axis and value
data appear in the tooltip.

Change an existing visual


Report users can change any existing visual in the report by selecting the More options
ellipsis (...) at the upper-right of the visual, and then selecting Change visual.

For example, a report user might want to change the Number of Opportunities by
Industry area chart to a column chart, because the data isn't continuous. When the user
selects Change visual, the Create quick visual dialog box opens, and the user can
change any of the settings.
In this example, the user changed the visual type to Column chart. The data now
displays as a column chart.

Quickly create personalized visuals showcase


code
The code for implementing the showcase is in the PowerBI-Embedded-Showcases
GitHub repository.

The application HTML code builds the embedded report container and elements,
dialog boxes, text fields, and buttons.

The report JavaScript code defines the visualization types, handles commands
and events, and performs all report embedding and interactions.

You can use the powerbi-report-authoring extension for the Power BI Client library to
help easily and quickly author reports and visuals. For more information, see the report
authoring overview.

For more information about creating visuals and binding them to data, see Create a
visual. For more information about visual properties, see Format visual properties.

Create and configure visuals


You create Power BI visuals by using createVisual and specifying the visual type, such
as barChart or pieChart . You then bind the visual type to properties, roles, fields, and
data. The showcase visuals.js file defines the properties, data roles, data fields, and
targets for the visual types this application supports.

In the index.js file, the following code creates an embedded visual inside the Create
quick visual dialog box, and sets and applies its properties. For example, the legend
property is enabled for pie chart visuals, but disabled for bar and column charts.

JavaScript

// Based on the state object, create a visual inside the modal


async function createVisualInsideTheModalInEditMode(visualType, dataRoles) {

// Create visual inside the modal


const newVisual = await
visualCreatorShowcaseState.page.createVisual(visualType, getVisualLayout());

// Update state
visualCreatorShowcaseState.newVisual = newVisual.visual;
visualCreatorShowcaseState.visualType = newVisual.visual.type;
const visual = newVisual.visual;
const newVisualType = visual.type;

// Enable the legend property for pie chart


if (visualCreatorShowcaseState.visualType === "pieChart") {
visual.setProperty(propertyToSelector("legend"), { schema:
schemas.property, value: true });
}

// Add properties to the created visual


Object.entries(visualCreatorShowcaseState.properties).forEach(property
=> {
let [propertyName, propertyValue] = property;
...
// Check the validity of the given property for the given visual-
type and apply it to the visual
applyValidPropertiesToTheVisual(visual, newVisualType, propertyName,
propertyValue);
});

// Disable the legend for the column and bar charts


if (visualCreatorShowcaseState.visualType === "columnChart" ||
visualCreatorShowcaseState.visualType === "barChart") {
visual.setProperty(propertyToSelector("legend"), { schema:
schemas.property, value: false });
}

Change the visual type


In the Create quick visual dialog box, all existing editing fields are available as long as
the selected visual type remains unchanged. When creating a new visual or changing
visual type, the relevant editing fields become available after the user selects the new
visual type.

The following code changes the visual type if the user edits a visual to change the type,
for example from an area chart to a column chart. For more information about changing
visual type, see Change the visual type.

JavaScript

const oldVisualType = selectedVisual.visual.type;


const oldVisual = selectedVisual.visual;
if (oldVisualType !== visualCreatorShowcaseState.visualType) {

// If visual-type is changed, remove all active data-fields on


the visual
await removeAllActiveDataRoles(oldVisual, oldVisualType);

// Change the visual type


await
oldVisual.changeType(visualCreatorShowcaseState.visualType);
}

Add the Change visual command to the More options


menu
The report embedConfiguration uses the extend menu command API to add a
changeVisual command to the report, which appears in the More options menu of each
visualization.

JavaScript

let config = {
...
settings: {
...
extensions: [
{
command: {
name: "changeVisual",
title: "Change visual",
extend: {
visualOptionsMenu: {
title: "Change visual",
menuLocation: models.MenuLocation.Top,

The configuration also hides all the default, pre-existing Power BI More options menu
commands, such as Export data and Sort. For more information about customizing
visual commands, see Customize menu commands.

Handle the Change visual and Create quick visual


selection events
The following code handles the Change visual command selection and Create quick
visual button click events. The code listens for the command or button selection, and
opens the Create quick visual modal dialog box to edit or create the visual.

JavaScript

// Listen for the commandTriggered event


baseReportState.report.on("commandTriggered", function (event) {

// Open the modal and set the fields, properties and title for the
visual
openModalAndFillState(event.detail);
});

baseReportState.report.on("buttonClicked", function () {

// Show the modal to create the visual


openModalAndFillState();
});

Next steps
Create a visual
Modify menu commands
How to handle events
Power BI Embedded Analytics Playground
Embed a report
Article • 12/05/2022

 Tip

Try embedding a report or experiment with our client APIs in the Explore our
APIs section of the Power BI Embedded Analytics Playground .

This article covers the steps for embedding a Power BI report in your application. Learn
more about reports in Reports in Power BI.

How to embed a report


When you embed Power BI content in an app, you use a configuration object to define
the content that you're embedding and to specify the content's settings. Then you pass
that object to the API. See Configure report settings for more information.

Embed an existing report


When you embed a report that already exists, use a configuration object of type
IReportLoadConfiguration.

TypeScript

interface IReportLoadConfiguration {
accessToken: string;
bookmark?: models.IApplyBookmarkRequest;
contrastMode?: models.ContrastMode;
datasetBinding?: models.IDatasetBinding;
embedUrl?: string;
filters?: models.ReportLevelFilters[];
id: string;
pageName?: string;
permissions?: models.Permissions;
settings?: models.IEmbedSettings;
slicers?: models.ISlicer[];
theme?: models.IReportTheme;
tokenType?: models.TokenType;
type: string;
viewMode?: models.ViewMode;
}

This interface includes these properties:


accessToken - The token that gives you access to the Power BI data that you're

embedding. See Understand the different embedding solutions to learn more


about access tokens.

datasetBinding - The dataset that defines the data schema that the embedded
report uses. See Bind datasets dynamically to a report for more information on
datasets.

embedUrl - The URL of the report that you're embedding. This URL becomes the
source of the HTML iframe element that contains the embedded report.
Specifically, the API assigns the URL to the src attribute of the iframe . You can
use a Report API to obtain this URL. Two examples are:
Reports - Get Report In Group
Reports - Get Reports In Group

id - The ID of the Power BI report that you're embedding.

permissions - Operations that you grant to users for the embedded report. These
values are available:
Read - Users can view the report.

ReadWrite - Users can view, edit, and save the report.


Copy - Users can save a copy of the report by using Save As.

Create - Users can create a new report.


All - Users can create, view, edit, save, and save a copy of the report.

tokenType - The kind of token that gives you access to the Power BI data that
you're embedding.
Use models.TokenType.Aad if you're embedding for your organization (the user
owns the data).
Use models.TokenType.Embed if you're embedding for your customers (the app
owns the data).

See Understand the different embedding solutions for more information.

type - The kind of content that you're embedding. Use 'report' for a Power BI

report.

The IReportLoadConfiguration interface also contains other properties. See Configure


report settings for information on these properties:

bookmark

contrastMode
filters

pageName
settings

slicers
theme

viewMode

Embed a new report


When you embed a new report that you create from a dataset, use a configuration
object of type IReportCreateConfiguration .

TypeScript

interface IReportCreateConfiguration {
accessToken: string;
datasetId: string;
embedUrl?: string;
settings?: models.IEmbedSettings;
theme?: IReportTheme;
tokenType?: models.TokenType;
type: string;
}

The properties in this interface are similar to the properties in the


IReportLoadConfiguration interface, with the following exceptions:

datasetId - The ID of the dataset that defines the data schema that the new report
uses.

embedUrl - The URL of the dataset that defines the data schema that the new
report uses. This URL becomes the source of the HTML iframe element that
contains the embedded report. Specifically, the API assigns the URL to the src
attribute of the iframe . You can use a Datasets API to obtain this URL. Two
examples are:
Datasets - Get Dataset In Group
Datasets - Get Datasets In Group

See Create, edit, and save an embedded report for information on editing and creating
reports.

Example
The following example shows how to embed a report:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
embedUrl: anEmbedUrl,
id: aReportId,
permissions: somePermissions,
tokenType: aTokenType,
type: 'report'
};

// Get a reference to the HTML element that contains the embedded report.
let embedContainer = $('#embedContainer')[0];

// Embed the report.


let report = powerbi.embed(embedContainer, embedConfiguration);

Next steps
Embed a report visual

Embed a paginated report

Configure report settings

Create, edit, and save a report

Use bootstrap for better performance


Embed a quick report in a Power BI
embedded analytics application for your
organization
Article • 05/15/2023

Power BI Client APIs allow you to quickly create an interactive report and dataset from
your application's data without your users ever needing to leave your app. By using this
client-side library, you'll provide information about the data source, which Power BI will
use to generate a dataset within the Power BI service. At the same time, Power BI will
automatically generate a report with insights about the data for your users to explore
and customize to meet their needs.

In this tutorial, you'll learn how to:

Set up your embedded environment


Configure an object to store information about your data source and customize
your report
Pass this object to the API to add data exploration capabilities to your app

To use this experience, your users will need to sign into Power BI.

You'll use a configuration object to store information about your data source.
Additionally, you can also use the configuration object to customize your report's
appearance and behavior. For instance, you can adjust the theme, and location settings
in the configuration object. When you create and embed the dataset, you then pass that
object to the API.

) Important

If you are embedding content for a national cloud, the first few steps of this tutorial
are different. See Embed content for national clouds for details.

Prerequisites
Before you start this tutorial, verify that you have both the Power BI and code
dependencies listed below:

Power BI dependencies
Your own Azure Active Directory tenant.
One of the following licenses, for testing purposes:
Power BI Free
Power BI Pro
Premium Per User (PPU)
Code dependencies
A text editor
Command line terminal, such as PowerShell

Method
The following sections explain how to embed and configure Power BI content using your
favorite text editor.

The IQuickCreateConfiguration interface displays properties that a configuration object


can supply to the Power BI Client APIs about the dataset you want to create:

Example
TypeScript

interface IQuickCreateConfiguration {
type?: "quickCreate";
accessToken: string;
settings?: ISettings;
tokenType?: TokenType;
theme?: IReportTheme;
embedUrl?: string;
datasetCreateConfig: IDatasetCreateConfiguration;
reportCreationMode?: ReportCreationMode;
eventHooks?: EventHooks;
}

Access token permission to QuickCreate


QuickCreate only supports AAD tokens. Make sure your application has the following
scopes:

Content.Create
Dataset.ReadWrite.All

Report.Read.All

Workspace.Read.All

See Register an app to embed Power BI content for more information.


Embed Url
Unique to this form of embedding, this experience has a special route /quickcreate . A
typical embed Url for this experience looks like this:
https://app.powerbi.com/quickcreate

Step 1.1 - Create a dataset without a data


source
PowerBI provides a simple way to let developers include data directly in the request to
Power BI if you are unable to set up a data source. We do limit the size of the request to
16MB. Note that, because there is no data source for Power BI to connect to, you can't
refresh the dataset after creation.

1. IDataTable

IDataTable is essentially a wrapper of a 2D string array where you should fill in your
data. Although data is an array, we only support 1 data table for now. The name
can be set by you, but it needs to match the name in ITableSchema.

In order for Power BI to parse your data in the correct format, your data values
should be formatted following the M language value specification. The locale
property defined in IQuickCreateConfiguration also affects the parsing of the
values. See M Language values - PowerQuery M to learn more.

Your data should be passed in in rows. Each row should contain the same number
of columns defined in ITableSchema.

7 Note

Data and tableSchemaList must come in pairs.

Example
TypeScript

const data: IDataTable = [


{ "name": "MyTableName",
"rows": [
["1", "1", "1991"],
["1", "1", "1991"],
]
}
]

7 Note

Currently, the name property can't be customized, so you can't name a table. The
default name for the property is "Table".

1. ITableSchema

For Power BI to understand your data, you need to provide the schema for each
column of the table. Each column schema needs to have a name and a type. The
name will be used as the field list name after the dataset is created. The type is a
subset of the M Language type specification. The supported types are conveniently
listed in DataType. See M Language types - PowerQuery M to learn more.

Similar to the data property, although tableSchemaList is defined as an array, we


only support single table for now.

TypeScript

export const enum DataType {


Number = "Number",
Currency = "Currency",
Int32 = "Int32",
Percentage = "Percentage",
DateTime = "DateTime",
DateTimeZone = "DateTimeZone",
Date = "Date",
Time = "Time",
Duration = "Duration",
Text = "Text",
Logical = "Logical",
Binary = "Binary",
}

In addition to name and dataType, users can specify default aggregation on


columns by providing an optional property aggregateFunction for each column.
The number for supported aggregate functions are based on the
AggregateFunction Enum type.

Example

TypeScript
const tableSchemaList: ITableSchema = [{
name: "MyTableName",
columns: [
{
name: "createdby",
dataType: DataType.Text
aggregateFunction: 6 // Count
},
{
name: "createdon",
dataType: DataType.DateTime
},
{
name: "size",
dataType: DataType.Number
}
]
}];
const data: IDataTable = [
{
"name": "MyTableName",
"rows": [
["1", "1", "1991"],
["1", "1", "1991"],
]
}
]
const datasetCreateConfig: IDatasetCreateConfiguration = {
"modelName": "my model",
"locale": "en_US",
"tableSchemaList": tableSchemaList,
"data": data
}

Step 1.2 - Create a dataset with your existing


data source
IDatasetCreateConfiguration is a configuration that lets Power BI know how to create
the dataset. This includes the Mashup document, the locale of the dataset, and the
connection information that tells Power BI how to connect to your data source.

Mashup document
Mashup documents, or M documents, have their own language specifications. For the
purposes of this embed experience, the easiest way to start is to connect to the data
source of your choice in Power BI Desktop and then copy the resulting mashup query
out of the query editor view. Read the Query Editor documentation for Power BI
Desktop for details.

Example

Power Query M

Let Source = Csv.Document(Web.Contents("https://yourdomain.com/sample.csv"),


[Delimiter=",", QuoteStyle=QuoteStyle.None]), #"Promoted Headers" = Table.Pr
omoteHeader(Source, [PromoteAllScalars=true]) in #"Promoted Headers";"

To turn the source code above into a mashup document, you just need to add a section.
A section includes:

section-name;
shared section-member-name = expression;
where expression will be your mashup query,
and section-member-name will show up in Power BI as table/entity name.

For the sample mashup query provided above, here is a corresponding mashup
document example:

Power Query M

"section Section1; shared #"Table" = let Source = Csv.Document(Web.Contents(


"https://yourdomain.com/sample.csv"),
[Delimiter=",", QuoteStyle=QuoteStyle.None]), #"Promoted Headers" = Table.Pr
omoteHeaders(Source, [PromoteAllScalars=true]) in #"Promoted Headers";"

Once you have your mashup document, you can identify which parts will be static and
which parts will be dynamic and can be filled in programmatically. In the example above,
we have some adjustable variables, the web content domain, the delimiter, the quote
style, and if you want to promote the headers or not. Therefore, the query can be turned
into a template and populated with the appropriate parameters on the hosting
application side, depending on data the user is consuming at the time.

Locale
PowerBI will use the locale information provided in this configuration to evaluate the
mashup document and parse values if raw data is provided.

Data source configuration


Authorization to the data source
Currently, we only support anonymous connection to data sources. This means Power BI
needs to be able to connect to your data source without requiring authentication.

7 Note

If you include the data directly in the request, you should omit the
dataSourceConnection property.

DataCacheMode

For most data sources, Import mode should suit your needs. However, in some cases
where data changes quickly or when data sources are very big, you can also use the
DirectQuery mode. If you think this might apply to you, read learn more about
DirectQuery in Power BI.

7 Note

If you include raw data in the request, the DataCacheMode must be imported.

Sample

TypeScript

const datasetCreateConfig: IDatasetCreateConfiguration = {


"modelName": "temp model",
"locale": "en_US",
"mashupDocument": "section Section1; shared Table = let
Source = Csv.Document(Web.Contents(\"https://yourdomain.com/sample.csv\"),
[Delimiter=\",\", QuoteStyle=QuoteStyle.None]),
#\"Promoted Headers\" = Table.PromoteHeaders(Source, [PromoteAllScalars=true
]) in #\"Promoted Headers\";",
"dataSourceConnection": {
"credentialType": CredentialType.Anonymous, // =1
"dataCacheMode": DataCacheMode.Import // =1
}
}

Step 2 - Create a dataset and auto-generate


report
Now with the datasetCreateConfig set, you're ready to generate the dataset and embed
an auto-generated report. This is similar to the createReport method that allows you to
create in report embed, the quickCreate method that takes in an iframe container, and
the quickCreateConfig method that helps you embed the report.

Example
TypeScript

const powerbi = window.powerbi;


const iframeContainer = document.getElementById("myIframeContainer");
const quickCreateConfig: IQuickCreateConfiguration = {
type: "quickCreate",
accessToken: "ey.....",
tokenType: TokenType.Aad, // Aad token only
embedUrl: "https://app.powerbi.com/quickcreate", // see below for
generating the embed url
datasetCreateConfig: datasetCreateConfig,
reportCreationMode: ReportCreationMode.QuickExplore, // QuickExplore for
auto-generated visual,
settings: {
localeSettings: {
language: "en_US" // this should match the current locale of
your window/product. It will be used to localize the UI.
}
}
};
const quickCreateReport = powerbi.quickCreate(iframeContainer,
quickCreateConfig);

Next Steps
Understanding the different embedding solutions

Embed a report in Power BI embedded analytics


Embed a report visual
Article • 10/28/2021

 Tip

Try embedding a report visual or experiment with our client APIs in the Explore our
APIs section of the Power BI Embedded Analytics Playground .

This article covers the steps for embedding a visual in your application. Learn more
about visuals in Visuals in Power BI.

How to embed a visual


When you embed Power BI content in an app, you use a configuration object to define
the content that you're embedding and to specify the content's settings. Then you pass
that object to the API.

When you embed a visual, use a configuration object of type IVisualLoadConfiguration :

TypeScript

interface IVisualLoadConfiguration {
accessToken?: string;
embedUrl?: string;
id?: string;
pageName: string;
tokenType?: models.TokenType;
type: string;
visualName: string;
}

This interface includes these properties:

accessToken - The token that gives you access to the Power BI data that you're

embedding. See Understand the different embedding solutions to learn more


about access tokens.

embedUrl - The URL of the report that contains the visual that you're embedding.
This URL becomes the source of the HTML iframe element that contains the
embedded visual. Specifically, the API assigns the URL to the src attribute of the
iframe . You can use a Report API to obtain this URL. Two examples are:
Reports - Get Report In Group
Reports - Get Reports In Group

id - The ID of the Power BI report that contains the visual that you're embedding.

pageName - The name of the page that contains the visual that you're embedding.

You can use the Report getPages method to obtain the pages in a report.

tokenType - The kind of token that gives you access to the Power BI data that

you're embedding.
Use models.TokenType.Aad if you're embedding for your organization (the user
owns the data).
Use models.TokenType.Embed if you're embedding for your customers (the app
owns the data).

See Understand the different embedding solutions for more information.

type - The kind of content that you're embedding. Use 'visual' for a visual.

visualName - The name of the visual that you're embedding. You can use the Page

getVisuals method to obtain the visuals in a page.

Example
The following example shows you how to embed a single visual:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
embedUrl: anEmbedUrl,
id: aReportId,
pageName: aPageName,
tokenType: aTokenType,
type: 'visual',
visualName: aVisualName
};

// Get a reference to the HTML element that contains the embedded report.
let embedContainer = $('#embedContainer')[0];

// Embed the visual.


let visual = powerbi.embed(embedContainer, embedConfiguration);
Filters
By default the updateFilters API will apply visual level filters when embedding a single
report visual. This can cause a conflict with filters applied in the embed configuration
object, as these are applied at the report level. To fix this issue, you can set the filters
level with the API:

JavaScript

await visual.updateFilters(FiltersOperations.Add, filters,


FiltersLevel.Report);

Learn more about filters in Control report filters.

Next steps
Embed a report

Embed a paginated report

Embed a standalone Q&A visual

Use bootstrap for better performance


Embed a paginated report
Article • 09/18/2023

 Tip

Try embedding a paginated report or experiment with our client APIs in the Explore
our APIs section of the Power BI Embedded Analytics Playground .

This article covers the steps for embedding a paginated report in your application. Learn
more about paginated reports in What are paginated reports in Power BI Premium?.

How to embed a paginated report


When you embed Power BI content in an app, you define the content and specify its
settings in a configuration object. Then you pass that object to the API.

When you embed a paginated report, use a configuration object of type


IPaginatedReportLoadConfiguration:

TypeScript

export interface IPaginatedReportLoadConfiguration {


accessToken: string;
id: string;
embedUrl?: string;
settings?: IPaginatedReportSettings;
tokenType?: TokenType;
type?: string;
parameterValues?: IPaginatedReportParameter[];
}

This interface contains the following properties:

accessToken - The token that gives you access to the Power BI data that you're
embedding. See Understand the different embedding solutions to learn more
about access tokens.

embedUrl - The URL of the report that you're embedding. This URL becomes the
source of the HTML iframe element that contains the embedded report.
Specifically, the API assigns the URL to the src attribute of the iframe. You can use
a Report API to obtain this URL. Two examples are:
Reports - Get Report In Group
Reports - Get Reports In Group

We recommend passing report parameters to the report using the


parameterValues property described below. However, you can also pass

parameters to the report by adding the query string to the end of the embed URL.
Read more about passing URL parameters in paginated reports. See examples of
passing parameters to a URL.

id - The ID of the Power BI report that you're embedding.

hostname - The default hostname value is app.powerbi.com. If you're using a


sovereign cloud, provide the URL here. If you provided a value for embedURL , the
hostname will be ignored.

settings - A configuration object of type IPaginatedReportSettings. This object


specifies information about the appearance of the report's parameter panel. The
parameter panel is the bar underneath the action bar which can be expanded or
hidden.

You can show or hide the parameter panel by clicking the Parameters button on
the action bar. That button is available by default. But if you configure the
panel's enabled property to be false , the Parameters button isn't available.

By default, the API collapses the parameter panel. If you set the panel's
expanded property to true , the API loads the report with this panel expanded.

This code shows one way to configure the settings property:

JavaScript

settings: {
commands: {
parameterPanel: {
enabled: true,
expanded: true
}
}
}

tokenType - The kind of token that gives you access to the Power BI data that
you're embedding.
Use models.TokenType.Aad if you're embedding for your organization (user owns
data).
Use models.TokenType.Embed if you're embedding for your customers (app owns
data).

See Understand the different embedding solutions for more information.

parameterValues – A configuration object of type IPaginatedReportParameter. Set


the report parameters using this property. This method uses the JavaScript SDK
and is the preferred method of passing report parameters. For example:

JavaScript

parameterValues: [
{name: "State", value: "WA"},
{name: "City", value: "Seattle"},
{name: "City", value: "Bellevue"},
{name: "City", value: "Redmond"}
]

This method can only be used to pass report parameters (those parameters that
have a URL prefix rp: ) and not rdl parameters (with the URL prefix rdl: ).

Example
The following example shows you how to embed a paginated report:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
embedUrl: anEmbedUrl,
uniqueId: aReportId,
tokenType: aTokenType,
type: 'report',
datasetBindings: [{
sourceDatasetId: "originalDatasetId",
targetDatasetId: "notOriginalDatasetId"
}]
};

// Get a reference to the HTML element that contains the embedded report.
let embedContainer = $('#embedContainer')[0];

// Embed the report.


let report = powerbi.embed(embedContainer, embedConfiguration);

Make sure you include all DatasetIds used for binding in the multi-resource embed
token.

Considerations and limitations


To use dynamic binding, see Bind datasets dynamically to a paginated report
visual.
The bootstrapped method isn't supported for paginated reports.
Multi-value parameters aren't supported when embedding a paginated report.
The parameterValues property can only be used for report parameters. It can't be
used for rdl parameters.
Embedding a paginated report with a real-time dataset (push dataset) is not
supported.

Next steps
Embed a report
What are paginated reports?
Explore our APIs
Embed a standalone Q&A visual
Article • 12/05/2022

 Tip

Try embedding a Q&A or experiment with our client APIs in the Explore our APIs
section of the Power BI Embedded Analytics Playground .

This article covers the steps for embedding a standalone Q&A visual in your application.

This feature provides a way for users to ask questions. They then receive immediate
answers in the form of visuals like charts or graphs. Learn more about this feature in
Create a Q&A visual in Power BI.

How to embed Q&A


When you embed Power BI content in an app, you use a configuration object to define
the content that you're embedding and to specify the content's settings. Then you pass
that object to the API.

When you embed Q&A, use a configuration object of type ILoadQnaConfiguration:

TypeScript
interface ILoadQnaConfiguration {
accessToken: string;
datasetIds: string[];
embedUrl: string;
question?: string;
tokenType?: models.TokenType;
type: string;
viewMode?: models.QnaMode;
}

This interface contains the following properties:

accessToken - The token that gives you access to the Power BI data that you're
embedding. See Understand the different embedding solutions to learn more
about access tokens.

datasetIds - The IDs of the datasets that define the data schemas that the
embedded Q&A uses. You can use a Datasets API to obtain the datasets. Two
examples are:
Datasets - Get Dataset In Group
Datasets - Get Datasets In Group

7 Note

Currently you can only configure one dataset.

embedUrl - The URL of the dataset for the Q&A that you're embedding. This URL
becomes the source of the HTML iframe element that contains the embedded
Q&A. Specifically, the API assigns the URL to the src attribute of the iframe . You
can use a Datasets API to obtain this URL. Two examples are:
Datasets - Get Dataset In Group
Datasets - Get Datasets In Group

question - The question that determines the visualization that the API displays.

This property is only used in result mode.

tokenType - The kind of token that gives you access to the Power BI data that

you're embedding.
Use models.TokenType.Aad if you're embedding for your organization (the user
owns the data).
Use models.TokenType.Embed if you're embedding for your customers (the app
owns the data).
See Understand the different embedding solutions for more information.

type - The kind of content that you're embedding. Use 'qna' for Q&A.

viewMode - The mode of the embedded Q&A. Two modes are available:

Interactive - The user can enter questions. The API displays the questions and
updates the visual accordingly.
ResultOnly You supply a specific question. The API displays that question and

its visual.

This example shows you how to embed Q&A:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
datasetIds: [aDatasetID],
embedUrl: anEmbedUrl,
question: aTextQuestion,
tokenType: aTokenType,
type: 'qna',
viewMode: QnaMode.ResultOnly
};

// Get a reference to the HTML element that contains the embedded Q&A.
let embedContainer = $('#embedContainer')[0];

// Embed the Q&A.


let visual = powerbi.embed(embedContainer, embedConfiguration);

Change the displayed question


If you use a viewMode of ResultOnly and provide a question, you can use the
setQuestion method to change the displayed question. The API then changes the
displayed visual.

You might use this method for a list of frequently asked questions. As the user goes
through the questions, you can display the answers within the embedded element.

The PowerBI JavaScript Qna class defines the setQuestion method as:

JavaScript

setQuestion(question: string): Promise<void>


The question parameter contains a question in text format.

This example shows how to use this method to change the displayed question:

JavaScript

// Get a reference to the embedded Q&A HTML element.


let qnaContainer = $('#qnaContainer')[0];

// Get a reference to the embedded Q&A.


let qna = powerbi.get(qnaContainer);

// Change the displayed question.


await qna.setQuestion("This year sales");

Capture your users' questions


If you use a viewMode of Interactive , the API can notify your app when the displayed
visual changes. Whenever the visual changes in response to an updated input query, the
embedded component emits a visualRendered event. If your app listens to this type of
event, your code can respond to the new query.

For instance, you can record the questions that users enter. You might use these
questions later, for AI or telemetry purposes.

Use code like these lines to listen to visualRendered events:

JavaScript

qna.on("visualRendered", function(event) {
...
});

See How to handle events for more information on listening to events.

Limitations
The embedded Q&A uses data schemas. Currently you can only configure one schema,
not multiple schemas.

Next steps
Embed a report
Embed a report visual

Use bootstrap for better performance


Embed a dashboard
Article • 12/05/2022

This article covers the steps for embedding a dashboard in your application. Learn more
about dashboards in Introduction to dashboards for Power BI designers.

 Tip

Try embedding a dashboard or experiment with our client APIs in the Explore our
APIs section of the Power BI Embedded Analytics Playground .

How to embed a dashboard


When you embed Power BI content in an app, you use a configuration object to define
the content that you're embedding and to specify the content's settings. Then you pass
that object to the API.

When you embed a dashboard, use a configuration object of type


IDashboardLoadConfiguration:

TypeScript

interface IDashboardLoadConfiguration {
accessToken: string;
embedUrl?: string;
id: string;
pageView?: models.PageView
tokenType?: models.TokenType;
type: string;
}

This interface contains the following properties:

accessToken - The token that gives you access to the Power BI data that you're
embedding. See Understand the different embedding solutions to learn more
about access tokens.

embedUrl - The URL of the dashboard that you're embedding. This URL becomes

the source of the HTML iframe element that contains the embedded dashboard.
Specifically, the API assigns the URL to the src attribute of the iframe . You can
use a Dashboards API to obtain this URL. Two examples are:
Dashboards - Get Dashboard In Group
Dashboards - Get Dashboards In Group

id - The ID of the dashboard that you're embedding. Use a Dashboards API to


obtain this ID. For example:
Dashboards - Get Dashboard In Group
Dashboards - Get Dashboards In Group

pageView - The format that the API uses for the embedded dashboard. Possibilities

include:
fitToWidth - The embedded dashboard's width matches the width of the div

element that contains the dashboard.


oneColumn - The embedded dashboard appears in one column.

actualSize - The API displays the embedded dashboard at full size.

tokenType - The kind of token that gives you access to the Power BI data that
you're embedding.
Use models.TokenType.Aad to embed for your organization (user owns data).
Use models.TokenType.Embed to embed for your customers (app owns data).

See Understand the different embedding solutions for more information.

type - The kind of content that you're embedding. Use 'dashboard' for a
dashboard.

Example
The following example shows you how to embed a single dashboard:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
embedUrl: anEmbedUrl,
id: aDashboardId,
pageView: 'fitToWidth',
tokenType: aTokenType,
type: 'dashboard'
};

// Get a reference to the HTML element that contains the embedded dashboard.
let dashboardContainer = $('#dashboardContainer')[0];

// Embed the dashboard.


let dashboard = powerbi.embed(dashboardContainer, embedConfiguration);
Considerations and limitations
Embedding dashboards on EM SKUs is not supported

When you embed content, your app displays the content in a div element. If you
use a pageView value of actualSize when you embed a dashboard:
If the dashboard is wider than the div element, the API uses the width of the
div element as the width of the embedded dashboard.

If the dashboard is narrower than the div element, the API fills the unused
space with the embedded background. By default, that background is white, but
you can configure it to be transparent. In that case, the div element's styling is
visible in the unused space.

Next steps
Embed a report

Embed a dashboard tile

Use bootstrap for better performance


Embed a dashboard tile
Article • 12/05/2022

 Tip

Try embedding a dashboard tile or experiment with our client APIs in the Explore
our APIs section of the Power BI Embedded Analytics Playground .

This article covers the steps for embedding a dashboard tile in your application. Learn
more about dashboard tiles in Intro to dashboard tiles for Power BI designers.

How to embed a dashboard tile


When you embed Power BI content in an app, you use a configuration object to define
the content that you're embedding and to specify the content's settings. Then you pass
that object to the API.

When you embed a dashboard tile, use a configuration object of type


ITileLoadConfiguration:

TypeScript

interface ITileLoadConfiguration {
accessToken: string;
dashboardId: string;
embedUrl: string;
id: string;
tokenType?: models.TokenType;
type: string;
}

This interface contains the following properties:

accessToken - The token that gives you access to the Power BI data that you're
embedding. See Understand the different embedding solutions to learn more
about access tokens.

dashboardId - The ID of the dashboard that contains the tile that you're

embedding. You can use a Dashboards API to obtain this ID. Two examples are:
Dashboards - Get Dashboard In Group
Dashboards - Get Dashboards In Group
embedUrl - The URL of the dashboard tile that you're embedding. This URL

becomes the source of the HTML iframe element that contains the embedded
dashboard tile. Specifically, the API assigns the URL to the src attribute of the
iframe . You can use a Dashboards API to obtain this URL. Two examples are:
Dashboards - Get Tile In Group
Dashboards - Get Tiles In Group

id - The ID of the dashboard tile that you're embedding. You can use a
Dashboards API to obtain this ID. Two examples are:
Dashboards - Get Tile In Group
Dashboards - Get Tiles In Group

tokenType - The kind of token that gives you access to the Power BI data that
you're embedding.
Use models.TokenType.Aad if you're embedding for your organization (the user
owns the data).
Use models.TokenType.Embed if you're embedding for your customers (the app
owns the data).

See Understand the different embedding solutions for more information.

type - The kind of content that you're embedding. Use 'tile' for a dashboard

tile.

Example
The following example shows you how to embed a single dashboard tile:

JavaScript

// Set up the configuration object that determines what to embed and how to
embed it.
let embedConfiguration = {
accessToken: anAccessToken,
dashboardId: aDashboardId,
embedUrl: anEmbedUrl,
id: aTileId,
tokenType: aTokenType,
type: 'tile'
};

// Get a reference to the HTML element that contains the embedded dashboard
tile.
let tileContainer = $('#tileContainer')[0];
// Embed the dashboard.
let tile = powerbi.embed(tileContainer, embedConfiguration);

Next steps
Embed a report

Embed a report visual

Embed a dashboard

Use bootstrap for better performance


Embed a Power BI item in a React
application
Article • 12/05/2022

When creating a Power BI embedded analytics application, React can help you optimize
performance with bootstrap integration, while using all of the client-side APIs, including
report authoring. It also simplifies the Power BI embed lifecycle management in your
application. The Power BI React component supports both JavaScript and TypeScript and
helps you embed your analytics in a React web application.

The React library lets you embed the following Power BI items:

Reports
Dashboards
Dashboard tiles
Report visuals
Q&A

How to embed a Power BI item in a React web


app
This section describes how to import React into your app and use it to embed a Power
BI report.

For detailed usage information, see the Power BI React readme file.

Import the React library


The Power BI React component can be found on NPM . It's also open sourced on
GitHub .

To import React into your web app, add the imports listed below.

JavaScript

import { PowerBIEmbed } from 'powerbi-client-react';


import { models } from 'powerbi-client';

Embed the report with React


This example shows how to embed a Power BI report using React. Below the example
you can find a description for each component in the code sample.

JavaScript

embedConfig = {
{
type: 'report', // Supported types: report, dashboard, tile, visual,
and qna.
id: '<Report Id>',
embedUrl: '<Embed Url>',
accessToken: '<Access Token>',
tokenType: models.TokenType.Embed, // Use models.TokenType.Aad if
you're embedding for your organization.
settings: {
panes: {
filters: {
expanded: false,
visible: false
}
},
}
}
}

eventHandlers = {
new Map([
['loaded', function () {
console.log('Report loaded');
}],
['rendered', function () {
console.log('Report rendered');
}],
['error', function (event) {
console.log(event.detail);
}]
])
}

cssClassName = {
"report-style-class"
}

getEmbeddedComponent = {
(embeddedReport) => {
window.report = embeddedReport;
}
}

The following list includes descriptions or additional information for each component in
the code snippet example.
Embed config - Defines the content that you're embedding, and specifies the
content's settings. The embed configuration changes when you embed the
following Power BI items:
Report
Report visual
Paginated report
Standalone Q&A visual
Dashboard
Dashboard tile

eventHandlers - A map object for event names and their handlers. See How to
handle events for more information.

cssClassName - Gives the embedded item a CSS class names that let you control
the style of the embedded iframe using CSS.

getEmbedComponent - A callback that helps you get the embedded instance, so


that you can use all of the APIs the Power BI Client library allows. For example,
when embedding a report, you will get an instance of the Report class.

Bootstrap a component
powerbi.bootstrap is a method used to help developers embed Power BI items faster

and get better performance. For more information, see Use bootstrap for better
performance.

JavaScript

embedConfig = {
{
type: 'report', // Supported types: report, dashboard, tile, visual,
and qna.
id: undefined,
embedUrl: undefined,
accessToken: undefined, // Keep as an empty string, null, or
undefined.
tokenType: models.TokenType.Embed
}
}

React demo
The React repository includes a demo that illustrates the complete flow of
bootstrapping a report, embedding, and updating the embedded report. It also
demonstrates the usage of the powerbi report authoring library by deleting a visual from
a report upon clicking the Delete a Visual button.

For more information, see the demo section of the readme file.

Running the demo


The demo is a subfolder in the repository. To run the demo on localhost, follow these
steps:

1. Run the following commands:

Bash

npm run install:demo


npm run demo

2. To view in your browser, redirect it to http:/localhost:8080/ .

Next steps
Embed a report

Embed a report visual

Use bootstrap for better performance


Configure report settings

Create, edit, and save a report


Embed Power BI content in an Angular
application
Article • 12/05/2022

When creating a Power BI embedded analytics application, Angular can help quickly set
up a maintainable, scalable app. Angular adds structure and design patterns to front-
end development, allowing developers to create more advanced web applications that
are easier to maintain and update.

The Power BI Angular library lets you embed the following Power BI items into your
Angular application:

Reports
Dashboards
Dashboard tiles
Report visuals
Q&A
Paginated reports

How to embed Power BI content in an Angular


web app
This section describes how to import Angular into your app and use it to embed a
Power BI report.

For detailed usage information, see the Power BI Angular readme file.

Import the Angular library


You can find the Power BI Angular component on NPM . It's also open sourced on
GitHub .

To import Angular into your web app, add the imports listed below.

JavaScript

import { PowerBIEmbedModule } from 'powerbi-client-angular';

@NgModule({
imports: [
...
...
PowerBIEmbedModule
],
exports: ...,
declarations: ...
})

Embed the report with Angular


This example shows how to embed a Power BI report using Angular. Below the example
is a description of each component in the code sample.

JavaScript

<powerbi-report
[embedConfig] = {{
type: "report",
id: "<Report Id>",
embedUrl: "<Embed Url>",
accessToken: "<Access Token>",
tokenType: models.TokenType.Embed,
settings: {
panes: {
filters: {
expanded: false,
visible: false
}
},
background: models.BackgroundType.Transparent,
}
}}

[cssClassName] = { "reportClass" }

[phasedEmbedding] = { false }

[eventHandlers] = {
new Map([
['loaded', () => console.log('Report loaded');],
['rendered', () => console.log('Report rendered');],
['error', (event) => console.log(event.detail);]
])
}
>
</powerbi-report>

The following list includes descriptions or additional information for each component in
the code snippet example.
embedConfig - Defines the content that you're embedding, and specifies the
content's settings. The embed configuration changes when you embed the
following Power BI items:
Report
Report visual
Paginated report
Standalone Q&A visual
Dashboard
Dashboard tile

eventHandlers - A map object for event names and their handlers. See How to
handle events for more information.

cssClassName - Gives the embedded item a CSS class names that let you control
the style of the embedded iframe using CSS.

phasedEmbedding - Improves the end-user's experience by giving developers


more flexibility to phase report embedding. See Use phased embedding for more
information.

Bootstrap a Power BI report


powerbi.bootstrap is a method used to help developers embed Power BI items faster

and get better performance. For more information, see Use bootstrap for better
performance.

JavaScript

<powerbi-report
[embedConfig] = {{
type: "report",
id: undefined,
embedUrl: undefined,
accessToken: undefined, // Keep as empty string, null or undefined
tokenType: models.TokenType.Embed,
hostname: "https://app.powerbi.com"
}}
>
</powerbi-report>

To embed the report after bootstrapping, update the embedConfig (with at least
accessToken and embedUrl).
Angular demo
The Angular repository includes a demo that embeds a sample report using the
PowerBIReportEmbed component. It demonstrates the complete flow from
bootstrapping the report, to embedding and updating the embedded report. It also
demonstrates the usage of the powerbi report authoring library by deleting a visual from
a report upon clicking the Delete a Visual button. It also sets a 'DataSelected' event.

For more information, see the demo section of the readme file.

Run the demo


The demo is a subfolder in the repository. To run the demo on localhost, follow these
steps:

1. Run the following commands:

Bash

npm run demo

2. To view in your browser, redirect it to http:/localhost:4200/ .

Next steps
Embed a report
Embed a report visual
Create, edit, and save a report
Embed Power BI content in a Vue
application
Article • 12/05/2022

Vue is a JavaScript framework for building front-end user interfaces and websites. The
Vue component enables you to embed Power BI content in your Vue application simply,
allowing you to make the most of both Vue and Power BI embedded.

The Power BI vue.js library lets you embed the following Power BI items into your Vue
application:

Reports
Dashboards
Dashboard tiles
Report visuals
Q&A
Paginated reports

How to embed Power BI content in a Vue web


app
This section describes how to import Vue into your app and use it to embed a Power BI
report.

For detailed usage information, see the Power BI Vue readme file.

Import the Vue library


You can find Power BI Vue components on NPM . It's also open sourced on GitHub .

To import Vue into your web app, add the imports listed below.

JavaScript

import { PowerBIEmbedModule } from 'powerbi-client-vue-js';

Embed the report with Vue


This example shows how to embed a Power BI report using Vue. Below the example is a
description of each component in the code sample.

JavaScript

<powerbi-report
[embedConfig] = {{
type: "report",
id: "<Report Id>",
embedUrl: "<Embed Url>",
accessToken: "<Access Token>",
tokenType: models.TokenType.Embed,
settings: {
panes: {
filters: {
expanded: false,
visible: false
}
},
background: models.BackgroundType.Transparent,
}
}}

[cssClassName] = { "reportClass" }

[phasedEmbedding] = { false }

[eventHandlers] = {
new Map([
['loaded', () => console.log('Report loaded');],
['rendered', () => console.log('Report rendered');],
['error', (event) => console.log(event.detail);]
])
}
>
</powerbi-report>

The following list includes descriptions or additional information for each component in
the code snippet example.

embedConfig - Defines the content that you're embedding, and specifies the
content's settings. The embed configuration changes when you embed the
following Power BI items:
Report
Report visual
Paginated report
Standalone Q&A visual
Dashboard
Dashboard tile
cssClassName - Gives the embedded item a CSS class names that let you control
the style of the embedded iframe using CSS.

phasedEmbedding - Improves the end-user's experience by giving developers


more flexibility to phase report embedding. See Use phased embedding for more
information.

eventHandlers - A map object for event names and their handlers. See How to
handle events for more information.

Bootstrap a Power BI report


powerbi.bootstrap is a method used to help developers embed Power BI items faster
and get better performance. For more information, see Use bootstrap for better
performance.

JavaScript

<powerbi-report
[embedConfig] = {{
type: "report",
id: undefined,
embedUrl: undefined,
accessToken: undefined, // Keep as empty string, null or undefined
tokenType: models.TokenType.Embed,
hostname: "https://app.powerbi.com"
}}
>
</powerbi-report>

To embed the report after bootstrapping, update the embedConfig (with at least
accessToken and embedUrl).

Vue demo
The Vue repository includes a demo that embeds a sample report using the
PowerBIReportEmbed component. It demonstrates the complete flow from
bootstrapping the report, to embedding and updating the embedded report. It also
demonstrates how to use the powerbi report authoring library by enabling the user to
change the type of visual from a report using the Change visual type button. It also sets
a 'DataSelected' event.

For more information, see the demo section of the readme file.
Run the demo
The demo is a subfolder in the repository. To run the demo on localhost, follow these
steps:

1. Run the following commands:

Bash

npm run demo

2. To view in your browser, redirect it to http:/localhost:3000/ .

Next steps
Embed a report
Embed a report visual
Create, edit, and save a report
Embed a Power BI component in a
Jupyter notebook
Article • 04/27/2023

The Jupyter notebook makes creating and sharing Power BI reports simple. With Jupyter
notebook you can embed or create reports quickly.

The powerbiclient Python package lets you embed Power BI reports in Jupyter
notebooks easily. You can export data from visuals in a Power BI report to the Jupyter
notebook for in-depth data exploration. You can also filter the report for quick analysis
or use bookmarks to apply a saved view.

Install the Power BI Client package


The powerbiclient package can be found on PyPI . It's also open sourced on
GitHub .

To install the package you can use pip .

If you are using Jupyter notebook:

Python

pip install powerbiclient

If you are using JupyterLab:

Python

pip install powerbiclient


jupyter labextension install @jupyter-widgets/jupyterlab-manager

If you are using Jupyter Notebook 5.2 or earlier, you may also need to enable the
nbextension:

Python

jupyter nbextension enable --py [--sys-prefix|--user|--system]


powerbiclient
Embed a Power BI report in a Jupyter notebook

For detailed usage information, see the GitHub wiki .

Embed a report
This example shows how to embed a Power BI report using the package.

1. Import Report class and models from the package:

Python

from powerbiclient import Report, models

2. Authenticate against Power BI using Azure AD:

Python

# Import the DeviceCodeLoginAuthentication class to authenticate


against Power BI
from powerbiclient.authentication import DeviceCodeLoginAuthentication
# Initiate device authentication
device_auth = DeviceCodeLoginAuthentication()

3. Set the workspace ID and report ID you’d like to embed:

Python

group_id="Workspace ID"
report_id="Report ID"

4. Create an instance of Power BI report and load the report to the output cell:

Python

report = Report(group_id=group_id, report_id=report_id,


auth=device_auth)

report

Run the demo


The GitHub repository includes a demo Jupyter notebook that embeds a user's
report. It demonstrates the complete flow of embedding and interacting with Power BI
report, including:

Report event handlers


Get list of pages
Get list of visuals
Export and visualize visual data
Apply filters

To run the demo:

1. Make sure you have the following prerequisites:

pandas
matplotlib

2. Run the following commands:

Python

cd demo
jupyter notebook
3. Run demo.ipynb .

Quick create a report


You can also easily generate a Power BI quick report from your data in just a few steps.
Use any DataFrame in your notebook to quickly transform it into insightful
visualizations'. Save the report, if you want, and use it as you would any other report.

For a detailed description, see Quick create a report using Jupyter notebook. For a demo
Jupyter notebook, see the GitHub repository .

Next steps
Embed and visualize with Power BI in Jupyter Notebooks video
Embed a report
Configure report settings
How to handle events
Article • 10/28/2021

 Tip

Experiment with APIs in real time using your own report or our sample report in the
Developer sandbox section of the Power BI Embedded Analytics Playground .

Events are used to communicate between the Power BI component (for example, a
report) and the web application code.

An embedded component emits events after an action is executed inside the


component. These can be user interactions or an automated action (like a visual being
rendered) within the component.

For example, buttonClicked is an event emitted by a Power BI report when a user clicks
a button in the report. You can listen to the event by using report.on(...) , and then set
an event handler.

An example of how to handle an event


This example shows how to handle a report event. To learn about other types of events,
see Events and their response values.

7 Note

Wait for the component to load before using the APIs. Listen to the loaded event
and then issue new commands.

JavaScript

report.on('loaded', function(event)
{
reportPages = await report.getPages();
});

How to remove event handlers


You can use report.off(...) to remove all event handlers for a specific event.
Events and their response values
View a full list of possible events and their response values.

Error events (relevant for all embeds)


An error event is emitted to describe a failed operation.

JavaScript

interface IError {
message: string // A general message that describes the operation that
failed (example: "Could not set page")
detailedMessage?: string // Detailed message that describes the error
errorCode?: string // Short message that describes the error
level?: TraceType // The level of the error (example: 'Fatal')
technicalDetails?: ITechnicalDetails
}

interface ITechnicalDetails {
requestId?: string // Id for debugging - should be provided when
reporting a bug
}

7 Note

Only the message property is required, and the other properties might be
undefined.

Report events
A report event is emitted for an interaction with an embedded report, such as clicking a
report button or rendering a visual.

buttonClicked

The buttonClicked event is raised when a user clicks on a Report button.

JavaScript

id: string
title?: string
type?: string (type of button)
bookmark?: string
commandTriggered

The commandTriggered event is raised when a user clicks on an extension command.

JavaScript

command: string
dataPoints?: IIdentityValue[]
report: models.IReport
page: models.IPage
visual: models.IVisual

dataHyperlinkClicked

The dataHyperlinkClicked event is raised when a hyperlink is clicked, and the hyperlink's
behavior is set to NavigateAndRaiseEvent or RaiseEvent .

JavaScript

url: string
report: models.IReport
page: models.IPage
visual: models.IVisual

For more information, see Configure report settings.

dataSelected

The dataSelected event is raised when a specific data point is selected.

JavaScript

report: models.IReport
page: models.IPage
visual: models.IVisual
filters: IFilter[]
dataPoints: IIdentityValue[]

loaded

The loaded event is raised when the report initializes. Loading is complete when the
Power BI logo disappears.
pageChanged
The pageChanged event is raised whenever a page is changed.

JavaScript

newPage: Models.IPage

rendered
The rendered event is raised when a report is fully rendered. For example, if all visuals
are rendered upon loading a report or after a user interaction.

saveAsTriggered
The saveAsTriggered event is raised when a user clicks on Save As in the UI. This lets
you create your own dialog for the Save As action.

saved

The saved event is raised when a save is triggered by a save or saveAs action in the UI
or by using the APIs.

selectionChanged
The selectionChanged event is raised whenever the user is changing the selected visual.
selectedItems is a list of all selected visuals when more than one is selected.

JavaScript

report: models.IReport
page: models.IPage
visual?: models.IVisual
selectedItems?: models.IVisual[]

visualClicked
The visualClicked event is raised every time a visual is clicked.

JavaScript
report: models.IReport
page: models.IPage
visual: models.IVisual

visualRendered
The visualRendered event is raised when a visual is rendered (requires setting
visualRenderedEvents to true in the settings object).

7 Note

Because visuals might render due to user interactions, it's recommended that this
event only be turned on when needed.

JavaScript

name: string

For more information, see Configure report settings.

Report Embed Mobile events


A Report Embed Mobile event is emitted for an interaction with an embedded report in
a mobile layout, such as the beginning or end of a swipe.

swipeStart and swipeEnd events


swipeStart or swipeEnd events are raised when a user begins or ends a swipe

movement on an embedded report.

JavaScript

interface ISwipeEvent {
currentPosition: IPosition
startPosition: IPosition
}

interface IPosition {
x: number
y: number
}
Dashboard events
A dashboard event is emitted when the dashboard is loaded and when a user clicks on a
tile in the dashboard.

loaded

The loaded event is raised when the dashboard initializes.

tileClicked

The tileClicked event is raised when an end user clicks a tile. It is not raised for pinned
live pages.

JavaScript

tileId: string
navigationUrl: string
pageName: string
reportEmbedUrl: string

Q&A events
A question and answer (Q&A) event is raised when a visual is rendered after entering a
question.

visualRendered (Q&A)
The visualRendered event is raised when a visual is rendered after a question is entered
and an answer displays.

JavaScript

question: string
normalizedQuestion: string

Tile events
A Tile event is raised when a user clicks on a tile.

tileClicked (tile event)


The tileClicked event is raised when an end user clicks a tile. It is not raised for pinned
live pages.

JavaScript

tileId: string
navigationUrl: string
pageName: string
reportEmbedUrl: string

tileLoaded

The tileLoaded event is raised when the tile initializes. Loading is complete when the
Power BI logo disappears.

Next steps
Configure report settings

Modify menu commands for a report visual

Page navigation

Create, edit, and save an embedded report


Refresh the access token
Article • 12/05/2022

Embedding and interacting with Power BI content (reports, dashboards and tiles)
requires an access token. The access token can be either an Azure AD token, when
embedding for your organization, or an embed token, when embedding for your
customers. The access token has an expiration time, which means that after embedding
a Power BI item, you have a limited amount of time to interact with it. To give your users
a continuous experience, refresh (or renew) the access token before it expires.

There are two ways to refresh your access token:

Directly using the setAccessToken API


Automatically if you're using an Azure AD token for embed for your organization

Refresh the access token directly


setAccessToken can be used to update the access token without reloading the
embedded report. Use it when the token is about expire.

JavaScript

await report.setAccessToken(newAccessToken);

Manual token refresh example


To refresh your access token manually, implement getNewUserAccessToken(). This
function calls your application backend to generate a new embed token, or refreshes the
Azure AD token.

Below is an example of how to manually implement the getNewUserAccessToken()


function to refresh your access token before it expires.

JavaScript

const MINUTES_BEFORE_EXPIRATION = 10;

// Set the refresh interval time to 30 seconds


const INTERVAL_TIME = 30000;

// Get the token expiration from the access token


var tokenExpiration;
// Set an interval to check the access token expiration, and update if
needed
setInterval(() => checkTokenAndUpdate(reportId, groupId), INTERVAL_TIME);

function checkTokenAndUpdate(reportId, groupId) {


// Get the current time
const currentTime = Date.now();
const expiration = Date.parse(tokenExpiration);

// Time until token expiration in milliseconds


const timeUntilExpiration = expiration - currentTime;
const timeToUpdate = MINUTES_BEFORE_EXPIRATION * 60 * 1000;

// Update the token if it is about to expired


if (timeUntilExpiration <= timeToUpdate)
{
console.log("Updating report access token");
updateToken(reportId, groupId);
}
}

async function updateToken(reportId, groupId) {


// Generate a new embed token or refresh the user Azure AD access token
let newAccessToken = await getNewUserAccessToken(reportId, groupId);

// Update the new token expiration time


tokenExpiration = newAccessToken.expiration;

// Get a reference to the embedded report HTML element


let embedContainer = $('#embedContainer')[0];

// Get a reference to the embedded report.


let report = powerbi.get(embedContainer);

// Set the new access token


await report.setAccessToken(newAccessToken.token);
}

// Add a listener to make sure token is updated after tab was inactive
document.addEventListener("visibilitychange", function() {​

// Check the access token when the tab is visible
if (!document.hidden) {​

checkTokenAndUpdate(reportId, groupId)
}​

}​
);

Automatically refresh token


If you're using an Azure AD token for the embed for your organization scenario, you can
refresh the access token automatically by setting an event hook in your embedding
configuration parameters. The event hook will call a function that generates new tokens
and assign the generated token to the embedded artifact before the current token
expires. All you need to do is provide the token generating function, and the rest
happens automatically.

7 Note

Refreshing the access token automatically is supported from powerbi-client


JavaScript library version 2.20.1.

To refresh the access token automatically, set the accessTokenProvider function as a


parameter in IEmbedConfiguration when embedding. This function is implemented by
the customer and returns a fresh token when it's called. When the token is close to
expiring, the iframe will call the accesTokenProvider hook to acquire a new token from
the hosting app, and then set the new token.

Automatically refresh token example


Below is an example of how to automatically refresh your access token before it expires.

JavaScript

let getNewAccessToken = async function () {


// Code you need to add for generating new Azure AD token
return token;
};

let config = {
type: 'report',
tokenType: models.TokenType.Aad,
accessToken: “eyJ0 …”,
embedUrl: “https: …”,
eventHooks: {
accessTokenProvider: getNewAccessToken
}
};

// Get a reference to the embedded report HTML element


let embedContainer = $('#embedContainer')[0];

// Embed the report and display it within the div container.


report = powerbi.embed(embedContainer, config);

Considerations and limitations


Automatically refreshing the access token is only supported for the embed for your
organization (user owns data) scenario.
The accessTokenProvider event hook should never throw an exception. If it fails to
generate a new token, return a Null value.

Next steps
Understanding the different embedding solutions
Use bootstrap for better performance
Article • 05/21/2023

powerbi.bootstrap is a method introduced in Client SDK version 2.9.0 to help


developers embed Power BI entities faster and get better performance.

Embedding a report using powerbi.embed requires multiple parameters, such as


reportId , embedURL , and accessToken . These parameters aren't always immediately

available.

powerbi.bootstrap allows you to start embedding before all the required parameters are
available. The bootstrap API prepares and initializes the iframe.

After the required parameters are received, powerbi.embed(element, config) should be


called on the same HTML element.

Bootstrap API
The powerbi.bootstrap(element, config) method receives an element and config, the
same as powerbi.embed(...) .

TypeScript

/**
* Given an HTML element and entityType, creates a new component
instance, and bootstrap the iframe for embedding.
*
* @param {HTMLElement} an HTML Element where you need to embed. must be
the same div element you will use in powerbi.embed.
* @param {IBootstrapEmbedConfiguration} config: a bootstrap config.
*/
bootstrap(element: HTMLElement, config: IBootstrapEmbedConfiguration):
embed.Embed;

Bootstrap embed configuration


JavaScript

interface IBootstrapEmbedConfiguration {
type: string;
hostname?: string;
embedUrl?: string;
settings?: ISettings;
}
Config parameters:

type (required): The type of entity you want to embed, such as 'report',
'dashboard', 'tile', 'qna', or 'visual'.
hostname: If you don't have an embedURL yet, you can provide a hostname. The
hostname is the domain name of the embed URL. For example, if the embed URL is
'https://app.powerbi.com/reportEmbed' then the hostname is
'https://app.powerbi.com/'. If no hostname or embedUrl is provided, the default
hostname, https://app.powerbi.com/ , is used.
embedUrl: The same embed URL you will provide later to powerbi.embed. If no
hostname or embedUrl is provided, the default hostname,
https://app.powerbi.com/ , is used.

settings: To embed the report in a mobile layout or to provide a locale (language),


include these parameters in the initial settings.

Bootstrap samples
The following samples provide a reference for the bootstrap method when embedding
Power BI entities.

7 Note

Make sure that you call powerbi.embed after receiving the embed parameters.

To bootstrap for embedding a report:

JavaScript

powerbi.bootstrap(
reportContainerDivElement,
{
type: 'report',
}
);

To bootstrap for embedding a dashboard:

JavaScript

powerbi.bootstrap(
reportContainerDivElement,
{
type: 'dashboard',
embedUrl: "https://app.powerbi.com/dashboardEmbed?
dashboardId=06e3ba63-47ea-4579-b010-
fdb5484b325a&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6mLndpbmRvd3MubmV0In0="
}
);

To bootstrap for embedding a report with the hostname only:

JavaScript

powerbi.bootstrap(
reportContainerDivElement,
{
type: 'report',
hostname: "https://app.powerbi.com"
}
);

To bootstrap for embedding a report with mobile layout:

JavaScript

powerbi.bootstrap(
reportContainerDivElement,
{
type: 'report',
hostname: "https://app.powerbi.com",
settings: {
layoutType: models.LayoutType.MobilePortrait
}
}
);

Limitations
The following bootstrapped entities cannot be changed without calling
powerbi.reset(element) .

Component type (report, dashboard): For example, if you bootstrap a report,


you can only embed reports in the same HTML element.
Layout (desktop/mobile)
Locale (language)

The powerbi.bootstrap method isn't supported when embedding paginated


reports.
Next steps
Embed a report

Power BI embedded analytics performance best practices

Configure report settings


Work with a Power BI instance
Article • 01/03/2021

Learn how to get or reset a Power BI instance. For example, you might need to get a
report instance in order to set filters.

Get a reference to an existing Power BI


component
The powerbi.get method is used to retrieve an embedded instance when there is
already an embedded item on the given <div> .

Usually, you get a Power BI item instance (like a report) by using the powerbi.embed or
powerbi.bootstrap methods. But if you need to get an item instance after the report is
embedded, you might not be able to use them. In these cases, use the get method to
retrieve the instance.

JavaScript

let report = powerbi.get(element);

Reset an element
If you have embedded a report within an element, and want to reset the element back
to its initial state, call:

JavaScript

powerbi.reset(element);

This method removes the embed from the service and removes the iframe, which is
required to prevent the service from holding on to the reference that doesn't exist in the
DOM. You typically need to call the reset before the containing element is removed
from the DOM by the parent.

Next steps
Use bootstrap for better performance
General operations
General operations
Article • 10/28/2021

 Tip

Experiment with APIs in real time using your own report or our sample report in the
Developer sandbox section of the Power BI Embedded Analytics Playground .

With Power BI, some operations can be used with all types of embedded components,
while others only apply to specific types of embedded components. Full-screen and
reload operations apply to all components; print and refresh only apply to reports.

General operations for all components


The following operations apply to report, report visual, dashboard, dashboard tile,
paginated report, and Q&A components.

Launch an embedded component in full-screen mode


The following code examples are used to open an embedded component in full-screen
mode or to exit full-screen mode.

JavaScript

report.fullscreen();

JavaScript

report.exitFullscreen();

Reload a component
This method reloads the embed and resets the current filters and user interactions,
returning the embed back to its original state. For example, in a report this effectively
clears all of the new filters originally saved and makes the page the report was saved on
as active, resetting a report back to its original state.

JavaScript
await dashboard.reload();

General report operations


The following operations only apply to reports.

Print a report
This method prints the active page of the report by invoking window.print() on the
embed iframe component.

JavaScript

await report.print();

Refresh a report
This method refreshes the underlined data of an embedded component without
resetting the current filters or user interactions, and only works in Direct Query mode.

JavaScript

await report.refresh();

Next steps
How to handle events

Configure report settings


Troubleshoot and debug your
embedding code
Article • 12/05/2022

When developing an embedded analytics solution, you may run into errors. When this
happens, you need to figure out why the error occurred.

Use the error event to debug your embedded analytics solution and better understand
what caused your errors.

If there is an error you don't know how to handle, you can always search or ask a
question on Stack Overflow .

Find what error occurred


An error event fires when an error occurs. You can listen to the event by using
element.on(...) , and then set an event handler.

JavaScript

report.on('error', (errorObject) => {


...
});

For more information about handling events, see How to handle events.

The error event returns an IError object:

TypeScript

interface IError {
message: string;
detailedMessage?: string;
errorCode?: string;
level?: TraceType;
technicalDetails?: ITechnicalDetails;
}

For example, when the token expires you'll get the following error object:

JSON
{
"message": "TokenExpired",
"detailedMessage": "Access token has expired, resubmit with a new access
token",
"errorCode": "403"
}

For information about refreshing the access token, see Refresh the access token.

Troubleshooting
After you acquire the IError object, compare look it up in the Troubleshoot your
embedded application with the IError object table, and find the possible cause(s) of the
failure.

7 Note

There's a common errors table for Power BI users (also known as embed for your
organization), and for non-Power BI users (also known as embed for your
customers).

Debug in the browser's console


You can also simply debug your app in the browser's console. For instance, enter the
following code snippet after you have an embed instance:

JavaScript

// Add a listener to 'error' events


report.on('error', (errorObject) => {
const err = errorObject.detail;

// Print the error to console


console.log(`Error occurred: ${err.message}. Detailed message:
${err.detailedMessage}`);
console.log(err);
});

Catch the APIs errors


Most of the Client APIs are async functions that return a Promise .
If you're using the async / await pattern, you should use try / catch to catch potential
error. For example:

JavaScript

try {
...

// Set a new access token


await report.setAccessToken(newAccessToken.token);
} catch (e) {
...
}

If you're not using the async / await pattern, you can use the catch function to catch
potential error. For example:

JavaScript

// Set a new access token


report.setAccessToken(newAccessToken.token).catch(e => {
...
});

Next steps
Troubleshoot your embedded application
How to handle events
Refresh the access token
Stack Overflow
Use the Power BI correlation ID
Article • 01/24/2021

With the Power BI embedded correlation ID, you can correlate your application session
ID with the Power BI embedded session ID. Supplying the session ID to Power BI support
helps with retrieving additional debugging information.

You can call the getCorrelationId function from any embedded Power BI items,
including reports and dashboards.

The getCorrelationId API lets you get the current Power BI embedded correlation ID.

How to get the Power BI correlation ID


The getCorrelationId function shown in the following code sample returns the
embedded correlation ID.

TypeScript

getCorrelationId(): Promise<string>

Example
TypeScript

let correlationId = await report.getCorrelationId();

This example shows how to get the correlation ID when an error occurs.

TypeScript

dashboard.on("error", function (error) {


let correlationId = await dashboard.getcorrelationId();
console.log("Error occurred in embed session: " + correlationId + "
Error: " + error.detail.message);
});

Limitations
The getCorrelationId function only works after the report is loaded.
Next steps
How to handle events

Override default error messages


Accessibility for your embedded
solution
Article • 12/05/2022

When working with Power BI, consider making your embedded reports accessible to
different types of users who might interact with them. A few easy ways to make your
reports more accessible is to use the title and tabindex attributes, keyboard shortcuts,
and high contrast mode.

How to use title and tabindex attributes


After you call the powerbi.embed or the powerbi.bootstrap method, you get a
component of the type you embedded.

Title attribute
The title attribute lets you add text to the element it belongs to. If someone is using a
screen reader, it will read the additional information about the element for them. In
order to set the title attribute of the embed component, use setComponentTitle .

JavaScript

setComponentTitle(title: string): void

Title attribute example

JavaScript

let component = powerbi.embed(…);


component.setComponentTitle(“Analytics report”);

To learn more about the title attribute, see the MDN Web Docs title article.

Tabindex attribute
People may use their keyboard to navigate through your embedded reports. You can
use the tabindex attribute to add tabbed focus to elements in your report that would
otherwise be skipped over when the user presses Tab. In order to set the tabindex
attribute of the embed component, use setComponentTabIndex .

JavaScript

setComponentTabIndex(tabIndex?: number): void

You can remove the tabindex attribute, by using removeComponentTabIndex

JavaScript

removeComponentTabIndex(tabIndex?: number): void

Tabindex attribute example

JavaScript

let component = powerbi.embed(...);


component.setComponentTabIndex(0);

To learn more about the tabindex attribute, see the MDN Web Docs tabindex article.

Keyboard shortcuts in embedded Power BI


reports
For the people who use their keyboards to explore your embedded reports, a list of
keyboard shortcuts is an invaluable tool. If you'd like to show the keyboard shortcuts,
focus on the embedded report and press Shift + ?.

To learn more, see Keyboard shortcuts in Power BI Desktop

High contrast mode in embedded Power BI


reports
In order to help users with visual or physical impairments benefit from your embedded
reports, you can set them to use a high contrast theme.

You can set high contrast mode by adding a single parameter to the embed
configuration of your application.
JavaScript

let embedConfig = {

contrastMode: models.ContrastMode.HighContrast1
};

The contrast modes available are:

JavaScript

enum ContrastMode {
None = 0,
HighContrast1 = 1,
HighContrast2 = 2,
HighContrastBlack = 3,
HighContrastWhite = 4
}

The default is None = 0 .

) Important

If you provide both a high contrast mode and a theme, Power BI will only apply the
high contrast mode. It can't apply both at the same time.

Adjust zoom level for Power BI reports


In order to help users with visual or physical impairments benefit from your embedded
reports, you can adjust the report zoom level to be higher or lower than the default
level.

You can set the zoom level of the report by adding a single parameter to the embed
settings, or by using the setZoom API after the report has loaded.

Zoom level is calculated based on the report's actual size, see Change the display of a
report page to learn more about the report display options.

JavaScript

let embedConfig = {

settings: {
zoomLevel: 2 // 200% zoom
}
};

To get the current zoom level or to change it after the report has loaded you can use the
getZoom and setZoom APIs.

JavaScript

let currentZoom = await report.getZoom();


await report.setZoom(0.5); // 50% zoom

7 Note

The zoom level must be between 0.25 (25%) and four (400%).

Next steps
Keyboard shortcuts in Power BI Desktop
Design Power BI reports for accessibility
Configure report settings
Apply report themes
Use preload to reduce load time
Article • 12/05/2022

The powerbi.preload API is used to reduce the load time of the embedded content in
Power BI when your embedded content is on a different page. Preload uses a minimal
configuration (only type and embedURL ) to help download the scripts required to embed
Power BI content before your users navigate to that page. This provides a faster
experience when displaying embedded reports and dashboards. Preload should only be
used if the Power BI content is on a different page of the web application.

7 Note

As a best practice for performance, we recommend using the bootstrap method


instead of preload.

How to use preload


powerbi.preload() is used to download the necessary scripts before embedding your
content. The browser stores these scripts in its cache, making the initial call to
powerbi.embed() faster. To use preload, you must provide the type of embedded entity
and a base URL for Power BI (embed URLs without any specific URL parameters such as
reportId or groupId ).

JavaScript

// Building the config object


let config = {
type: 'report',
embedUrl: 'https://app.powerbi.com/reportEmbed',
};

let element = powerbi.preload(config);

The preload event will fire when the preload is complete.

JavaScript

element.on('preloaded', function () {
...
});
Next steps
How to handle events

Use bootstrap for better performance


Configure report settings
Article • 01/04/2023

By using the Power BI Client APIs, you can embed Power BI analytics in your application.
When you use this client-side library to embed a Power BI report, you provide the API
with information about that report.

You can use a configuration object to store information about your Power BI report.
When you embed the report, you then pass that object to the API.

Besides giving the API access to the report, you can also use the configuration object to
customize your report's appearance and behavior. For instance, you can adjust the filter
visibility, navigation access, and location settings in the configuration object.

The following sections explain how to embed and configure Power BI content.

Provide configuration information


The IReportLoadConfiguration interface displays properties that a configuration object
can supply to the Power BI Client APIs about a report:

TypeScript

interface IReportLoadConfiguration {
embedUrl: string;
accessToken: string;
id: string;
groupId?: string;
settings?: ISettings;
bookmark?: IApplyBookmarkRequest;
pageName?: string;
filters?: ReportLevelFilters[];
slicers?: ISlicer[];
theme?: IReportTheme;
contrastMode?: ContrastMode;
datasetBinding?: IDatasetBinding;
permissions?: Permissions;
viewMode?: ViewMode;
tokenType?: TokenType;
}

See Embed a report for an explanation of this interface's required parameters and for
code examples showing how to embed a report.
Customize settings
The following sections describe how you can use the settings property to adjust the
appearance and behavior of your embedded Power BI report. To update the report
settings when the report is already loaded, use the report.updateSettings method. For
more information, see Update report settings at runtime.

Panes
Control the appearance of all the panes in your Power BI report with a single panes
property, as shown in the following code:

JavaScript

let embedConfig = {
...
settings: {
panes: {
bookmarks: {
visible: true
},
fields: {
expanded: false
},
filters: {
expanded: false,
visible: true
},
pageNavigation: {
visible: false
},
selection: {
visible: true
},
syncSlicers: {
visible: true
},
visualizations: {
expanded: false
}
}
}
};

From the following table, you can see which values each panes property supports:

Property Visible Expanded


Property Visible Expanded

bookmarks ✔ ❌

fields ✔ ✔

filters ✔ ✔

pageNavigation ✔ ❌

selection ✔ ❌

syncSlicers ✔ ❌

visualizations ✔ ✔

Filter pane

By default, the filter pane is visible. If you want to hide this pane, use the
filterPaneEnabled property, as shown in the following code:

JavaScript

let embedConfig = {
...
settings: {
filterPaneEnabled: false
}
};

7 Note

The panes property replaces the filterPaneEnabled property. To maintain


backward compatibility, the filterPaneEnabled property still exists. However, you
should avoid using these two properties together.

Page navigation pane


By default, the page navigation arrows are visible on embedded reports. To hide these
arrows, use the navContentPaneEnabled property, as shown in the following code:

JavaScript

let embedConfig = {
...
settings: {
navContentPaneEnabled: false
}
};

7 Note

The panes property replaces the navContentPaneEnabled property. To maintain


backward compatibility, the navContentPaneEnabled property still exists. However,
you should avoid using these two properties together.

The page navigation pane appears at the bottom of the report, to use the new vertical
pages pane you can set the position property:

JavaScript

let embedConfig = {
...
settings: {
panes:{
pageNavigation: {
visible: true,
position: PagesPosition.Left
}
}
}
};

7 Note

You can't change the position of the page navigation pane using updateSettings .

Bars
Set the visibility of the action bar and status bar by using the bars property.

Action bar
The following code makes the action bar visible:

JavaScript
let embedConfig = {
...
settings: {
bars: {
actionBar: {
visible: true
}
}
}
};

Alternatively, in view mode, it is also possible to use the actionBarEnabled URL


parameter:

TypeScript

let embedConfig = {
...
embedUrl: embedUrl + "&actionBarEnabled=true"
};

7 Note

In view mode the action bar is only supported for the embed for your organization
scenario.

For the action bar in view mode it’s recommended to enable


UserState.ReadWrite.All permission for your Azure AD application. This permission

is required to allow end users to add the report to their favorites, and for enabling
personal bookmarks and persistent filters.

Status bar

The status bar holds the canvas zoom controller, which provides the ability to zoom on
the canvas.

The following code makes the status bar visible:

JavaScript

let embedConfig = {
...
settings: {
bars: {
statusBar: {
visible: true
}
}
}
};

Locale settings
Use the localeSettings property to specify the language and the formatting of the
embedded report:

The language property in localeSettings consists of two parts of two letters each,
separated by a hyphen:

language defines the language that Power BI uses for localization. Examples of
languages include en (English), es (Spanish), and tr (Turkish).
locale defines the text formatting that Power BI uses for dates, currency, and other
related content. Examples of locales include US (English), ES (Spain), and TR
(Turkey).

See Supported languages for a list of available languages and regions.

The following code assigns a specific values to these localeSettings :

JavaScript

let embedConfig = {
...
settings: {
localeSettings: {
language: "en-us"
}
}
};

7 Note

Locale settings cannot be changed after the report is loaded. To change the report
locale settings, reset the iframe by calling powerbi.reset(element) , and then embed
the report again.

Transparent background
By default, the background of the embedded content is white with gray margins. If you
prefer, you can give the embedded content a transparent background. Then you can
apply the style you want to the HTML div element that contains the embedded content.
The div element's styling then becomes visible.

Use this code to make the background of the embedded content transparent:

JavaScript

let embedConfig = {
...
settings: {
background: models.BackgroundType.Transparent
}
};

Hyperlink click behavior


You can control the behavior of a hyperlink in a table, or matrix out-of-the-box visuals.
By default, the hyperlink will open a new window.

The behavior modes that are available are listed below:

TypeScript

enum HyperlinkClickBehavior {
Navigate,
NavigateAndRaiseEvent,
RaiseEvent
}

Navigate - The URL will be loaded into a new browsing context.

NavigateAndRaiseEvent - The URL will be loaded into a new browsing context, and

will raise a dataHyperlinkClicked event.


RaiseEvent - Prevents the default behavior of URL click, and raise

dataHyperlinkClicked event.

Use this code to change the behavior of links to raise an event:

JavaScript

let embedConfig = {
...
settings: {
hyperlinkClickBehavior: HyperlinkClickBehavior.RaiseEvent
}
};

A dataHyperlinkClicked event fires when a hyperlink is clicked on an out-of-the-box


table or matrix visuals and the behavior is either NavigateAndRaiseEvent or RaiseEvent .

JavaScript

report.on('dataHyperlinkClicked', () => {
...
});

For more information about handling events, see How to handle events.

Visual rendered events


You can listen to an event for each rendered visual. By default, the visual rendered
events are disabled.

Use this code to make the visualRendered events triggered:

JavaScript

let embedConfig = {
...
settings: {
visualRenderedEvents: true
}
};

A visualRendered event fires when a visual is rendered and the visualRenderedEvents is


enabled on the report settings.

JavaScript

report.on('visualRendered', () => {
...
});

For more information about handling events, see How to handle events.

7 Note
Because visuals might render due to user interactions, it's recommended to turn on
this event only when needed.

Error messages
If you'd like to display customized error messages in embedded reports, use the
hideErrors property to hide the default Power BI embedded error messages. Your code
can then handle error events in a way that fits your app design. See Override default
error messages for more information on overriding default errors.

Use this code to hide default error messages:

JavaScript

let embedConfig = {
...
settings: {
hideErrors: true
}
};

Customize options
The following sections describe how you can use additional properties to further
customize the appearance and behavior of your embedded Power BI report.

Default page
You can control which page of your embedded report appears initially. By default, the
initial page is the page that you modified most recently, which was the active page the
last time you saved the report. You can override this behavior by using the pageName
property and supplying it with the name of the page you'd like to display. However, if
no page with that name exists in Power BI, the request to open it fails.

The following code shows how to configure your app to display a specific page:

JavaScript

let embedConfig = {
...
pageName: 'ReportSection3'
};
On load filters
You can control the filters that your app applies to an embedded report. By default, the
report initially uses the filters that you saved to the report. However, you have two
options if you want to adjust the filters:

Configure additional filters to use together with the saved filters. The following
code shows how to use the filters property to append additional filters:

JavaScript

let embedConfig = {
...
filters: [...]
};

Replace the saved filters with a new set. The setFilters method provides a way to
dynamically change a report's filters. If you use this method during phased
embedding, you can override the filters that the report initially applies. For more
information about constructing filters and using the setFilters method, see
Control report filters.

On load slicers
You can control the state of the slicers that your app applies to an embedded report. By
default, the API uses the slicers that you saved to the report. However, you can use the
slicers property to modify the state of the existing slicers, as the following code
demonstrates:

JavaScript

embedConfig = {
...
slicers: slicerArray,
};

See Control report slicers for more information about modifying the state of a slicer.

On load bookmark
By using the bookmark property, you can apply a bookmark to an embedded report. See
Bookmarks for more information about using bookmarks to capture the currently
configured view of report pages.
You can specify the bookmark to use by providing either the bookmark name or the
state. If you provide the bookmark name, your Power BI report needs to contain a saved
bookmark with that name.

The bookmark property is of type IApplyBookmarkRequest. The following code shows this
type's definition:

TypeScript

type IApplyBookmarkRequest = IApplyBookmarkStateRequest |


IApplyBookmarkByNameRequest;

interface IApplyBookmarkStateRequest {
state: string;
}

interface IApplyBookmarkByNameRequest {
name: string;
}

This code shows how to specify a bookmark by name:

JavaScript

let embedConfig = {
...
bookmark: {
name: "Bookmark4f76333c3ea205286501"
}
};

This code shows how to specify a bookmark by state:

JavaScript

let embedConfig = {
...
bookmark: {
state: bookmarkState
}
};

Themes and high-contrast mode


You can control the theme and contrast level that your embedded content uses. By
default, any content that you embed appears with the default theme and with zero
contrast. You can override this behavior by configuring a specific theme or contrast level.
For more information about themes, see Apply report themes.

The contrast modes that are available are listed below:

TypeScript

enum ContrastMode {
None = 0,
HighContrast1 = 1,
HighContrast2 = 2,
HighContrastBlack = 3,
HighContrastWhite = 4
}

Use code similar to the following lines to configure a specific theme:

JavaScript

let embedConfig = {
...
theme: {themeJson: ...}
};

The following code shows how to override the default contrast level, None :

JavaScript

let embedConfig = {
...
contrastMode: models.contrastMode.HighContrast1
};

7 Note

The API cannot apply a theme and a contrast level at the same time. If you
configure both properties, the API uses the contrast level that you specified but
ignores the theme setting.

Zoom level
To learn more about adjusting the report zoom level check the accessibility document.
Open in edit mode
By default, the report that you embed appears in view mode. However, you can override
this behavior to open the report in edit mode. You can also switch between modes.

Configure edit mode


To open an embedded report in edit mode, use the viewMode property together with the
permissions property.

You can assign the viewMode property the following values:

View - Opens the report in view mode.

Edit - Opens the report in edit mode.

You can assign the permissions property these values:

Read - Users can view the report.

ReadWrite - Users can view, edit, and save the report.


Copy - Users can save a copy of the report by using Save As.

Create - Users can create a new report.


All - Users can create, view, edit, save, and save a copy of the report.

When you configure content to open in edit mode, assign the permissions property a
value that is appropriate for editing, as the following code demonstrates:

JavaScript

let embedConfig = {
...
permissions: models.Permissions.All
viewMode: models.ViewMode.Edit
};

7 Note

The permissions value that you configure only works if the embed token that you
acquired has sufficient privileges. For more information about embed tokens, see
Create the embed token.

Switch between edit and view modes


Besides specifying a mode for embedded content to start in, you can also switch
between edit and view modes dynamically.

If the content is in edit mode, and you'd like to switch to view mode, use this JavaScript
code:

JavaScript

// Embed the content.


let embeddedContent = powerbi.embed(container, embedConfiguration);

...

// Switch to view mode.


embeddedContent.switchMode("view");

If the content is in view mode, and you'd like to switch to edit mode, use this JavaScript
code:

JavaScript

// Embed the content.


let embeddedContent = powerbi.embed(container, embedConfiguration);

...

// Switch to edit mode.


embeddedContent.switchMode("edit");

Considerations and limitations


Consider the following points when you configure embedded content:

The page navigation position can't be changed when the action bar is visible. Learn
more about the action bar.

When you use the bars property in the setting property, as described in Bars, the
API only applies your configuration if the embedded content is in edit mode. If
your content is in view mode, the API ignores the bars setting.

When you use the viewMode property to display content in edit mode, you need to
take two additional steps:
Configure a permission level with the permissions property. That permission
level needs to give the user appropriate access for modifying content. For
instance, if you assign a permissions value of Read, the user will not be able to
edit content.
Ensure that the embed token that you generate has privileges that support
editing. For instance, if you acquire a token with an accessLevel value of view,
the API will fail to display content in edit mode.

The panes property replaces the following settings properties:


filterPaneEnabled
navContentPaneEnabled

If you use the panes property to configure filter or page navigation visibility, do
not use the filterPaneEnabled or navContentPaneEnabled property in your app.

The API can't apply a theme and a contrast level to embedded content at the same
time. If you configure both options by using the theme and contrastMode
properties, the API uses your contrastMode value with the embedded content.
However, the API ignores the theme setting.

If you want to apply a bookmark to an embedded report, you can use the
bookmark property. If you supply a bookmark name with that property, the API can

only use the bookmark if one exists with that name. Likewise, if you use the
pageName property to specify an opening page, the API can only display that page

if one exists with the given name. Before configuring a name, consider using an
accessor method, such as the Report getPages method, to check whether a
component exists with that name.

Next steps
Enhance your users' experience with bookmarks
Apply report themes in Power BI
Control report filters
Control report slicers
Update report settings at runtime
Article • 05/12/2021

You can use the report.updateSettings method to update the report settings when the
report is already loaded. The settings property is used to adjust the appearance and
behavior of your embedded Power BI report.

How to update the report settings


The Power BI Client Report class defines the updateSettings method as:

TypeScript

report.updateSettings(settings: ISettings):
Promise<IHttpPostMessageResponse<void>>

See Configure report settings for the settings object details.

Example
To update the report settings and show the bookmarks pane:

JavaScript

const newSettings = {
panes: {
bookmarks: {
visible: true
}
}
};

await report.updateSettings(newSettings);

Limitations
The following settings can't be updated after the report is loaded:

Locale settings
Mobile layout, if the report was initially loaded or bootstrapped without mobile
layout
Page navigation pane position

Next steps
Configure report settings

Enhance your users' experience with bookmarks


Create, edit, and save an embedded
report
Article • 10/04/2021

Power BI embedded analytics allows you to create, edit, and save embedded reports. A
report can be created based on an existing dataset, or you can edit an existing report.
You can also save the report after it was created or edited.

How to create a report


Learn how to create a new, blank report from an existing data set.

Required access token permissions for creating a report

Embed for your customers

Generate an embed token with access to the dataset. If you use the master user
authentication method, make sure your application has the following scopes:
Dataset.Read.All , Content.Create , and Workspaces.ReadWrite.all . See Embed

Token - Generate Token for more information.

Required client-side permissions for creating a report


The following client-side permissions are required for creating a report:

Create - Users can create a new report.

All - Users can create, view, edit, save, and save a copy of the report.

Create a new report


Create a new, blank report from an existing dataset. You will need a dataset ID and the
embed URL. For example, you can use the getDatasetsInGroup REST API and retrieve the
CreateReportEmbedURL . See Datasets - Get Datasets In Group for more information.

7 Note

You must have build or write permissions on the dataset to create a new report.
JavaScript

let embedCreateConfiguration = {
tokenType: tokenType,
accessToken: accessToken,
embedUrl: embedURL,
datasetId: datasetId,
settings: settings,
theme: theme, // optional
};

// Grab the reference to the div HTML element that will host the report
let embedContainer = $('#embedContainer')[0];

// Create report
let report = powerbi.createReport(embedContainer, embedCreateConfiguration);

You also have the option to create a report with a theme applied to it. New visuals
added to the report will respect the theme style. See Apply report themes for more
information.

How to edit a report


Learn how to edit an existing report and switch between View and Edit modes.

Required access token permissions for editing

Embed for your customers

Generate an embed token with access to the report. If you use the master user
authentication method, make sure your application has the following scopes:
Dataset.ReadWrite.All and Report.ReadWrite.All . You must also set the

allowEdit: true flag for each report that the end-user needs to edit. See Embed

Token - Generate Token for more information.

Required client-side permissions for editing


The following client-side permissions are required for editing a report:

Copy - Users can save a copy of the report by using Save As.

ReadWrite - Users can view, edit, and save the report.


All - Users can create, view, edit, save, and save a copy of the report.

Edit the report


Load your existing report in Edit mode. The report must be embedded in the same way
the application embeds a regular report, and the view mode must be in Edit. Make sure
that you set the viewMode parameter to models.ViewMode.Edit , and that you have the
right client permissions.

JavaScript

let config = {
type: 'report',
tokenType: models.TokenType.Aad or models.TokenType.Embed,
accessToken: YourAccessToken,
embedUrl: YourEmbedUrl,
id: YourEmbedReportId,
permissions: models.Permissions.All,
viewMode: models.ViewMode.Edit,
};

// Grab the reference to the div HTML element that will host the report
let embedContainer = $('#embedContainer')[0];

// Embed report
let report = powerbi.embed(embedContainer, config);

Your user can now edit the report based on the permissions that have been enabled.

You can also switch between the Edit and View modes after the report is loaded.

JavaScript

report.switchMode("view");

To switch to edit mode:

JavaScript

report.switchMode("edit");

How to save a report


Learn how to save a report, including additional options like saving a copy of a report
and saving a report to another workspace.
Required access token permissions for saving

Embed for your customers

Generate an embed token with access to the report and dataset. If you want to save
the report to another workspace, the token needs to have access to the target
workspace. If you use the master user authentication method, make sure your
application has the following scopes: Report.ReadWrite.All , and
Workspaces.ReadWrite.all . You must also set the allowEdit: true flag for each
report that the customer needs to edit. See Embed Token - Generate Token for
more information.

Required client-side permissions for saving


The following client-side permissions are required for saving a report:

ReadWrite - Users can view, edit, and save the report.

Create - Users can create a new report.

Copy - Users can save a copy of the report by using Save As.

All - Users can create, view, edit, save, and save a copy of the report.

Save a report
When creating a report, the report is not saved until you call the save operation from
the file menu or JavaScript.

JavaScript

report.save();

Save a copy of a report


Save an additional copy with a different name. The copy of the report will be saved to
the same workspace as the report's dataset.

JavaScript

let saveAsParameters = {
name: "newReport"
};

report.saveAs(saveAsParameters);

You can also save your report to another workspace. Make sure you have the right
permissions for the target workspace.

JavaScript

let saveAsParameters = {
name: "newReport"
targetWorkspaceId: "13bbf317-fe2b-4b15-a081-94b0921c28e5"
};

report.saveAs(saveAsParameters);

Verify that the report is saved

Call report.isSaved to make sure the report is saved. This method can help prevent
losing unsaved changes.

JavaScript

let isReportSaved = await report.isSaved();

Create a custom saveAs experience


You can create a custom saveAs dialog by adding the useCustomSaveAsDialog: true
report setting to the configuration object. This setting hides the default UI dialog.

The saveAsTriggered event is raised when a user clicks on Save As in the UI. Use this
information to show your custom dialog.

JavaScript

report.on("saveAsTriggered", function (event) {


console.log(event);
});

To perform a save as operation, you can call report.saveAs from your custom dialog.
See Save a copy of a report for more information.

JavaScript
let saveAsParameters = {
name: "newReport"
targetWorkspaceId: "13bbf317-fe2b-4b15-a081-94b0921c28e5"
};

report.saveAs(saveAsParameters);

Listen to the save and saveAs events


The saved event is raised when a save is triggered by a save or saveAs action in the UI
or by using the APIs. See How to handle events for more information.

JavaScript

report.on("saved", function (event) {


console.log(event);
});

Next steps
Bind datasets dynamically to a report

Use phased embedding

Report authoring overview


Bind datasets dynamically to a
paginated report visual
Article • 09/18/2023

Power BI reports and paginated reports are built based on an existing dataset. That
dataset defines the data schema that the report visuals use. By using dynamic binding,
you can select a dataset on the fly when you embed a paginated report visual.

The datasets that you select need to use the same data schema. If you have multiple
datasets with the same data schema, your report can connect, or bind, dynamically to
each of those datasets. You can then display different insights, depending on your
needs.

Dynamic binding offers other advantages, too. You don't need to create a copy of the
same report with a different dataset for each user. One report can serve multiple users.
This feature then reduces the number of maintained items and improves the application
life cycle handling. As a result, dynamic binding simplifies onboarding for new
customers.

How to connect a report to multiple datasets


dynamically
Your reports and datasets can be in separate workspaces, however both workspaces
must have a capacity.

When you embed for customers, the embed token must include permissions for both
the report and the dynamically bound dataset. Use the new API to generate an embed
token that supports Power BI items, such as reports and dashboards.

When you embed for your organization, the user's Azure Active Directory (AD) token
that you use must have appropriate permissions for all Power BI items.

Example
To implement an embedded solution using dynamic binding add the datasetBinding
property to the embed configuration object, as shown in the following example.

TypeScript
let config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: "reportId",
permissions: permissions,
datasetBinding: {
datasetId: "notOriginalDatasetId",
paginatedReportBindings: [{
sourceDatasetId: "originalDatasetId",
targetDatasetId: "notOriginalDatasetId"
}]
}
};

// Get a reference to the embedded report HTML element.


let embedContainer = $('#embedContainer')[0];

// Embed the report and display it within the div container.


let report = powerbi.embed(embedContainer, config);

Considerations and limitations


The dynamically selected dataset must use the same data schema in the report.
When embedding for customers, generate an embed token using the new API.
When embedding for your organization, ensure the user has permissions for both
the report and dataset.
The datasetBinding property can't be empty. It should contain, datasetId ,
paginatedReportBindings , or both.

The values for datasetId and targetDatasetId don't have to be the same. Binding
works independently for .pbix and paginated reports.
The datasetBinding property can contain multiple objects.

Next steps
Embed a report
Considerations when generating an embed token
Embedding a Power BI report with
mobile layout
Article • 03/27/2023

Mobile users can view any Power BI report page in landscape orientation. However,
report authors can create an additional view that is optimized for mobile devices and
displays in portrait orientation. This design option, which is available in both Power BI
Desktop and in the Power BI service, enables authors to select and rearrange just those
visuals that make sense for mobile users on the go.

If your report has mobile layout that was created in Power BI Desktop or Power BI
service, you can embed the report with this layout in your web application.

How to embed a report using mobile layout


First you need to create a mobile layout for your report, check out Optimize Power BI
reports for the mobile app for creating this layout.

To embed a Power BI report in the report's mobile layout, you should set the layoutType
to models.LayoutType.MobilePortrait in the settings object:

JavaScript

let embedConfig = {
...
settings: {
layoutType: models.LayoutType.MobilePortrait
}
};

For more information about report settings, see Configure report settings.

There are two layout types dedicated to mobile devices:

MobilePortrait - Optimized for portrait view. This is the mobile layout you created

for your report.

MobileLandscape - Optimized for landscape view. This is the regular layout of your

report.

7 Note
The report layout will be determined by the layoutType property regardless of the
device actual orientation.

For example, the following code shows how to embed the report with a mobile layout.

JavaScript

// Get models. models contains enums that can be used.


var models = window['powerbi-client'].models;

var embedConfiguration = {
type: 'report',
id: reportId,
embedUrl: embedUrl,
tokenType: tokenType,
accessToken: accessToken,
settings: {
layoutType: models.LayoutType.MobilePortrait
}
};

To update the report layout when the report is already loaded, use the
report.updateSettings method. For more information, see Update report settings at

runtime.

JavaScript

const newSettings = {
layoutType: models.LayoutType.MobileLandscape
};

report.updateSettings(newSettings);

Check if a report page has mobile layout


The Power BI Client Page class, defines the hasLayout method as:

TypeScript

hasLayout(layoutType: any): Promise<boolean>

The hasLayout method will return a boolean if the page has the specified layout type.

JavaScript
let pages = await report.getPages();
let mobileLayout = pages[0].hasLayout(models.LayoutType.MobilePortrait);

You can use phased embedding with hasLayout in order to check if the page has mobile
layout before rendering the report.

Swipe events
When embedding a report in mobile layout you can listen to the swipe events and run a
custom code on your web application. There are two swipe events, swipeStart and
swipeEnd both return the following format:

JavaScript

interface ISwipeEvent {
currentPosition: IPosition;
startPosition: IPosition;
}

interface IPosition {
x: number;
y: number;
}

For example, you can use the swipeEnd event to detect a left swipe:

JavaScript

report.on("swipeEnd", function(event) {
const swipeEndEvent = event.detail.swipeEvent;
if (swipeEndEvent.currentPosition.x < swipeEndEvent.startPosition.x) {
console.log("Swipe left detected");
}
});

For more information about handling events, see How to handle events.

Optimize your app with custom layouts


You can also use the custom layout feature to create a customized layouts that are
optimized for different mobiles or tablet screens.
Limitations
After the report initial load, changing to report mobile layout is supported only if
mobile layout (portrait/landscape) has been set into the initial embedding
configuration object. Otherwise, you must first call powerbi.reset(HTMLElement) to
remove the iframe. Then, you have to call powerbi.embed(...) using the same
container with the mobile layout setting defined on the embedded configuration
object.

If you try to embed a report page with the MobilePortrait layout and the page
does not have a mobile layout, the page will be loaded with the MobileLandscape
layout.

To allow your users to navigate between pages while using mobile layouts, you can
use report.setPage and implement your own navigation. For more information,
see Page navigation.

The above configurations refer to embedding a Power BI report in mobile view.


Dashboard embed can be configured to mobile layout with the pageView
configuration: pageView: 'oneColumn'

Next steps
Optimize Power BI reports for the mobile app
Personalize a report layout
How to handle events
Use phased embedding
Article • 01/24/2021

The Power BI embedded analytics powerbi.load and report.render APIs can improve
end-user experience by giving developers more flexibility to phase report embedding.

Normally, you load an embedded report by using powerbi.embed :

JavaScript

let report = powerbi.embed(embedContainer, embedConfig);

The embedded report loads and renders in the user interface. The end user then sees
any interactions with the rendered report. For example, if you apply a slicer state, the
end user sees the slicer take effect after the report renders.

To hide these interactions from end users, the powerbi.load and report.render APIs
break down the embedding process into phases. The powerbi.load function loads the
report so you can interact with items before end users see the results. The
report.render function then displays the report.

Load
The powerbi.load function loads the report but doesn't render it, so interactions can
happen before the end user sees the results. For example, you can use powerbi.load
with report.getPages , and then specify which page to show the end user. Or, you can
use page.getVisuals , and then decide which visuals to show or hide.

Like powerbi.embed , the powerbi.load function requires an HTML element and an


IEmbedConfiguration object.

When the load finishes, a loaded event fires.

JavaScript

let config = {
...
};

// Get a reference to the embedded report HTML element.


let embedContainer = $('#embedContainer')[0];

// Load the report in the container.


let report = powerbi.load(embedContainer, config);

report.on('loaded', function() {
...
});

Render
If you use powerbi.load , you must then call the report.render function on the loaded
event handler function, after running your code. Use report.render to continue the
report rendering and display the embedded report.

A rendered event fires when the report finishes rendering.

JavaScript

report.on('loaded', function() {
report.render();
});

report.on('rendered', () => {
...
});

For more information about handling events, see How to handle events.

Example
The following code example loads a report, sets filters, and then renders the filtered
report.

JavaScript

// Build the config object.


let config = {
type: 'report',
tokenType: TokenType.Embed,
accessToken: ...,
embedUrl: ...,
id: ...,
...
};

// Get a reference to the embedded report HTML element.


let embedContainer = $('#embedContainer')[0];

// Load the report in the container.


let report = powerbi.load(embedContainer, config);

...
report.on('loaded', async () => {
await report.setFilters(filters);
report.render();
});

Limitations
Phased embedding can slow down report rendering, so be sure to use it correctly and
only when you need it.

You can call the following APIs after you load the report and before you call
report.render :

Method Action

BookmarksManager.getBookmarks, Get and apply bookmarks. Capturing bookmarks


BookmarksManager.apply isn't supported.

Report.updateSettings Update report settings.

Report.applyTheme Apply the report theme.

Report.getFilters, Report.setFilters, Get, set, and remove report filters.


Report.removeFilters

Report.getPages Get the report pages.

Page.setActive Set the active report page.

Page.getFilters, Page.setFilters, Get, set, and remove page filters.


Page.removeFilters

Page.getVisuals Get page visuals.

Visual.getFilters, Visual.setFilters, Get, set, and remove visual filters.


Visual.removeFilters

Visual.getSlicerState, Visual.setSlicerState Get and set visual slicer state.

Next steps
Enhance your users' experience with bookmarks
Apply report themes in Power BI

Control report filters

Control report slicers

Get pages and visuals


Get pages and visuals
Article • 01/31/2023

After loading a report, you can make a list of pages or visuals that can be directly used
to make changes to those instances. You can also create a list to see what visuals are
used on a specific page.

How to get a list of pages


The Page class includes properties and methods to a change report page. For example,
you can use the defaultSize property to define the page size as saved in the report, or
the getFilters() method to get all page level filters in the report. For more information,
see Page class.

Use getPages to retrieve a list of the pages in the report. The order of pages returned is
in the same order as in the report.

JavaScript

let pages = await report.getPages();

How to get a list of visuals


The VisualDescriptor class includes properties and methods to change a visual in a
specific page. For example, you can use the layout property to define the visual's
position, size, and visibility. For more information, see VisualDescriptor class.

Use the getVisuals async method on the page instance.

JavaScript

let pages = await page.getVisuals();

Code examples

Retrieve the page collection


The following code example shows how to retrieve a page collection in report, with an
example output showing the page name and display name of each object.

JavaScript

let pages = await report.getPages();


let log = "Report pages:";
pages.forEach(function (page) {
log += "\n" + page.name + " - " + page.displayName;
});

console.log(log);

Output

Report pages:
ReportSectioneb8c865100f8508cc533 - Tiles
ReportSection600dd9293d71ade01765 - Market Share
ReportSectiona271643cba2213c935be - YTD Category
ReportSection1c45b5dc6513ae89b4e3 - Sentiment
ReportSection2ff5a27ac612830bbd93 - Tooltip
ReportSection6da8317ad6cbcae5b3bb - Empty Page

Get a list of visuals


This code example shows how to get a list of visuals for the first page.

JavaScript

let pages = await report.getPages();

// Retrieve the first page.


let firstPage = pages[0];
let visuals = await firstPage.getVisuals();
console.log(visuals);

Get the page collection and the visuals of the first page
This example retrieves the page collection and the visuals (with several properties) for
the active page.

JavaScript

let activePage = await report.getActivePage();

let visuals = await activePage.getVisuals();


console.log(
visuals.map(function (visual) {
return {
name: visual.name,
type: visual.type,
title: visual.title,
layout: visual.layout
};
}));

Limitations
The report must be loaded in order to use the getPages or getVisuals functions.

Next steps
Page navigation

Configure report settings


Page navigation
Article • 12/05/2022

When you load a Power BI report in an application, you can use the Power BI Client APIs
to navigate between its report pages. For example, you can set the default page or
change a page dynamically. Doing so allows you to create your own custom page
navigation to match your brand. You can also automatically change pages based on a
set criteria to show a user certain visuals and information.

Each page in a report is represented by a Page object. To return all the of pages in a
report, call the report's getPages method, which returns the pages as a collection of
Page objects. The collection of pages is returned in the same order as in the report.

The Report class defines the getPages method as follows:

TypeScript

getPages(): Promise<Page[]>

For example:

JavaScript

let pages = await report.getPages();

How to navigate between report pages


Use the Page and Report objects in your application to navigate between report pages,
as shown by the code examples in the following sections.

Set the active page


Use the setPage method of a Report object to make an existing page the active page of
a report.

The Report class defines the setPage method as follows:

TypeScript

setPage(pageName: string): Promise<void>


For example:

JavaScript

await report.setPage("page2");

Make the current page active


Use the setActive method of a Page object to ensure the page is always valid for a
given report. To get Page objects, call getPages on a Report object.

The Page class defines the setActive method as follows:

TypeScript

setActive(): Promise<void>

For example:

JavaScript

await page.setActive();

Add an event handler


When you monitor a user's page navigation in a report, you need to be aware of when a
user changes pages. To do so, add an event handler for the pageChanged event. For
example:

JavaScript

report.on('pageChanged', event => {


const page = event.detail.newPage;
console.log(page.name);
});

For more information about events, see How to handle events.

Next steps
How to handle events
Get pages and visuals
Control report filters
Article • 01/22/2023

When you embed a Power BI report, you can apply filters automatically during the
loading phase, or you can change filters dynamically after the report is loaded. For
example, you can create your own custom filter pane and automatically apply those
filters to reports to show the user specific insights. You can also create a button that
allows the user to apply filters to the embedded report.

The following filter types are supported:

Basic - IBasicFilter
Advanced - IAdvancedFilter
Top N - ITopNFilter
Relative date - IRelativeDateFilter
Relative time - IRelativeTimeFilter

The filter object attributes


All filter types inherit the IFilter interface. The attributes listed below are relevant for
all the filter types.

TypeScript

interface IFilter {
$schema: string;
target: IFilterGeneralTarget;
filterType: FilterType;
displaySettings?: IFilterDisplaySettings;
}

Schema
The $schema attribute defines the type of filter. There are five schemas available, one for
each filter type:

Basic - http://powerbi.com/product/schema#basic
Advanced - http://powerbi.com/product/schema#advanced
Relative date - http://powerbi.com/product/schema#relativeDate
Relative time - http://powerbi.com/product/schema#relativeTime
Top N - http://powerbi.com/product/schema#topN
Display settings
The displaySettings attribute, defines the way the filter is displayed in the filters pane.

TypeScript

interface IFilterDisplaySettings {
isLockedInViewMode?: boolean;
isHiddenInViewMode?: boolean;
displayName?: string;
}

isLockedInViewMode - A locked filter is applied and displayed in the filter pane. The

filter value cannot be changed in view mode. Set it to true to lock the filter.

isHiddenInViewMode - A hidden filter is applied to the report but not displayed in


the filter pane in view mode. Set it to true to hide the filter.

displayName - A filter can be displayed in the filter pane with a personalized name.
Use this attribute to set a personalized name for your filter. When the value is
undefined or null, the default name of the filter will be displayed (typically the
name of the filtered data field).

Filter type
The filterType attribute defines the filter's type. Use the following enum, defined in the
models library:

TypeScript

enum FilterType {
Advanced = 0,
Basic = 1,
Unknown = 2,
IncludeExclude = 3,
RelativeDate = 4,
TopN = 5,
Tuple = 6,
RelativeTime = 7,
}

Target
The target attribute defines the filter's target. For more information, see Use targets to
select which data field to act on.

Additional attributes by filter type


Each filter type has its own interface with a different set of attributes. The filter interfaces
are part of the powerbi-models library.

Basic filter
Basic filter has a single operator with one or more values.

TypeScript

interface IBasicFilter extends IFilter {


operator: BasicFilterOperators;
values: (string | number | boolean)[];
requireSingleSelection?: boolean;
}

operator - For basic filter the operator can be one of the following:

TypeScript

type BasicFilterOperators = "In" | "NotIn" | "All"

values - An array of values for the filter, all values need to be of the same type.

requireSingleSelection - Defines whether it is possible to select multiple values

on the filter. If it is set to true, only a single value can be selected.

For example:

JavaScript

const basicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Store",
column: "Count"
},
operator: "In",
values: [1, 2, 3, 4],
filterType: models.FilterType.BasicFilter,
requireSingleSelection: true
}
Advanced filter
Advanced filter has a single logical operator and one or two conditions that have their
own operator and value.

TypeScript

interface IAdvancedFilter extends IFilter {


logicalOperator: AdvancedFilterLogicalOperators;
conditions: IAdvancedFilterCondition[];
}

logicalOperator - The logical operator can be one of the following:

TypeScript

type AdvancedFilterLogicalOperators = "And" | "Or";

conditions - An array of conditions for the advanced filter, each condition has an
operator and a value .

TypeScript

interface IAdvancedFilterCondition {
value?: (string | number | boolean | Date);
operator: AdvancedFilterConditionOperators;
}

The available operators for a condition are:

TypeScript

type AdvancedFilterConditionOperators = "None" | "LessThan" |


"LessThanOrEqual" |
"GreaterThan" | "GreaterThanOrEqual" | "Contains" | "DoesNotContain" |
"StartsWith" |
"DoesNotStartWith" | "Is" | "IsNot" | "IsBlank" | "IsNotBlank";

For example:

JavaScript

const advancedFilter = {
$schema: "http://powerbi.com/product/schema#advanced",
target: {
table: "Store",
column: "Name"
},
logicalOperator: "Or",
conditions: [
{
operator: "Contains",
value: "Wash"
},
{
operator: "Contains",
value: "Park"
}
],
filterType: models.FilterType.AdvancedFilter
}

7 Note

If you're creating an AdvancedFilter with only a single condition, set the


logicalOperator to "And" . The logical operator is ignored when being parsed by

Power BI because there's only one condition, and when the filter is serialized the
default logical operator is "And" . This ensures the filters returned when calling
getFilters , match the ones set using setFilters .

Top N filter
Top N filter has a single operator, item counter for the amount of items to display, and
order by target.

TypeScript

interface ITopNFilter extends IFilter {


operator: TopNFilterOperators;
itemCount: number;
orderBy: ITarget;
}

operator - The operator for Top N filter can be one of the following:

TypeScript

type TopNFilterOperators = "Top" | "Bottom";


itemCount - The amount of items to display.

orderBy - The target data field to sort by. For more information, see Use targets to
select which data field to act on.

For example:

JavaScript

const topNFilter = {
$schema: "http://powerbi.com/product/schema#topN",
target: {
table: "Store",
column: "name"
},
operator: "Top",
itemCount: 5,
orderBy: {
table: "Product",
measure: "Count of Product"
},
filterType: models.FilterType.TopN
};

Relative date and relative time filters


The relative date filter and the relative time filter both inherit from the
IRelativeDateTimeFilter interface:

TypeScript

interface IRelativeDateTimeFilter extends IFilter {


operator: RelativeDateOperators;
timeUnitsCount: number;
timeUnitType: RelativeDateFilterTimeUnit;
}

operator - The operator for relative date and time filters can be one of the

following:

TypeScript

enum RelativeDateOperators {
InLast = 0,
InThis = 1,
InNext = 2,
}
timeUnitsCount - The amount of time units.

timeUnitType - Defines the unit of time the filter is using.

TypeScript

enum RelativeDateFilterTimeUnit {
Days = 0,
Weeks = 1,
CalendarWeeks = 2,
Months = 3,
CalendarMonths = 4,
Years = 5,
CalendarYears = 6,
Minutes = 7,
Hours = 8
}

The following table lists the unit times supported by the relative date and relative
time filters.

Time unit Relative date Relative time

Days ✔ ✖

Weeks ✔ ✖

CalendarWeeks ✔ ✖

Months ✔ ✖

CalendarMonths ✔ ✖

Years ✔ ✖

CalendarYears ✔ ✖

Minutes ✖ ✔

Hours ✖ ✔

includeToday - Accepts a boolean value that specifies whether to include the

current day in the filter.

TypeScript

interface IRelativeDateFilter extends IRelativeDateTimeFilter {


includeToday: boolean;
}
7 Note

includeToday is only supported by the relative date filter.

A relative date filter example:

JavaScript

const relativeDateFilter = {
$schema: "http://powerbi.com/product/schema#relativeDate",
target: {
table: "Sales",
column: "OrderDate"
},
operator: models.RelativeDateOperators.InLast,
timeUnitsCount: 30,
timeUnitType: RelativeDateFilterTimeUnit.Days,
includeToday: true,
filterType: models.FilterType.RelativeDate
};

A relative time filter example:

JavaScript

const relativeTimeFilter = {
$schema: "http://powerbi.com/product/schema#relativeTime",
target: {
table: "Sales",
column: "OrderDate"
},
operator: models.RelativeDateOperators.InLast,
timeUnitsCount: 12,
timeUnitType: models.RelativeDateFilterTimeUnit.Hours,
filterType: models.FilterType.RelativeTime
};

Filters APIs
Use the following methods to get and update the filters applied to a report:

Get filters - getFilters


Update filters- updateFilters .

Get filters
Use getFilters to get all the filters for one of the following objects:

Report
Page
Visual

TypeScript

getFilters(): Promise<IFilter[]>

Update filters
Use updateFilters to add, replace or remove filters on the object (report, page or
visual). Receives an operation and an optional filters array.

TypeScript

updateFilters(operation: models.FiltersOperations, filters?:


models.IFilter[]): Promise<IHttpPostMessageResponse<void>>

Filters operation

When calling updateFilters you need to pass the filter operation you want to preform.
The available operations are:

RemoveAll - Removes all filters on the filter level.

ReplaceAll - Replaces all existing filters on the filter level with the given filters.
Add - Adds the given filters on the filter level (in addition to the existing filters).

Replace - Replaces an existing filter with a given filter only if both filters apply to
the same data field. If there is a given filter that doesn't replace an existing filter, it
will be added.

7 Note

When calling the API with RemoveAll , the filters argument must be undefined . For
any other operations, it must be defined.

Filters levels
Updating and getting the filters can be done at three levels. Filters on different level are
independent, and updating filters on one level, will not change another. For example,
removing a page filter, doesn't remove it from other pages in the report.

The supported levels for filters are:

Report - The filters are applied to all the pages in the report.
Page - The filters are applied to the current report page.
Visual - The filters are applied to a specific visual.

7 Note

Only visual level filters support the ITopNFilter filter type.

Report level filters


To get or update the filters that apply to all the pages in the report, call the relevant API
on the report object. For example:

Get the report filters

Getting the filters applied to all pages.

JavaScript

let reportFilters = await report.getFilters();

Add new filters to the report filters

Adding new filters, alongside the existing filters, for all pages.

JavaScript

await report.updateFilters(models.FiltersOperations.Add, filtersArray);

Remove the report filters

Remove the filters applied to all pages.

JavaScript
await report.updateFilters(models.FiltersOperations.RemoveAll);

Page level filters


To get or update page level filters, do the following:

1. Get the page object for the target page. For more information, see Get pages and
visuals.
2. On the page object, call the relevant API.

Get the page filters

Getting the filters applied to a specific page.

JavaScript

let reportFilters = await page.getFilters();

Replace all the page filters

Replacing all existing filters applied to a specific page, with a new set of filters.

JavaScript

await page.updateFilters(models.FiltersOperations.ReplaceAll, filtersArray);

Remove the page filters

Removing the filters applied to a specific page.

JavaScript

await page.updateFilters(models.FiltersOperations.RemoveAll);

Visual level filters


To get or update visual level filters, do the following:

1. Get the visual object for the target visual. For more information, see Get pages and
visuals.
2. On the visual object, call the relevant API.

Get the visual filters


Getting the filters applied to a specific visual.

JavaScript

let reportFilters = await visual.getFilters();

Replace visual filters with same target


Replacing the filters of a specific visual. If a filter exists with the same target data field as
a given filter, it is replaced by the given filter. Given filters that don't match any existing
filter are added.

JavaScript

await visual.updateFilters(models.FiltersOperations.Replace, filtersArray);

Remove the visual filters


Removing the filters applied to a specific visual.

JavaScript

await visual.updateFilters(models.FiltersOperations.RemoveAll);

Limitations
Having more than two conditions when building an Advanced filter may cause
undefined behavior.

IncludeExclude and Tuple filter types are not supported.

Tuple and hierarchy filter targets are not supported.

Next steps
Configure report settings
Control report slicers
Personalize a report layout
Enhance your users' experience with
bookmarks
Article • 02/26/2023

Report bookmarks in Power BI let you capture the current state of an embedded report
page, including all filters and the state of its visuals. When you open the report at a later
time, you can select the a bookmark to restore the report to the saved state. Developers
can control the user experience by using the Power BI Client APIs to capture and apply
bookmarks.

A saved bookmark can either be a bookmark that was saved as part of a report or a
bookmark that was captured as a real-time state of a report. If you apply a saved
bookmark when you load a report, you can specify the bookmark to use by providing
either the bookmark's name or its state. If you provide a bookmark by name, your report
needs to contain a saved bookmark with that same name.

This article explains the different API settings you'll need to embed reports that support
bookmarks.

7 Note

In reports you embed for your organization, report consumers create personal
bookmarks by capturing the state of the report, and quickly returning to that state
by selecting the bookmark. See Personal bookmarks for more information.

For information on how to create a similar experience in reports you embed for
your customers, see the capture report view showcase in the Power BI embedded
analytics playground.

For more information about using bookmarks in Power BI, see Create bookmarks in
Power BI Desktop.

For information about using personal bookmarks when embedding Power BI, see
Personal bookmarks.

How to use report bookmarks


The following sections show how to use the Power BI Client APIs to work with report
bookmarks.
Manage a report's bookmarks
To manage a report's bookmarks, use the bookmarksManager property of an embedded
report instance.

The BookmarksManager class has the following methods:

getBookmarks - Returns a list of saved bookmarks associated with the report.

apply - Applies by name a previously saved bookmark to the report.

capture - Captures and returns a base64-serialization string, which represents the


current state of the report.

applyState Applies a previously captured base64-serialization state of a bookmark

to the report.

play - Controls the slide show presentation mode for the report's bookmarks.

Access a report bookmark


To access an individual bookmark, use the getBookmarks method to access a list of
ReportBookmark objects. The ReportBookmark class has the following properties:

name - The unique identifier of the report bookmark.

displayName - The display name of the report bookmark, which appears in the

Bookmarks pane.

state - A base64 serialization of the report bookmark's state. You can save it and
apply it to a report with the bookmarksManager.applyState method.

children - A list of ReportBookmark objects representing a report bookmark group,


if it exists.

Use the report bookmarks APIs


In an embedded report, developers can:

Get a list of saved report bookmarks.


Apply a saved bookmark by name on report load or during a session.
Capture and get a current view as a bookmark object.
Apply a captured bookmark state on report load or during a session
Perform additional logic when a report bookmark is applied.
Show or hide the Bookmarks pane.
Enter or exit bookmarks slide show mode.

Get a list of saved report bookmarks


To get the list of saved bookmarks associated with a report, call the getBookmarks
method of the BookmarksManager object returned by the report's bookmarksManager
property.

The getBookmarks method is defined as follows:

TypeScript

getBookmarks(): Promise<models.IReportBookmark[]>

For example:

JavaScript

let bookmarks = await report.bookmarksManager.getBookmarks();

Apply a saved bookmark by name on report load or


during a session
To apply a previously saved bookmark to a report by using its bookmark name, call the
apply method of the BookmarksManager object returned by a report's

bookmarksManager property.

For more information, see Configure report settings.

The apply method is defined as follows:

TypeScript

apply(bookmarkName: string): Promise<void>

For example:

JavaScript

await report.bookmarksManager.apply("Bookmark1234");
Capture and get a current view as a bookmark object
To capture the current state of a report as a base64 string, call the capture method of a
BookmarksManager object. The capture method returns an IReportBookmark object,
which represents a bookmark that's not saved in a specific report. Use the
IReportBookmark.state property to return the base64 string identifying the bookmark
state, which you can later apply to a report during load time or run time.

The capture method is defined as follows:

TypeScript

capture(options?:ICaptureBookmarkOptions): Promise<models.IReportBookmark>

For example:

JavaScript

let capturedBookmark = await report.bookmarksManager.capture();

Capture bookmark options


You can also pass an ICaptureBookmarkOptions object to the capture method.

TypeScript

interface ICaptureBookmarkOptions {
allPages?: boolean;
personalizeVisuals?: boolean;
}

allPages - By default, the captured bookmark state will save only the current page

state. To capture the state of all pages, call capture method with allPages option
set to true .
personalizeVisuals - To capture the current state with personalized visuals, call
the capture method with the personalizeVisuals option set to true .

For example, the following code captures the state of all pages, including the
personalized visuals:

JavaScript
let capturedBookmark = await report.bookmarksManager.capture({
allPages: true,
personalizeVisuals: true
});

Apply a captured bookmark state on report load or


during a session
To apply a previously captured bookmark state to a report, use the applyState method
of a BookmarksManager object.

For more information, see Configure report settings.

The applyState method is defined as follows:

TypeScript

applyState(state: string): Promise<void>

For example:

JavaScript

await report.bookmarksManager.applyState(capturedBookmark.state);

Perform additional logic when a report bookmark is


applied
To determine when a report bookmark has been applied, listen for the bookmarkApplied
event by calling the on method of the report object.

For example:

JavaScript

report.on("bookmarkApplied", (event) => {


console.log(event.detail.name);
});

Show or hide the Bookmarks pane


To show or hide the Power BI Bookmarks pane, update the panes property of the report
settings.

Show the Bookmarks pane

JavaScript

let embedConfig = {
...
panes: {
bookmarks: {
visible: true
}
}
};

Hide the Bookmarks pane

JavaScript

let embedConfig = {
...
panes: {
bookmarks: {
visible: false
}
}
};

For information about updating report settings, see Configure report settings.

Enter or exit bookmarks slide show mode


To control the slide show presentation mode for a report's bookmarks, call the play
method of a BookmarksManager object. For more information, see Bookmarks as a slide
show.

The play method is defined as follows:

TypeScript

play(playMode: models.BookmarksPlayMode): Promise<void>


7 Note

Before entering bookmarks slide show mode, make sure that there is at least one
bookmark on the report with getBookmarks API.

Enter slide show presentation mode

JavaScript

await report.bookmarksManager.play(models.BookmarksPlayMode.Presentation);

Exit slide show presentation mode

JavaScript

await report.bookmarksManager.play(models.BookmarksPlayMode.Off);

Limitations
When you use the bookmarks API, certain changes to the report can cause an error
or an unexpected result. One example of this is removing report filters from the
report. To avoid errors, the corresponding filter cards must be present. Instead of
removing the filters, set their values to All . If you don’t know which filters were
deleted or changed, recapture the bookmark after you apply the changes to the
report.

Filters such as on load filters created by the embed session or added by the update
filters add operation, are captured in the bookmark state but will be applied only in
the current session. To overcome this limitation, the filter should be saved on the
report with the All value, and modified in the embed session using the update
filters update operation.

Next steps
Control report filters
Control report slicers
How to handle events
Export data from a visual
Article • 04/12/2022

In Power BI you can export the data that was used to create a visual as an Excel or a CSV
file, by using the Export data command on the options menu.

The Export data command in the options menu lets you export the data that was used
to create a visual into an Excel or a CSV file.

Use the Power BI Client visual.exportData API to export data from a report visual into
CSV format.

How to export a visual's data


The Power BI Client VisualDescriptor class defines the exportData method as:

TypeScript

exportData(exportDataType?: ExportDataType, rows?: number):


Promise<IExportDataResult>
The exportData method uses two parameters:

exportDataType (optional), choose which data you like to export Summarized data
or Underlying data.
ExportDataType.Summarized , select this option if you want to export data for
what you currently see in the visual.
ExportDataType.Underlying , select this option if you want to export data for

what you see in the visual plus additional data from the underlying dataset.

If not provided the data will be exported Summarized. Learn more about the
different types in Export data from a visual.

rows, the number of rows to return, if available.

The exportData method returns an IExportDataResult object, use the


IExportDataResult.data property to get the exported data as a string in a CSV format.

TypeScript

interface IExportDataResult {
data: string;
}

Example
To export the first 100 rows of summarized data:

JavaScript

let result = await visual.exportData(models.ExportDataType.Summarized, 100);

console.log(result.data);

Considerations and limitations


The maximum number of rows you can export is 30,000.
Exports using Underlying don't work if the data source uses Analysis Services live
connection on versions older than 2016, when the tables in the model do not have
a unique key.
Exports using Underlying don't work if Show items with no data is enabled for the
visualization.
If filters are applied to the visualization, the exported data will also be filtered.
If using DirectQuery, the maximum amount of data that can be exported is 16 MB.
Exports may result in less than the maximum number of rows, especially if when
using multiple columns, data that is difficult to compress, or factors are present
that increase file size and decrease number of rows exported.
Power BI only supports export on visuals that use basic aggregates. Export is not
available on visuals using model or report measures.
Custom and R visuals, aren't supported.
Power BI admins can to disable the export data feature.
Concurrent export data requests from the same session aren't supported. Multiple
requests should be run synchronously.

Next steps
Get pages and visuals

Modify menu commands for a report visual

Hide or show a visual header


Control report slicers
Article • 01/22/2023

Using the slicer APIs, you can get and set the state of a Power BI slicer. In addition, you
can use load configuration to change the slicer state when loading a report.

There are two type of slicer visuals:

Out-of-the-box - Slicers for out-of-the-box Power BI visuals. Out-of-the-box slicers


support all the Power BI visuals that are shipped with Power BI (Desktop and
service).

Power BI visuals from AppSource and files - Slicers for third party Power BI
visuals, available from AppSource, or as a .pbiviz file. Slicers for Power BI visuals
from AppSource and files, or in short visuals from AppSource or files, are slicers for
Power BI visuals built by developers.

Slicer object
There are four slicer types:

Categorical slicers
Range slicers
Relative date slicers
Hierarchy slicers

Categorical slicer
Categorical slicers support the following displays:

A list
A dropdown menu
Value cards

You can select single or multiple items from these lists to filter the report accordingly.

To change a selection for these type of slicers, you need to create an IBasicFilter
object. For more information about creating a basic filter, see Basic filter.

JavaScript

const basicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Store",
column: "Count"
},
operator: "In",
values: [1, 2, 3, 4],
filterType: models.FilterType.BasicFilter
};

await visual.setSlicerState({
filters: [basicFilter]
});

If the slicer target is a hierarchy, provide an IFilterHierarchyTarget target. For more


information, see Use targets to select which data field to act on.

JavaScript

const basicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Store",
hierarchy: "Country",
hierarchyLevel: "Code"
},
operator: "In",
values: [456, 943],
filterType: models.FilterType.BasicFilter
};

await visual.setSlicerState({
filters: [basicFilter]
});

Range slicer
Range slicers support conditions such as:

Between
Before
After

To change a selection for range slicers, create an IAdvancedFilter object. For more
information, see Advanced filter.

JavaScript
const advancedFilter = {
$schema: "http://powerbi.com/product/schema#advanced",
target: {
table: "Store",
column: "Number"
},
logicalOperator: "And",
conditions: [
{
operator: "GreaterThanOrEqual",
value: 30
},
{
operator: "LessThan",
value: 40
}
],
filterType: models.FilterType.AdvancedFilter
};

await visual.setSlicerState({
filters: [advancedFilter]
});

Relative date slicer


Relative date slicers support conditions such as:

Last Week
Last five years

To change a selection for relative date slicers, create an IRelativeDateFilter object. For
more information, see Relative date and relative time filter objects.

JavaScript

const relativeDateFilter = {
$schema: "http://powerbi.com/product/schema#relativeDate",
target: {
table: "Sales",
column: "OrderDate"
},
operator: models.RelativeDateOperators.InLast,
timeUnitsCount: 30,
timeUnitType: models.RelativeDateFilterTimeUnit.Days,
includeToday: true,
filterType: models.FilterType.RelativeDate
};

await visual.setSlicerState({
filters: [relativeDateFilter]
});

Relative time slicer


Relative time slicers support conditions such as:

Last five minutes


This hour

To change a selection for relative time slicers, create an IRelativeTimeFilter object. For
more information, see Relative date and relative time filters.

JavaScript

const relativeTimeFilter = {
$schema: "http://powerbi.com/product/schema#relativeTime",
target: {
table: "Sales",
column: "OrderDate"
},
operator: models.RelativeDateOperators.InLast,
timeUnitsCount: 5,
timeUnitType: models.RelativeDateFilterTimeUnit.Minutes,
filterType: models.FilterType.RelativeTime
};

await visual.setSlicerState({
filters: [relativeTimeFilter]
});

Hierarchy slicer
Hierarchy slicers let you filter from multiple related fields.
The Hierarchy slicer is supported from SDK version 2.21. Set selections in the hierarchy
slicer with the setSlicerState API or get the current hierarchy selections with
getSlicerState API.

Read about adding fields to hierarchy slicers.

Hierarchy filter
The IHierarchyFilter describes the slicer hierarchy. Use the getSlicerState and
setSlicerState methods with this filter.

JavaScript

interface IHierarchyFilter extends IFilter {


target: (IFilterTarget | IFilterKeyTarget)[];
hierarchyData: IHierarchyFilterNode[];
}
hierarchyData - the selected and unselected items in a hierarchy tree where each

IHierarchyFilterNode represents a single value selection.

JavaScript

interface IHierarchyFilterNode {
value?: PrimitiveValueType;
keyValues?: PrimitiveValueType[];
children?: IHierarchyFilterNode[];
operator?: HierarchyFilterNodeOperators;
}

Either value or keyValues must be set


children – List of the node children relevant to the current selection
operator – The operator for single objects in the tree. The operator can be one

of the following:

type HierarchyFilterNodeOperators = "Selected" | "NotSelected" | "Inherited";

Selected – value is explicitly selected.

NotSelected – value is explicitly not selected.


Inherited – value selection is according to the parent value in the hierarchy, or

default if it's the root value.

operator is optional. If no operator is set, the default is Inherited .

Hierarchy slicer examples


The following examples describe different scenarios for using the setSlicerState API
with hierarchy slicers.

Select values on different levels. For example, select ‘Qtr 1’ and ‘Qtr 2’ in 2013 and
‘Qtr 1’ and ‘Qtr 2’ in 2014.

JavaScript

const filter = {
"$schema": http://powerbi.com/product/schema#hierarchy,
"target": [
{
"table": "Dates",
"hierarchy": "Date Hierarchy",
"hierarchyLevel": "Year"
},
{
"table": "Dates",
"hierarchy": "Date Hierarchy",
"hierarchyLevel": "Quarter"
}
],
"filterType": 9,
"hierarchyData": [
{
"operator": "Inherited",
"value": 2013,
"children": [
{
"operator": "Selected",
"value": "Qtr 1"
},
{
"operator": "Selected",
"value": "Qtr 2"
}
]
},
{
"operator": "Inherited",
"value": 2014,
"children": [
{
"operator": "Selected",
"value": "Qtr 1"
},
{
"operator": "Selected",
"value": "Qtr 2"
}
]
}
]
};

await slicer.setSlicerState({ filters: [filter] });


Select values on different levels with exceptions. For example, select 2014 without
‘Qtr 1’.

JavaScript

const filter = {
"$schema": http://powerbi.com/product/schema#hierarchy,
"target": [
{
"table": "Dates",
"hierarchy": "Date Hierarchy",
"hierarchyLevel": "Year"
},
{
"table": "Dates",
"hierarchy": "Date Hierarchy",
"hierarchyLevel": "Quarter"
}
],
"filterType": 9,
"hierarchyData": [
{
"operator": "Selected",
"value": 2014,
"children": [
{
"operator": "NotSelected",
"value": "Qtr 1"
}
]
}
]
};

await slicer.setSlicerState({ filters: [filter] });

Start with the NotSelected operator to select everything except for certain values.
For example, select everything except for ‘Qtr 1’ of 2008, and 2009.

JavaScript

const filter = {
"$schema": http://powerbi.com/product/schema#hierarchy,
"target": [
{
"table": "Dates",
"column": "Year"
},
{
"table": "Dates",
"column": "Quarter"
}
],
"filterType": 9,
"hierarchyData": [
{
"operator": "NotSelected",
"value": 2009
},
{
"operator": "Inherited",
"value": 2008,
"children": [
{
"operator": "NotSelected",
"value": "Q1"
}
]
}
]
}

await slicer.setSlicerState({ filters: [filter] });

Slicer APIs
You can use the following methods for visuals with the slicer type:

Get slicer state - getSlicerState


Set slicer state - setSlicerState

7 Note

Sync slicers configuration saved in a report is recognized by the slicer APIs. This
means that if you set a slicer using the API, all slicers in the same sync group will be
affected.

Get slicer state


To get a slicer state, you need to find the slicer visual instance and call getSlicerState .
The result is of type ISlicerState .

By default, the slicer will not have any filters applied to it. In such cases, getSlicerState
will return ISlicerState with an empty array of filters.

getSlicerState works for both out-of-the-box and visuals from AppSource or files slicers.

JavaScript

let state = await visual.getSlicerState();

Set slicer state


To set a slicer state, you need to find the slicer visual instance, create the slicer state and
call setSlicerState with the slicer state you created.

JavaScript

await visual.setSlicerState(state);

The slicer state is an ISlicerState object.

TypeScript

interface ISlicerState {
filters: ISlicerFilter[];
targets?: SlicerTarget[];
}
To reset a slicer, call setSlicerState with an empty array of filters.

Setting a slicer for visuals from AppSource or files

To set a visuals from AppSource or files slicer selection, you need to create an
ISlicerFilter object, which can be of the following types:

IBasicFilter
IAdvancedFilter

IRelativeDateFilter

IRelativeTimeFilter

Different visuals from AppSource or files slicers, support different types of filters. To
determine the filter type required to modify the slicer, call visual.getSlicerState() .

For more information about filter types, see Control report filters.

Setting slicers on report load


Report load configuration supports changing slicers state. This allows you to change the
report slicers state during report load. To do this, pass an ISlicer array.

TypeScript

interface IReportLoadConfiguration {
...
slicers?: ISlicer[];
}

Each ISlicer object contains a selector and a slicer state.

TypeScript

interface ISlicer {
selector: SlicerSelector;
state: ISlicerState;
}

Use a visual name or slicer target selector to select which slicer to change. For more
information, see Use selectors to control which visuals are effected.

7 Note
If you pass different ISlicer objects that are in the same sync group, the result will
be unexpected.

Apply slicer on load examples


This section includes two examples of load configuration with slicers.

Set a specific slicer by name

JavaScript

let slicers = [
{
selector: {
$schema: "http://powerbi.com/product/schema#visualSelector",
visualName: "d1feb8891635af3b335a"
},
state: {
filters: [advancedFilter]
}
}
];

let embedConfig = {
...
slicers: slicers,
};

Set slicers by slicer target

JavaScript

let target = {
table: "Store",
column: "StoreNumber"
};

let slicers = [
{
selector: {
$schema:
"http://powerbi.com/product/schema#slicerTargetSelector",
target: target
},
state: {
filters: [advancedFilter]
}
}
];
let embedConfig = {
...
slicers: slicers,
};

Considerations and limitations


Tuple slicers are not supported.

The Hierarchy slicer is supported from SDK version 2.21.

Out-of-the-box slicers support only a single filter.

Calling setSlicerState on a visual which is not a slicer, will return a rejected


promise with the error Operation works on slicers only.

There is no API to change the slicers sync configuration.

Next steps
Embed using filters
Get pages and visuals
Configure report settings
Personalize a report layout
Article • 05/12/2021

With a custom report layout, you can embed a Power BI report with a different layout
than what was saved in the original report. When you define a custom report layout, you
can vary the size of a report page, and control the size, position, and visibility of visuals
on the page.

Custom layout overview


To create a custom report layout, define a custom layout object and pass it to the
settings object in an embed configuration.

In the settings object, set layoutType to models.LayoutType.Custom and set


customLayout to your custom layout object:

JavaScript

let embedConfig = {
...
settings: {
layoutType: models.LayoutType.Custom
customLayout: {...}
}
};

For more information about report settings, see Configure report settings.

How to define a custom report layout


Each custom report layout is represented by a custom layout object that you define to
specify the page size, canvas scale, and pages layout. Within the pages layout, you can
specify a visual layout for each visual and a default visual layout for the report.

Custom layout interface definition


Use the ICustomLayout interface to define a custom layout object:

JavaScript

interface ICustomLayout {
pageSize?: IPageSize;
displayOption?: DisplayOption;
pagesLayout?: PagesLayout;
}

The ICustomLayout interface has the following properties:

pageSize - An IPageSize object that defines the page size of the canvas area for
the report.

JavaScript

interface IPageSize {
type: PageSizeType;
}

The IPageSize object uses the PageSizeType enum to set the page size:

JavaScript

enum PageSizeType {
Widescreen,
Standard,
Cortana,
Letter,
Custom
}

displayOption - A DisplayOption enum that controls how to scale the canvas to fit

in the frame.

JavaScript

enum DisplayOption {
FitToPage,
FitToWidth,
ActualSize
}

pagesLayout - A PagesLayout object that controls the layout for each visual on a

page. This property maps a page name to a PageLayout object. For more
information, see Define a pages layout.

TypeScript

type PagesLayout = { [key: string]: IPageLayout; }


Define a pages layout
Use the IPageLayout interface to define a pages layout object. The interface enables you
to define a visual layout map, which maps each visual name to a new layout object, and
a default visual layout. Defining a pages layout is optional. If you don't provide a layout
for a report, Power BI applies the default layout to the report. That is, the default layout
is what applies to all the visuals that you don't specify in the visuals layout object. For
example, you can initially hide all the visuals in a report, and then show selected visuals
in the layout of your choice.

JavaScript

interface IPageLayout {
defaultLayout: IVisualLayout,
visualsLayout: { [key: string]: IVisualLayout; };
}

The IPageLayout interface has the following properties:

defaultLayout - An IVisualLayout object that defines the default visual layout.


The default layout is automatically applied to all the visuals on the report page.

TypeScript

defaultLayout?: IVisualLayout

visualsLayout - A VisualsLayout object that defines a map between the visual


names and visual layouts on the report page.

TypeScript

visualsLayout: VisualsLayout

TypeScript

VisualsLayout = { [key: string]: IVisualLayout; }

Define a visual layout


To define a visual layout, use the IVisualLayout interface to create a visual layout object
and set its position, size, and visibility.
JavaScript

interface IVisualLayout {
x?: number;
y?: number;
z?: number;
width?: number;
height?: number;
displayState?: IVisualContainerDisplayState;
}

The IVisualLayout interface has the following properties:

x , y , z - Defines the x, y, and z coordinates of the visual.

width , height - Defines the width and height of the visual.

displayState - An IVisualContainerDisplayState object that defines the visibility

of the visual.

JavaScript

interface IVisualContainerDisplayState {
mode: VisualContainerDisplayMode;
}

The IVisualContainerDisplayState object uses the VisualContainerDisplayMode


enum to set the visibility:

JavaScript

enum VisualContainerDisplayMode {
Visible,
Hidden
}

Update the layout


To update the report layout when the report is already loaded, use the
report.updateSettings method. For more information, see Update report settings at

runtime.

Example
This complete code example shows how to embed a report with a custom report layout.
All visuals are hidden except for two visuals: VisualContainer1 and VisualContainer2.
VisualContainer1 has a new layout, position, and size, while VisualContainer2 is visible
with the report's default layout.

JavaScript

// Get models. Models contains enums that can be used.


let models = window['powerbi-client'].models;

let embedConfig = {
type: 'report',
id: reportId,
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Embed,
accessToken: 'H4...rf',
settings: {
layoutType: models.LayoutType.Custom
customLayout: {
pageSize: {
type: models.PageSizeType.Custom,
width: 1600,
height: 1200
},
displayOption: models.DisplayOption.ActualSize,
pagesLayout: {
"ReportSection1" : {
defaultLayout: {
displayState: {
mode: models.VisualContainerDisplayMode.Hidden
}
},
visualsLayout: {
"VisualContainer1": {
x: 1,
y: 1,
z: 1,
width: 400,
height: 300,
displayState: {
mode:
models.VisualContainerDisplayMode.Visible
}
},
"VisualContainer2": {
displayState: {
mode:
models.VisualContainerDisplayMode.Visible
}
},
}
}
}
}
}
};
...
// Embed the report and display it within the div container.
let report = powerbi.embed(embedContainer, embedConfig);

Next steps
Get pages and visuals

Configure report settings


Apply report themes
Article • 12/13/2021

Power BI report themes allow you to apply design changes to your entire report. For
example, you can include your corporate colors, and change your icon sets. When you
apply a report theme, all visuals in your report use the colors and formatting from your
selected theme as their defaults. For more information about theme settings and how
they are designed, see Report theme JSON file format.

You can save and publish a report with a theme applied to it. The applied theme will be
the default theme for this report when it's loaded in Power BI Service or Power BI
embedded analytics.

Developers using Power BI embedded analytics also have the ability to embed a report
with a custom theme applied instead of the default theme for the report. Applying a
theme this way loads the same report with different themes to different users according
to their settings.

Report theme object


This section describes the report theme object which is used to represent themes. An
IReportTheme object type can be passed to the embedded configuration.

TypeScript

interface IEmbedConfiguration extends IEmbedConfigurationBase {


...
theme?: models.IReportTheme;
}

The report theme object should have a single parameter named themeJson . This field
should contain the JSON object that represent the theme settings. For additional
information, see the Report theme JSON file format page.

TypeScript

interface IReportTheme {}
interface ICustomTheme extends IReportTheme {
themeJson: any;
}
Apply a theme to a report
The applied theme can also be changed after the report is loaded. Applying the theme
after the report loads lets you support scenarios where the end-user selects a theme
from a list and see the style changes applied to the report immediately without
reloading.

Apply a theme on load


This example is useful if you want to apply a custom theme on report load.

TypeScript

// Parse the theme JSON file into an object


let themeJsonObject = parseJsonfile(path);
let embedConfig = {

theme: {
themeJson: themeJsonObject
}
};

let report = powerbi.embed(embedContainer, embedConfig);

Apply theme in run time


The apply method is useful if you want to change the theme after the report is loaded
without reloading the report.

The Power BI Client Report class, defines the applyTheme method as:

TypeScript

applyTheme(theme: models.IReportTheme): Promise<void>

The applyTheme API will change the theme that is applied to the report in run time.

TypeScript

...
// Parse the theme JSON file into an object
let themeJsonObject = parseJsonfile(path);

// Apply the theme


report.applyTheme({ themeJson: themeJsonObject });
Apply a theme when you create a report
A new embedded report can be created with a theme applied to it. New visuals added
to the report will respect the theme style. See also the Create, edit, and save an
embedded report page.

This example is useful if you want to apply a custom theme to a new report.

TypeScript

// Parse the theme JSON file into an object


let themeJsonObject = parseJsonfile(path);
let embedCreateConfiguration = {

theme: {
themeJson: themeJsonObject
}
};

let report = powerbi.createReport(embedContainer, embedCreateConfiguration);

7 Note

parseJsonfile is a function that needs to be implemented on the application code

and isn't part of the SDK.

Reset a report theme


The reset method is useful if you want to reset the report theme to the default theme
but you don't have the theme JSON file.

The Power BI Client Report class, defines the resetTheme method as:

TypeScript

resetTheme(): Promise<void>

Calling the resetTheme API returns to the default theme of the report.

TypeScript

// Apply the theme


report.resetTheme();
Limitations and considerations
Using the applyTheme API described above overrides the default theme entirely
with the new JSON file. The API won't extend the configuration of the default
theme.
There are a few times when when applying themes won't change the visuals in the
report like you're expecting. For more information, see Situations when Report
Theme colors won't stick to your reports.
You can't use the API to apply a theme and set a contrast level at the same time. If
you configure both properties, the API uses the contrast level that you specified
but ignores the theme setting.

Next steps
Configure report settings

Accessibility for your embedded solution


Modify menu commands for a report
visual
Article • 12/05/2022

Visuals in Power BI have menus that let your app users change the way they see their
data. For example, using the Context menu, data points can be included or excluded
from a visual. The Options menu can be used to export the data contained in a visual to
a spreadsheet.

Open the Context menu by right-clicking a visual or a specific data point within a visual.

Open the Options menu by selecting the ellipsis in the top-right corner of the visual.

7 Note

If the visual header for a visual is hidden, the ellipsis does not display.
This API provides a way to extend these menus, so you to add commands for your users
and enhance the app experience. You can further customize the menus by hiding or
disabling actions. For example, you can hide the Spotlight built-in command for the
options menu.

How to modify menu commands


Modify the menus by using extensions to add commands, and commands to change how
the built-in commands display.

You can configure the API to work on report load (embed configuration), or you can call
the report updateSettings method to update the added items after a report loads. See
Configure report settings and Hide or show visual headers to learn more.

The new menu settings are applied on all visuals in the report. To apply a setting to a
specific visual, use Selectors.

Extend menu commands


Use the following parameters to build a command definition:

name - The command name.


title - The title for the command. This will be used as default , if there is no
override inside visualContextMenu and visualOptionsMenu .
icon (optional) - The image you want to display as an icon. Icons are only
supported in the options menu.
extend - Define the menu that the command extends. You can add the command
to the visual context menu, the visual options menu, or both. It's also possible to
customize the properties in each menu, such as the menu title or icon location.

Add the command definition to the commands array in the extensions object, which is
passed to the report settings. Commands is an array of ICommandExtension inside
extensions which is of type IExtensions.

JavaScript

let embedConfig = {
...
settings: {
extensions: {
commands: [...]
}
}
};

You should also handle the commandTriggered event for the new command. This event is
triggered specifically for the commandName .

JavaScript

report.on("commandTriggered", function(event) {
let commandName = event.detail.command;
...
if (commandName === "command name") {
// Handler code
}
});

For more information about handling events, see How to handle events.

Icons are optional. If you choose to use one, it must be converted to Base64. See the
following for an example of a valid Base64 icon.

JavaScript

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACcFBMV
EUAAAAAAAAAAAAAAAA/Pz8zMzMqKiokJCQfHx8cHBwZGRkuLi4qKionJyckJCQiIiIfHx8cHBwoK
CgmJiYkJCQiIiIhISEfHx8eHh4nJyclJSUkJCQjIyMiIiIgICAfHx8mJiYlJSUkJCQjIyMhISEgI
CAfHx8lJSUkJCQiIiIhISElJSUjIyMjIyMiIiIhISEhISElJSUkJCQjIyMiIiIhISEkJCQiIiIhI
SEkJCQjIyMjIyMiIiIiIiIhISEhISEjIyMjIyMjIyMiIiIiIiIhISEjIyMiIiIhISEkJCQjIyMiI
iIiIiIiIiIhISEkJCQjIyMjIyMiIiIiIiIhISEkJCQjIyMjIyMiIiIiIiIiIiIkJCQjIyMjIyMiI
iIiIiIiIiIjIyMjIyMjIyMiIiIiIiIiIiIiIiIjIyMjIyMjIyMiIiIiIiIiIiIjIyMjIyMjIyMjI
yMiIiIiIiIiIiIiIiIhISEiIiIiIiIjIyMhISEiIiIiIiIiIiIjIyMjIyMjIyMjIyMhISEiIiIiI
iIjIyMjIyMiIiIiIiIjIyMjIyMhISEiIiIiIiIjIyMjIyMjIyMjIyMjIyMjIyMhISEhISEiIiIjI
yMjIyMhISEiIiIiIiIjIyMjIyMjIyMhISEhISEiIiIjIyMjIyMjIyMhISEhISEiIiIjIyMjIyMjI
yMjIyMhISEhISEhISEiIiIjIyMjIyMjIyMhISEhISEhISEiIiIjIyMjIyMjIyMjIyMhISEhISEhI
SEjIyMjIyMjIyMhISEhISEhISEiIiIjIyMjIyMjIyMhISEhISEhISEhISEjIyMjIyMjIyMjIyNZp
HNAAAAAz3RSTlMAAQIDBAUGBwgJCgsMDQ4PEBITFBUWFxgZGhscHR4fICEiIyQmJygpKiwtMDIzN
DU2Nzg5Oz0/QkVGR0hJSktMTk9QUVJTVllbXF5fYGFiY2VmZ2hpamtsbm9wcXN0dXd4eXp7fH1+f
4CBg4SFhoeIiYqLjI2OkpOUl5mam5ydnp+goaKjpKapqqyusLGys7W2uru9vr/AwsTGx8jJysvNz
s/Q0dLU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8fLz9PX29/j5+vv8/f5uCdcaAAADyklEQ
VQYGe3B+0NTZQAG4NftsKFotUBFY5XiBexehnbTCEtLKaVMrKhhmVciTcuszIiiMivNUrNC0RTE1
KC4RyACbrDz/ksxQISxs53z7Zzz/bLnQUJCQkJCLEmedE8yhCR70j1JEDf/xT2H6/0M6Tx3cNuyW
6Fb2tPbv6u+whB/3aEPCubBKGVJeSPDqKc2ZUGH7C2nVYZpKHvcCf28u5oZ2YmVLkSV/PzvjKxp5
23QJ3NfgNr+XueCJvf6BmrzfzwLsaXsCDC62qXQkHuR0flLJiKGJfWM7atURDD1G8b216OIJmkXd
WlehHEeaaMeaqkCTdN+oU79RQizIUidjqVBw+w/qd8eB0ZxfkT9zt+BiBY00YgvHBjhrKARjVmI4
M4mGrN/AoZNKKcx/3gxztQLNGorhpXSqJpUhHEepXHLMeg5GnfEgbG2U0DXHAyY300BmzHGIpUiK
hVAqaKIYA5GcddSzBvABoqpduGGjRTUk+HtpaBijJjRQ1Fln1NU93Rct5vCgkEK24Fhqd2UosuDI
W9SEh+G1FKScxj0IKW5FyG7Kc1OhJyhNCcxIE2lNEEPgDxKlAvgLUpUDKCcEn0G4FdKdBzAJUp0A
UAbJWoB0EuJegBco0R9AOooUQeAE5SoHsABSnQGwIeU6ACATZToPQCrKVEBgGxKdA8GNFKaqwoGl
FGaHxGygtIUI2SaSlmyMKiKkpzHkC2UpARDZvZRCjUTwyooxU+4biGlWI4RlZSgTsGIVZTgFdzgb
qXt2lMwSiFt58NoSg1t1jARYyylzQoQ5jBt9YeCMAv6aaccjLOXNvoS46W10jYdMxBBLm2zChHto
02+R2RTLtEW/82EhoeDtMMyaHqXNtgLba5KWu7sJEThbaXFOuciqpw+WisPMbxMS5Uipk9ooYMOx
OQ6TsucngwdptfTIs1e6DKvjZa4cjd0uq+LFggshm6L/TSd+iwMeCZIs62FIS/RZMUwyEdTbYNhR
TRRCQSsp2negZC1Ks2xFYJWqzSDD8Ly+xk3tRBxeLKHcQqsQFwe+pdxufoY4jT3MuPQcj/iln6Kw
mpmwQRTDlHQUQ9MobxPIZ+6YJYX/DQsWAQTLWymQR1PwFQZJ2nI2UyYbNJ+GlAxGebL76FOgUJYI
ruaulx+ABZJKacOX98C66zsZAzda2Cp239mVL/NgcUcr12jpsBGBdbLrqSGqrtgC+erXYyg16fAL
hnfcpwfZsNOT9VyjIt5sFnSujaOaH/dDfvd9HYLB7VvvhlyuPOPdAePrUmBRIobCQkJCQnx+R9iL
yo0N1V+hgAAAABJRU5ErkJggg=="

The following is a full code example for adding a menu command extension.

JavaScript

// Get models. Models contain enums that can be used.


let models = window['powerbi-client'].models;

let embedConfiguration = {
type: 'report',
id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Aad,
accessToken: 'e4...rf',
settings: {
...
extensions: {
commands: [{
name: "command name",
title: "command title",
icon:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEU...AAABJRU5ErkJggg==",
extend: {
visualContextMenu: {
title: "context menu title",
},
visualOptionsMenu: {
title: "options menu title",
}
}
}]
}
}
};

...

// Embed the report and display it within the div container.


let report = powerbi.embed(embedContainer, embedConfiguration);

// Report.on will add an event handler to commandTriggered event which


prints to console window.
report.on("commandTriggered", function (command) {
console.log(command);
});

Set the menu item location


Commands are added to the bottom of the menu by default. For non-grouped
commands, you can use the menuLocation property to select whether a command is
placed at the top or bottom of the menu.

7 Note

When adding more than one extension to the top of the menu, the last extension
added will be at the top.

For example, the following code allows you to set the options menu command
extension at the top of the menu, and the context menu command at the bottom of the
menu.

JavaScript
extensions: {
commands: [{
name: "command name",
title: "command title",
icon:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEU...AAABJRU5ErkJggg==",
extend:
{
visualContextMenu: {
title: "context menu title",
menuLocation: models.MenuLocation.Bottom
},
visualOptionsMenu: {
title: "options menu title",
menuLocation: models.MenuLocation.Top
}
}
}]
}

Group commands in a submenu


You can create a submenu to group commands with the following parameters:

name - The group name. This is the group unique identifier.


title - The title to show on the menu.
menuLocation (optional) - Choose whether the group is placed at the top or
bottom of the menu.

The group definition should be added to the groups array, which is an array of
IMenuGroupExtension, inside the extensions object.

If you choose to use a menu location value, Top will place the group at the top of the
menu at the time of adding the group's first command. If unused, or when using the
Bottom value, the group will be added at the bottom of the menu at the time of adding

the group's first command.

To add a command to a group that was defined in the group array, add the groupName
property to the command.

Below is a full code example of how to add a submenu to the options menu with two
commands inside it.

JavaScript

extensions: {
commands: [
{
name: "Command 1",
title: "Command 1",
extend: {
visualOptionsMenu: {
groupName: "group-unique-identifier"
}
}
},
{
name: "Command 2",
title: "Command 2",
extend: {
visualOptionsMenu: {
groupName: "group-unique-identifier"
}
}
}
],
groups: [{
name: "group-unique-identifier",
title: "Group title",
menuLocation: models.MenuLocation.Top
}]
}

Customize menu commands


The display of built-in commands has three display modes.

Enabled - The command appears if it is available for the visual.


Disabled - The command appears if it is available for the visual but is grayed out
(the user cannot click the command).
Hidden - The command does not appear.
The currently available built-in commands are:

copy - Copy value, selection or visual. Available only under the context menu
(visual is available only in edit mode).
drill - Use the drill mode. Available only under the context menu.
drillthrough - Use the drill through feature. Available only under the context menu.
expandCollapse - Expand or collapse selection, entire level or entire hierarchy.
Available only under the context menu.
exportData - Export the data that was used to create a visualization. Available only
under the options menu.
includeExclude - Include or exclude data points. Available only under the context
menu.
removeVisual - Delete the visual. Available only under the options menu in edit
mode.
search - Toggle the search option for a slicer. Available only in edit mode.
seeData - Display the data that was used to create a visualization (Also known as
Show as a table).
sort - Sort and select the sort order of the values by a selected data field. Available
only under the options menu.
spotlight - Spotlight a visual. Available only under the options menu.
insightsAnalysis - Display insights about the visual. Available only under options
menu.
addComment - Add a comment to the visual. Available only under options menu.
groupVisualContainers - Available only under context menu in edit mode.
summarize - Display a summary of the visualization. Available only under the
context menu.
clearSelection - Available only under the context menu.

To customize the built-in commands display, define and pass a command object in the
embed configuration settings. Commands are an array of ICommandsSettings.

JavaScript

let embedConfig = {
...
settings: {
commands: [...]
}
};

Below is a full code example for adding built-in commands.

JavaScript
// The new settings that you want to apply to the report.
const newSettings = {
commands: [
{
spotlight: {
displayOption: models.CommandDisplayOption.Hidden,
},
drill: {
displayOption: models.CommandDisplayOption.Disabled,
}
}
]
};

// Update the settings by passing in the new settings you have configured.
await report.updateSettings(newSettings);

Next steps
Configure report settings

How to handle events

Get pages and visuals


Sort a visual by a target data field
Article • 01/24/2021

In Power BI, you can change how a visual looks by sorting it by different data fields. By
changing how you sort a visual, you can highlight the information you want to convey.
Whether you're using numeric data (such as sales figures) or text data (such as state
names), you can sort your visuals as desired. Power BI provides lots of flexibility for
sorting, and quick menus for you to use. To learn more, see Change how a chart is
sorted in a Power BI report

You can use the visual.sortBy API to change how you sort a visual by one of its data
fields. You can also control the direction of the sort.

How to sort a visual


The Power BI Client VisualDescriptor class defines a sortBy method as:

TypeScript

visual.sortBy(request: ISortByVisualRequest): Promise<void>

The ISortByVisualRequest interface includes a definition for the sort request:

JavaScript

export interface ISortByVisualRequest {


orderBy: ITarget;
direction: SortDirection;
}

orderBy, the target data field of the sort. Data fields that the visual can be sorted
by, are found in the visual’s option menu under the Sort by menu command,
Learn more about Use targets to select which data field to act on.

direction, the direction of the sort. The SortDirection enum defines the sort
direction as Ascending or Descending .

JavaScript

enum SortDirection {
Ascending = 1,
Descending = 2,
}

Example
To get the pages of a report, find the active page, and get the visuals. The visual is found
with the unique name VisualContainer1 and sorted descending by Total Category
Volume measure on the SalesFact table:

JavaScript

let pages = await report.getPages();

// Retrieve active page


var activePage = pages.find(function (page) { return page.isActive });

let visuals = await activePage.getVisuals();


// Retrieve target visual (replace "VisualContainer1" with requested visual
name)
var visual = visuals.find(function (visual) { return visual.name ===
"VisualContainer1" });

const request = {
// Set the target data field of the sort
orderBy: {
table: "SalesFact",
measure: "Total Category Volume"
},
direction: models.SortDirection.Descending
};

await visual.sortBy(request);

To sort a visual by a column target:

JavaScript

const request = {
// Set the target data field of the sort
orderBy: {
table: "Store",
column: "Name"
},
direction: models.SortDirection.Ascending
};

await visual.sortBy(request);

Next steps
Get pages and visuals

Configure data fields

Modify menu commands for a report visual

Hide or show a visual header


Hide or show visual headers
Article • 05/12/2021

Power BI reports that you embed in apps contain visuals, such as charts, heat maps, and
gauges. These visuals have headers that make actions available to users. When you use
Power BI, you can hide or show the header of each visual in a report. Each visual has a
card in the Formatting section of the Visualizations pane called Visual header. You can
use that card to turn the visual's header on and off. Learn more about visual headers in
Visual headers.

Examples of actions in visual headers include:

Opening the visual in focus mode.


Drilling down or up.
Viewing which filters and slicers are currently applied to the visual.
Opening the visual's options menu.

Sometimes it's useful to hide these actions. For instance, when two visuals overlap, you
might not want to display both visuals' headers.

This API provides a way to hide or show headers of all the visuals in a report or only
specific ones. You can configure the visibility on report load, or you can call the Report
updateSettings method to change the visibility after a report has loaded, see Update
report settings at runtime.

You can use the API in many scenarios, including the following use cases:

Hide only some of the visual headers in a report.


Use business logic in an app, such as a button click, to hide or show a header after
a report has loaded.

How to hide or show visual headers


To hide or show visual headers in the API, you configure certain parameters in a report's
settings. See Configure report settings for general information on configuring options in
embedded reports.

Visual header settings


With visual headers, visibility is currently the only setting that you can configure. To hide
or display headers, you provide a list of visual header configuration objects. Each one
contains a settings object and can also include a selector. Selectors identify the visuals
that you're applying the settings to. Learn more about selectors in Selectors.

The type of the configuration object that you provide to the API is IVisualSettings. Later
in this article, you'll find examples that show how to use this interface in your code.
Power BI models lists all interface definitions that the examples use.

Note the following points:

The selector is optional in these settings. When you don't list any selectors, the API
applies your settings to all the visuals in the report.
When you use selectors, you can specify visuals either by name or by type. To get
the names and types of the visuals in a given page, use the Page getVisuals
method.

Precedence rules
The API applies configuration settings in the following order:

Settings that are saved in the report.


Settings that you define in the embed configuration object, which the API applies
on load.
Settings that you provide to the updateSettings API.

If more than one setting can apply to a visual, the API uses the last setting that applies.
The Hide all but one visual header example in the next section illustrates this point.

Examples
These examples show different ways of using the API to hide or show visual headers.

Hide all visual headers


This simple scenario provides customers with a clean report view by hiding all the visual
headers in a report:

JavaScript

let embedConfig = {
...
settings: {
...
visualSettings: {
visualHeaders: [
{
settings: {
visible: false
}
/* No selector is listed. The API hides the headers of
all the visuals in the report. */
}
]
}
}
};
...
let report = powerbi.embed(embedContainer, embedConfig);

Hide a specific visual's header


This example uses a selector to apply a visibility setting to a single visual. This scenario
comes up when you want to hide functionality that doesn't make sense for a visual. Use
this code in that case:

JavaScript

let embedConfig = {
...
settings: {
...
visualSettings: {
visualHeaders: [
{
settings: {
visible: false
},
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: <The name of the visual> // You can
retrieve the name by using getVisuals.
}
}
]
}
}
};
...
let report = powerbi.embed(embedContainer, embedConfig);

Hide all but one visual header


Use this code to hide all visual headers in a report except a specific visual's header:
JavaScript

let embedConfig = {
...
settings: {
...
visualSettings: {
visualHeaders: [
{
settings: {
visible: false
}
/* No selector is listed. The API hides the headers of
all the visuals in the report. */
},
{
settings: {
visible: true
},
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: <The name of the visual> // You can
retrieve the name by using getVisuals.
}
}
]
}
}
};
...
let report = powerbi.embed(embedContainer, embedConfig);

If you'd like to make more than one header visible, you can extend this code. Set up
additional instances of IVisualHeader with the visible parameter in settings set to
true . For each visual that should have a visible header, add one IVisualHeader instance
to the list.

Limitations
You can only control the visibility of visual headers if the report that you embed is
in view mode.
You can only hide or show a visual's entire header. You can't configure the visibility
of specific items in the header menu.
When you use a selector to specify a visual's name or type, use the Page getVisuals
method to obtain the visual's name, which is a unique identifier. Don't configure
the selector with the visual's title.
If a user saves a report that you embed with the API, the visual settings that you
defined will be saved to the report. You can avoid this situation by configuring the
report with a permission level of View instead of Edit or Save .

Next steps
Configure report settings

Use selectors to control which visuals are affected

get-visuals.md
Clone a visual
Article • 02/02/2021

The Clone Visual API clones a specific visual into the active page of a Power BI report.
You can clone a visual from any page in the report into the active page. Cloning a visual
lets you make copies with different layouts or filters from the original visual.

How to clone a visual


The Power BI Client VisualDescriptor class, defines the clone method as:

TypeScript

clone(request: models.ICloneVisualRequest = {}):


Promise<ICloneVisualResponse>

In the ICloneVisualRequest interface:

IFilter describes the filters to apply to the cloned visual.


IVisualLayout defines the cloned visual's size and location.
The autoFocus property determines whether to focus on the cloned visual after
creation.

The ICloneVisualResponse interface returns the new cloned visual name or unique
identifier.

JavaScript

interface ICloneVisualRequest {
// The filters to apply to the new visual. Default: source visual filters.
filters?: IFilter[];

// The layout to apply to the new visual.


// Default: a best effort to put the new visual in an empty space on the
canvas.
layout?: IVisualLayout;

// Focus on the new visual after creation.


// If autoFocus is set to false, no scrolling will occur.
// Default: true.
autoFocus?: boolean;
}

interface ICloneVisualResponse {
// New visual name.
visualName: string;
}

To get a list of all visuals in a report, use the getVisuals method of the Page class.

Examples
The first code example clones a visual with default settings. The position and size of the
new visual represent a best effort to put a visual into an empty space on the canvas. To
specify position and size, use the second example.

JavaScript

let clonedVisual = await visual.clone();


console.log(clonedVisual.name);

The second example clones to a new visual with a specific layout, and doesn't focus on
the new visual after creation.

JavaScript

let cloneRequest = {
layout: {
height: 300,
width: 600,
x: 150,
y: 250
},
autoFocus: false
};

let clonedVisual = await visual.clone(cloneRequest);


console.log(clonedVisual.name);

The third code example clones to a new visual with a specific layout and new filters.

JavaScript

const basicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Store",
column: "Count"
},
operator: "In",
values: [1, 2, 3, 4],
filterType: models.FilterType.BasicFilter
};

let cloneRequest = {
layout: { x: 150, y: 250 },
filters: [basicFilter]
};

let clonedVisual = await visual.clone(cloneRequest);


console.log(clonedVisual.name);

Limitations
You can clone a visual only if the report is fully rendered, so wait on the rendered event
before you call the Clone Visual API.

Next steps
Get pages and visuals

Control report filters

Personalize a report layout

Report authoring overview


Override default error messages
Article • 01/24/2021

You can hide the Power BI embedded analytics default error messages on reports, and
instead show custom error messages that fit your app design.

For example, you could replace this default error dialog:

With this custom error dialog:

How to override errors


To use custom error messages, first hide the default Power BI embedded analytics error
messages by setting the hideErrors property to true in the Power BI embedded
analytics configuration object. This configuration for powerbi.embed(element, config)
also includes other settings and options. For more information, see Configure report
settings.

JavaScript

let config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: embedReportId,
permissions: permissions,
settings: {
hideErrors: true
}
};

When you hide the default error messages, error dialogs and messages no longer
appear if errors occur. For your app's users to get consistent and helpful responses
when errors occur, you're responsible for handling error events.

To handle errors, first get the errors by listening on the error event:

JavaScript

report.off("error");
report.on("error", function(event) {
// Handle errors
});

The level property on the IError interface lets you specify which types of errors to
handle:

TypeScript

interface IError {
message: string;
detailedMessage?: string;
errorCode?: string;
level?: TraceType;
technicalDetails?: ITechnicalDetails;
}

enum TraceType {
Information = 0,
Verbose = 1,
Warning = 2,
Error = 3,
ExpectedError = 4,
UnexpectedError = 5,
Fatal = 6,
}

Fatal errors are the most serious error type, because they make the report

unresponsive. Make sure to handle Fatal errors to prevent end users from facing
unresponsive or broken reports with no error messaging.
Example
The following code example demonstrates how you can override errors by listening to
and handling error events. The example doesn't show the newAccessToken or
error.detailedMessage functions. Implement your own functions where indicated.

JavaScript

// Embed the loadConfiguration that hides the default errors.


let config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: embedReportId,
permissions: permissions,
settings: {
hideErrors: true
}
};

// Get a reference to the embedded report HTML element.


let embedContainer = $('#embedContainer')[0];

// Embed the report and display it within the div container.


let report = powerbi.embed(embedContainer, config);

// Set report.off to remove any pre-existing error event handler.


report.off("error");

// Set report.on to add the new error event handler.


report.on("error", function(event) {
const error = event.detail;

// If the error level isn't Fatal, log the error and continue.
if (error.level !== models.TraceType.Fatal) {
console.error(error);
return;
}

// If the Fatal error is TokenExpired, refresh the token.


if (error.message === models.CommonErrorCode.TokenExpired) {
// Implement your own function here.
let newAccessToken = refreshToken();

// Set the new access token.


report.setAccessToken(newAccessToken);
} else {
// If the error isn't TokenExpired, show the custom
// dialog with detailed error message in the iframe.
// Implement your own function here.
showError(error.detailedMessage);
}
});

Next steps
Configure report settings

Troubleshoot your embedded application

Use the Power BI correlation ID


Use selectors to control which visuals
are effected
Article • 01/24/2021

Some features allow you to use selectors to control which visuals are effected. The
selector is optional, and when it doesn't appear, the settings are applicable for all the
visuals in the report.

Supported features
Selectors can be used in the following features:

Modify menu commands


Hide or display visual headers
Slicers on report load

Selector types

Visual name
Apply the settings only for the specified visual.

JavaScript

selector: {
$schema: "http://powerbi.com/product/schema#visualSelector",
visualName: <a visual name> // You can retrieve the name using
`getVisuals`
}

In order to find a visual name, you can use the getVisuals() API on a page and get the
visual's name property. Visual name is a unique identifier.

Visual type
Apply the settings to all the visuals from the specified type.

JavaScript
selector: {
$schema: "http://powerbi.com/product/schema#visualTypeSelector",
visualType: <a visual type> // You can retrieve the type using
`getVisuals`
}

In order to find a visual type, you can use the getVisuals() API on a page and get the
visual's type property.

Slicer target
Apply the slicer state only for the slicers with the specified target.

JavaScript

selector: {
$schema: "http://powerbi.com/product/schema#slicerTargetSelector",
target: <target data field>
}

Examples

Visual header settings


Hide all visual headers in the report.

JavaScript

let config = {

settings: {

visualSettings: {
visualHeaders: [
{
settings: {
visible: false
}
/* No selector - Hide visual header for all the
visuals in the report */
}
]
}
}
};
Hide a visual header for a specific visual using the visual selector.

JavaScript

let config = {

settings: {

visualSettings: {
visualHeaders: [
{
settings: {
visible: false
}
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: "VisualContainer1",
}
}
]
}
}
};

Menu commands settings


Both menu command extensions and built-in commands display support selectors.

Adding an extension command to a specific visual options menu.

JavaScript

let config = {
...
settings: {
...

// Adding the extension command to the options menu


extensions: [
{
command: {
name: "campaign",
title: "Start campaign",
icon: base64Icon,
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: tableVisualName
},
extend: {
visualOptionsMenu: {
title: "Start campaign",
menuLocation: models.MenuLocation.Top,
}
}
}
},
],
}
}

Hide a few built-in commands for all visuals with table type.

JavaScript

let tableSelector = {
$schema: "http://powerbi.com/product/schema#visualTypeSelector",
visualType: 'table'
};

let config = {
...
settings: {
...
// Hiding built-in commands on the options menu
commands: [
{
spotlight: {
selector: tableSelector,
displayOption: models.CommandDisplayOption.Hidden,
},
exportData: {
selector: tableSelector,
displayOption: models.CommandDisplayOption.Hidden,
},
seeData: {
selector: tableSelector,
displayOption: models.CommandDisplayOption.Hidden,
},
}
]
},
};

Slicers on load

7 Note

Slicers on load do not support visual type selector


Set a specific slicer by name

JavaScript

let slicers = [
{
selector: {
$schema:
"http://powerbi.com/product/schema#visualSelector",
visualName: "d1feb8891635af3b335a"
},
state: {
filters: [
{
$schema:"http://powerbi.com/product/schema#advanced",
target: {
table: "Store",
column: "StoreNumber"
},
filterType: models.FilterType.AdvancedFilter,
logicalOperator: "And",
conditions: [
{ operator: "GreaterThanOrEqual", value: 37 },
{ operator: "LessThanOrEqual", value: 576 }]
}]
}
}
];

embedConfig = {
slicers: slicers,
...
};

Set slicers by target

JavaScript

// We want to slice all slicers with "StoreNumber" column target


let target = {
table: "Store",
column: "StoreNumber"
};

let slicers = [
{
selector: {
$schema:
"http://powerbi.com/product/schema#slicerTargetSelector",
target: target
},
state: {
filters: [
{
$schema:"http://powerbi.com/product/schema#advanced",
target: target,
filterType: models.FilterType.AdvancedFilter,
logicalOperator: "And",
conditions: [
{operator: "GreaterThanOrEqual", value: 37 },
{operator: "LessThanOrEqual", value: 576 }]
}]
}
}
];

embedConfig = {
slicers: slicers,
...
};

Next steps
Modify menu commands for a report visual

Hide or show a visual header

Control report slicers


Use targets to select which data field to
act on
Article • 05/09/2022

In Power BI edit mode, the Fields pane shows all the tables on the model with all their
data fields. You can sort, filter, or slice data in the data fields to affect how the data
shows in reports, pages, or visuals.

A Power BI embedded analytics filter, slicer, or sort requires a target object that specifies
which data field to act on. Use ITarget to provide the target data field when you:

Construct a filter with the IFilter interface


Set a slicer on load
Sort a visual
Add a data field to a visualization

Target types
A data field can be a column, a hierarchy level, an aggregated column or hierarchy level,
or a calculated measure. Target types for the ITarget interface include:

IColumnTarget
IHierarchyLevelTarget

IMeasureTarget

IColumnAggrTarget
IHierarchyLevelAggrTarget

Column
Use IColumnTarget to target the specified column in a table:

JavaScript

target: {
$schema: "http://powerbi.com/product/schema#column",
table: "<table name>",
column: "<column name>"
}

Hierarchy level
Use IHierarchyLevelTarget to target the specified hierarchy level within a hierarchy in a
table:

JavaScript

target: {
$schema: "http://powerbi.com/product/schema#hierarchyLevel",
table: "<table name>",
hierarchy: "<hierarchy name>",
hierarchyLevel: "<hierarchy level name>"
}

Measure
Use IMeasureTarget to target the specified measure in a table. The value of
percentOfGrandTotal is set to true if the target is bound to a visual and its values are
shown as a percent of the grand total.

JavaScript

target: {
$schema: "http://powerbi.com/product/schema#measure",
table: "<table name>",
measure: "<measure name>",
percentOfGrandTotal?: boolean
}

Aggregation functions
You can specify aggregation functions for column and hierarchy level targets. The
aggregationFunction variable is optional, and if you don't supply it, data fields use the
default Sum aggregation function. Other supported values for aggregationFunction are:

Avg

DoNotSummarize
Count

CountNonNull
Max

Median
Min

StandardDeviation

Variance
Aggregated column
Use IColumnAggrTarget to specify an aggregation function on the specified column in a
table. The value of 'percentOfGrandTotal' is set to true if the target is bound to a visual
and its values are shown as a percent of the grand total.

JavaScript

target: {
$schema: "http://powerbi.com/product/schema#columnAggr",
table: "<table name>",
column: "<column name>",
aggregationFunction: "<aggregation function>", // Optional, default is
Sum.
percentOfGrandTotal?: boolean
}

Aggregated hierarchy level


Use IHierarchyLevelAggrTarget to specify an aggregation function on the specified
hierarchy level within a hierarchy in a table. The value of 'percentOfGrandTotal' is set to
true if the target is bound to a visual and its values are shown as a percent of the grand
total.

JavaScript

target: {
$schema: "http://powerbi.com/product/schema#hierarchyLevelAggr",
table: "<table name>",
hierarchy: "<hierarchy name>",
hierarchyLevel: "<hierarchy level name>",
aggregationFunction: "<aggregation function>", // Optional, default is
Sum.
percentOfGrandTotal?: boolean
}

Examples
The following code examples use the target object to specify the data field that a filter
should act on.

Column target example


The following code example applies a basic filter with a column target to a report. The
code acts on the Region column of the Geo table so that only data in the West region
shows in the report.

JavaScript

let filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
$schema: "http://powerbi.com/product/schema#column",
table: "Geo",
column: "Region"
},
operator: "In",
values: ["West"]
};

Hierarchy level target example


The following code example applies a basic filter with a hierarchy level target to a report.
The code acts on the Month level of the OrderDate hierarchy of the Sales table so that
only data in the West region shows under that hierarchy level in the report.

JavaScript

let filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
$schema: "http://powerbi.com/product/schema#hierarchyLevel",
table: "Sales",
hierarchy: "OrderDate",
hierarchyLevel: "Month"
},
operator: "In",
values: ["West"]
};

Measure target example


The following code example applies an advanced filter with a measure target to a visual.
The code acts on the Total Category Volume measure in the SalesFact table so it only
appears when the value is not blank.

JavaScript
let filter = {
$schema: "http://powerbi.com/product/schema#advanced",
target: {
$schema: "http://powerbi.com/product/schema#measure",
table: "SalesFact",
measure: "Total Category Volume"
},
filterType: models.FilterType.AdvancedFilter,
logicalOperator: "And",
conditions: [{
operator: "IsNotBlank"
}]
}

Aggregated column target example


The following code defines a column aggregation target that is the sum of the values in
the Store column of the Sales table:

JavaScript

let columnAggregation = {
$schema: "http://powerbi.com/product/schema#columnAggr",
table: "Store",
column: "Sales",
aggregationFunction: "Sum"
};

Next steps
Control report filters

Control report slicers

Sort a visual by a target data field


Use the action bar to enhance user
experience
Article • 05/12/2021

When you embed a report for your organization, you require your application users to
sign in to Power BI to view the embedded content. Once the users sign in, they have
access to the reports they own or that you or other organization members share with
them.

Consumers of reports you embed for your organization can take advantage of self-
service capabilities like action bars, personal bookmarks, and persistent filters through
the Client APIs.

Action bar
When you embed a Power BI report for your organization, report consumers can use the
report action bar to export, share, change views, or take several other actions.

You can enable the full functionality of the action bar to let users:

Favorite the report


Use persistent filters
Use personal bookmarks

) Important
To provide full action bar functionality, you must grant users
UserState.ReadWrite.All permission for your application in Azure Active Directory
(Azure AD).

To show the action bar to your report consumers, add the bars setting to your embed
configuration, and set the actionBar visibility to true .

JavaScript

let embedConfig = {
...
settings: {
bars: {
actionBar: {
visible: true
}
}
}
};

Showing the action bar displays a vertical list of report pages, the same experience as in
Power BI service. Users can collapse the page navigation pane to give the report more
room.

Persistent filters
Persistent filters retain report consumers' filters, slicers, and other report states over
sessions. Report consumers can quickly get to their insights without repeating the same
filtering steps every time they return to the report. Users can share the same persistent
report state across Power BI service, mobile, and embed scenarios.

To enable persistent filters in embedded reports for your organization:

1. Enable persistent filters in the Power BI service or desktop report settings.

2. Make sure your app allows UserState.ReadWrite.All permissions in Azure AD.

3. Set the persistentFiltersEnabled property in the embedded loadConfiguration


settings to true :

TypeScript

let config = {
type: 'report',
...
settings: {
persistentFiltersEnabled: true
}
};

The report loads with the user's latest report state, if one exists. In the embedded report,
consumers can use the Reset to default button in the action bar to apply their persistent
filters.

For more information about persistent filters and the relevant APIs, see Persistent filters.

Personal bookmarks
In reports you embed for your organization, report consumers can create personal
bookmarks by capturing report page states, including filters, slicers, and visual states,
and giving them friendly names. Users can then quickly return to these states by
selecting the bookmarks. Personal bookmarks are available only to their creators, and
creating them doesn't require write permissions for the report.

Report consumers can use the same personal bookmarks in embedded reports and in
the Power BI service. Users can make any personal bookmark their default view, so they
see their favorite view of the report every time they open it.

To enable personal bookmarks in embedded reports for your organization:

1. Make sure your app allows UserState.ReadWrite.All permissions in Azure AD.

2. Set the personalBookmarksEnabled property in the embedded loadConfiguration


settings to true :

TypeScript

let config = {
type: 'report',
...
settings: {
personalBookmarksEnabled: true
}
};

3. Make the bookmark pane visible in the report.


You can make the bookmark pane visible in the report in two ways. The first option is to
show the report action bar, which has a Bookmarks button for users to open and close
the bookmarks pane.

The second option is to show and hide the bookmarks pane programmatically by using
the panes object in the report settings.

JavaScript

let embedConfig = {
...
settings: {
panes: {
bookmarks: {
visible: true
}
}
}
};

You can update the report settings at runtime by using the updateSettings method, see
Update report settings at runtime.

For more information about personal bookmarks, see Personal bookmarks.

Limitations
In Power BI embedded analytics, the persistent filters and personal bookmarks
features are disabled by default. These features are supported only when you
embed reports for your organization, not when you embed for your customers.
When you show the action bar, you can no longer programmatically control
whether page navigation appears as a pane on the left or as tabs across the
bottom. Changing the report pages list location is only available through the
Power BI service report settings, not through the panes object.

Personal bookmarks actions aren't supported by API. For information about report
bookmarks, see Report bookmarks.

Next steps
Enhance your users' experience with bookmarks

Enable persistent filters


Enable persistent filters
Article • 01/24/2021

In reports you embed for your organization, when the persistent filters feature is
enabled, reports retain their state, including filters, slicers, and other data view changes.
When your user opens a report, the saved user state loads into the report. Also, the user
gets the same user state in the different scenarios if persistent filters is enabled.

To reset the persistent filters in an embed scenario, you'll need to implement a button
and use the resetPersistentFilters API, or show the action bar to get the Power BI
Reset to default button on the action bar.

How to enable persistent filters


Persistent filters are disabled by default. To enable persistent filters, follow the steps in
this section.

1. Verify that persistent filters are enabled in the report settings in the Power BI
service or desktop.

2. Verify that your Azure Active Directory (Azure AD) app has
UserState.ReadWrite.All permissions.

3. Set the persistentFiltersEnabled property to true .

TypeScript

let config = {
type: 'report',
...
settings: {
persistentFiltersEnabled: true
}
};

The report is loaded with the latest user's report state, if the state exists. The user's
report state is automatically saved after 60 seconds, without any change.

7 Note

Only updates to existing filters are saved. New filters that are added by the
setFilters API won't be saved.
Persistent filters APIs

Reset persistent filters


Reset a user's filters, slicers, and other data view changes to the report's default state.

TypeScript

resetPersistentFilters(): Promise<void>

Save persistent filters


Save the user's report filters, slicers, and other data view changes.

TypeScript

savePersistentFilters(): Promise<void>

Persistent filters applied


Returns a user's filters, slicers, or other data view changes applied on the report, if they
exist. If persistent filters are disabled, this returns false.

You can use this API to determine the reset button state.

TypeScript

arePersistentFiltersApplied(): Promise<boolean>

Limitations
Persistent filters are supported only for the embed for your organization (user owns data)
solution.

Next steps
Enhance your users' experience with bookmarks

Use the action bar to enhance user experience


Control report filters

Use the action bar to enhance user experience

Control report slicers


Personal bookmarks
Article • 05/12/2021

In reports you embed for your organization, report consumers can create personal
bookmarks. Personal bookmarks are created by capturing report page states, including
filters, slicers, and visual states, and giving them friendly names. Users can then quickly
return to these states by selecting the bookmarks. Personal bookmarks are available
only to their creators, and creating them doesn't require write permissions for the
report.

7 Note

This feature is disabled by default and is supported only for the embed for your
organization (user owns data) solution.

To enable personal bookmarks in embedded reports for your organization:

1. Verify that your Azure Active Directory (Azure AD) app has the
UserState.ReadWrite.All permission.

2. Set the personalBookmarksEnabled property in the loadConfiguration settings, to


true:

JavaScript

let config = {
type: 'report',
...
settings: {
personalBookmarksEnabled: true
}
};

3. Make the bookmark pane visible in the report.

Using personal bookmarks


In order to create, apply, delete, update or rename a personal bookmark, the bookmark
pane should be visible. When enabled and the user has the right permissions, the
personal bookmarks tab will show in the bookmark pane.
You can make the bookmark pane visible in the report in two ways. The first option is to
show the report action bar, which has a Bookmarks button for users to open and close
the bookmarks pane.

The second option is to show and hide the bookmarks pane programmatically by using
the panes object in the report settings.

JavaScript

let embedConfig = {
...
settings: {
panes: {
bookmarks: {
visible: true
}
}
}
};

To update the report settings at runtime see Update report settings at runtime.

7 Note

Actions for personal bookmarks aren't supported by APIs. For report bookmarks,
see report bookmarks.

Next steps
Use the action bar to enhance user experience

Persistent filters

Enhance your users' experience with bookmarks


Report authoring overview
Article • 12/05/2022

Power BI comes with many out-of-the-box visuals. These visuals are available in the
visualization pane of both Power BI Desktop and Power BI service, and can be used to
discover meaningful insights about your data. You can develop your own Power BI
visuals, to be used by you, your organization, or the entire Power BI community. You can
also edit or customize your visuals, reports, and dashboards using Edit mode in Power
BI embedded analytics.

The visualization APIs for Power BI allow you to personalize your visuals as needed.

Your visual might be an area chart, filled map, matrix, or other visual type. After creating
a visual, you can change its type if you decide the visual doesn't convey the information
as well as you would like. For example, you can change a pie chart to a bar chart. In
addition, if your application users don't like a visual in the report, it can be removed.

After creating a visual, you can bind data to it so that you can control the data that's
displayed. You can control the visual's displayed data programmatically by using the
add and remove data fields APIs.

You can retrieve, set, or reset visuals' properties, such as the color or size of a visual's
title. There are readily available properties for out-of-the-box visuals. For custom visuals,
all the properties that were defined when the visual was created are available.

The Power BI Report Authoring library is an extension for the Power BI Client library,
and makes it easy to quickly author a Power BI report.

Limitations
Only out-of-the-box visuals, custom visuals that are installed from the marketplace, or
visuals imported from a file can be created using the APIs. createVisual or changeType
fail if the target visual type is not installed.

Next steps
Create a visual

Remove a visual
Change the visual type

Configure data fields

Format visual properties


Create a visual
Article • 01/25/2021

This API provides a way to create a new visual on a report page.

How to create a visual and bind it to data


Create an empty visual of a specific type, and then bind the visual to data fields. For a
list of visual types, see out-of-the-box visual types.

7 Note

Visuals that are not installed in the visualization pane cannot be added to a report.
This is true for both custom visuals that are not installed and out-of-the-box visuals
that have been uninstalled.

1. Configure the visual you want to create by using the following parameters:

Visual type: The type of visual you want to create, such as a barChart .
Layout (optional): The layout to be applied to the new visual.
autoFocus (optional): Choose whether or not the page automatically scrolls
to the newly created visual (set to 'True' by default).

2. Use the following method to create your visual:

JavaScript

createVisual(visualType: string, layout?: models.IVisualLayout,


autoFocus?: boolean): Promise<models.ICreateVisualResponse>

The returned value contains an object that represents the newly created visual. You can
use the visual data binding and visual properties APIs to edit the visual according to
your needs.

For example:

JavaScript

let createVisualResponse = await page.createVisual('areaChart');


let visual = createVisualResponse.visual;
Code examples
The following code examples show how to create visuals with different parameters.

7 Note

For information about creating custom layouts, see Visual layout.

Create an area chart visual with a custom layout and no focus.

JavaScript

const customLayout = {
x: 20,
y: 35,
width: 1600,
height: 1200
}

let createVisualResponse = await page.createVisual('areaChart',


customLayout, false /* autoFocus */);

Create an area chart with a default layout.

JavaScript

let createVisualResponse = await page.createVisual('areaChart');

Available out-of-the-box visual types


actionButton

areaChart

barChart

basicShape

card

clusteredBarChart

clusteredColumnChart

columnChart
debugVisual

Decomposition Tree

donutChart

esriVisual

filledMap

funnel

gauge

hundredPercentStackedBarChart

hundredPercentStackedColumnChart

image

keyDriversVisual

kpi

lineChart

lineClusteredColumnComboChart

lineStackedColumnComboChart

map

multiRowCard

pieChart

pivotTable

PowerApps

pythonVisual

qnaVisual

ribbonChart

scatterChart

scriptVisual
shapeMap

slicer

stackedAreaChart

tableEx

textbox

treemap

waterfallChart

Limitations
Visual creation APIs are only available after the report is rendered. Listen on the report
rendered event and trigger visual authoring APIs only after it is called. See Event

handling for more information.

Next steps
Change the visual type

Configure data fields

Format visual properties


Get the capabilities of a visual
Article • 01/24/2021

A visual's capabilities are data roles that the visualization type can accept. For example,
this image shows the visual capabilities of a clustered column chart in the Visualization
pane.

Get a visual's capabilities to determine what data is displayed at the report or visual
level. Both of the APIs used to get capabilities return IVisualCapabilities .

TypeScript

export interface IVisualCapabilities {


dataRoles?: IVisualDataRole[];
}
dataRoles define the roles a visual expects and how those roles should be populated.

This data is required to use the following visual data binding APIs. Each of these APIs
expects the target dataRole name as the input parameter.

dataRoles are represented by the IVisualDataRole interface:

TypeScript

interface IVisualDataRole {
name: string;
kind: VisualDataRoleKind;
kindPreference?: VisualDataRoleKindPreference;
displayName?: string;
description?: string;
}

name - Unique identifier for VisualDataRole .


kind - Indicates the kind of role for the visual data.
kindPreference - Indicates the visual preference on what kind of role to use.
displayName - The display name of the role.
description - The text for the tooltip.

You can retrieve visual metadata for both out-of-the-box and custom visuals installed on
the report.

How to get visual capabilities at the report


level
Use the getVisualCapabilities API to find the the visual data that displays at the report
level.

TypeScript

getVisualCapabilities(visualType: string):
Promise<models.IVisualCapabilities>

Example
Below is a code example for finding the capabilities in a bar chart visual at the report
level.

JavaScript
let capabilities = await report.getVisualCapabilities('barChart');

How to get visual capabilities at the visual level


Use the getCapabilities API to determine what data displays at the visual level.

TypeScript

getCapabilities(): Promise<models.IVisualCapabilities>

Example
Below is a code example for finding the capabilities in a visual at the visual level.

JavaScript

let capabilities = await visual.getCapabilities();

For instance, getting the capabilities for a clusteredColumnChart returns the following:

JSON

{
"dataRoles": [
{
"name": "Category",
"displayName": "Axis",
"description": "Fields to place on the horizontal or vertical
axis",
"kind": 0
},
{
"name": "Series",
"displayName": "Legend",
"description": "The categorical field to show for color",
"kind": 0
},
{
"name": "Y",
"displayName": "Values",
"description": "The numeric amounts to plot",
"kind": 1
},
{
"name": "Rows",
"displayName": "Small multiples",
"description": "Split your visual into multiple, smaller visuals
based on your selected fields",
"kind": 0
},
{
"name": "Tooltips",
"displayName": "Tooltips",
"description": "Add additional data fields that people can see
in the tooltip when they hover on part of this visualization.",
"kind": 1
}
]
}

Next steps
Get pages and visuals

Configure data fields

Modify menu commands for a report visual

Hide or show a visual header


Configure data fields
Article • 01/25/2021

When you create a visualization, the visual is rendered according to the assigned data
fields. This article shows how to use Power BI report authoring APIs to interact with data
fields and assign them to data roles. To determine what data roles a visual has, use the
getCapabilities method.

Add a data field


To add a data field to a visual data role, call the addDataField method of the visual.

TypeScript

addDataField(dataRole: string, dataField: models.IBaseTarget, index?:


number): Promise<models.IError>

This method has the following variables:

dataRole - The name of the data role to which the data field should be assigned.
The dataRole parameter is equivalent to the data role name property. To retrieve
the available data roles and names, use the getCapabilities method.
dataField - The data field to add to the data role. The data field is a target object,
which can be a column, column with aggregation, measure, hierarchy, or hierarchy
with aggregation. For more information about targets, see Use targets to select
which data field to act on.
index (optional) - The index at which the data field should be added. The default
behavior is for the field to be added last.

For example:

JavaScript

const dataField = {
$schema: "http://powerbi.com/product/schema#column",
table: "Store",
column: "Name"
};

await visual.addDataField('Category', dataField);


Get data fields
To get a list of the data fields that are defined in a data role, call the getDataFields
method of the visual.

TypeScript

getDataFields(dataRole: string): Promise<models.IBaseTarget>

This method has the dataRole variable, which is the name of the data role from which to
retrieve the data fields.

For example:

JavaScript

let dataField = await visual.getDataFields('Category');

Remove data fields


To remove a data field that's applied on a data role, call the removeDataField method of
the visual.

TypeScript

removeDataField(dataRole: string, index: number): Promise<models.IError>

This method has the following parameters:

dataRole - The name of the target data role to which the data field is associated.
index - The index of the data field to delete.

For example:

JavaScript

await visual.removeDataField('Category', 2);

To get the index of the data field, you can use the index of the target in the
getDataFields results array.
Next steps
Embed a report visual

Create a visual

Get the capabilities of a visual


Format visual properties
Article • 01/25/2021

When you're editing a report in Power BI, you can customize each visual in the report by
using the Format option in the Visualizations pane. You can customize many elements
of each visualization, such as title, legend, background and tooltip. With Power BI report
authoring APIs you can retrieve, set, or reset visual properties programmatically, without
the need of Power BI Edit mode.

To format a visual using the visual properties APIs, you need to get the visual you would
like to format. To get a list of all visuals in a report, use the getVisuals method of the
Page class.

Selecting the format object and property


To select the property you would like to retrieve, set or reset, you need to define an
IVisualPropertySelector instance which includes an objectName and a propertyName .

JavaScript

export interface IVisualPropertySelector {


objectName: string;
propertyName: string;
}

objectName: the name of the object (for example: "title").


propertyName: the name of the property within the object (for example:
"titleText").

Available properties for out-of-the-box visuals


Out-of-the-box visuals are Power BI visuals that appear in the Visualization pane by
default.

Object name Property name Type

tooltip

visible Boolean

valueColor Hex color, IThemeColorProperty


Object name Property name Type

labelColor Hex color, IThemeColorProperty

textSize Number

fontFamily String

backgroundColor Hex color, IThemeColorProperty

transparency Number

background

visible Boolean

color Hex color, IThemeColorProperty

transparency Number

visualHeader

visible Boolean

backgroundColor Hex color, IThemeColorProperty

border Hex color, IThemeColorProperty

transparency Number

iconColor Hex color, IThemeColorProperty

border

visible Boolean

color Hex color, IThemeColorProperty

radius Number

lockAspect

enabled Boolean

title

visible Boolean

alignment String (TextAlignment)

fontColor Hex color, IThemeColorProperty

textSize Number
Object name Property name Type

fontFamily String

backgroundColor Hex color, IThemeColorProperty

titleText String

legend

visible Boolean

position String (LegendPosition)

dataLabels

visible Boolean

categoryAxis

visible Boolean

valueAxis

visible Boolean

Available Properties for custom visuals


Custom visual creators define their properties, therefore, to find the objectName and
propertyName , you should check the custom visual source code. Custom visuals code is

open sourced, and their repositories can be found on GitHub.

For example: looking at the custom visual Mekko Chart, you can find the open source
repo here . In the src/visual.ts file, you can see the defined Properties .

The Mekko Chart custom visual's defined properties are listed below.

7 Note

This list was copied from the Mekko Chart custom visual's source code in January
2021.

TypeScript

public static Properties: MekkoChartProperties = <MekkoChartProperties>{


dataPoint: {
defaultColor: { objectName: "dataPoint", propertyName:
"defaultColor" },
fill: { objectName: "dataPoint", propertyName: "fill" },
showAllDataPoints: { objectName: "dataPoint", propertyName:
"showAllDataPoints" },
categoryGradient: { objectName: "dataPoint", propertyName:
"categoryGradient" },
colorGradientEndColor: { objectName: "dataPoint", propertyName:
"colorGradientEndColor" },
colorDistribution: { objectName: "dataPoint", propertyName:
"colorDistribution" }
},
columnBorder: {
show: { objectName: "columnBorder", propertyName: "show", },
color: { objectName: "columnBorder", propertyName: "color" },
width: { objectName: "columnBorder", propertyName: "width" }
},
sortSeries: {
enabled: { objectName: "sortSeries", propertyName: "enabled", },
direction: { objectName: "sortSeries", propertyName: "direction" },
displayPercents: { objectName: "sortSeries", propertyName:
"displayPercents" }
},
sortLegend: {
enabled: { objectName: "sortLegend", propertyName: "enabled", },
direction: { objectName: "sortLegend", propertyName: "direction" },
groupByCategory: { objectName: "sortLegend", propertyName:
"groupByCategory" },
groupByCategoryDirection: { objectName: "sortLegend", propertyName:
"groupByCategoryDirection" }
},
xAxisLabels: {
enableRotataion: { objectName: "xAxisLabels", propertyName:
"enableRotataion", },
},
categoryColors: {
color: { objectName: "categoryColors", propertyName: "color" },
}
};

7 Note

The dataPoint object is not supported.

Defining the property value


The property value is represented by an IVisualPropertyValue object.

JavaScript
export interface IVisualPropertyValue {
schema?: string;
value: any;
}

schema - Defines the type of the value. There are two schemas available:

Property schema: "http://powerbi.com/product/schema#property" used to


define a property.

Default schema: "http://powerbi.com/product/schema#default" used to define a


default value.

value - The value that you want to assign to the property.

Property value types


This section lists the property value types that you can configure.

Color property value


A color property value can be either a hex color (string), for example, #0000FF for the
color blue, or a IThemeColorProperty to set a report theme color.

JavaScript

interface IThemeColorProperty {
id: number;
shade: number;
}

id - The id of the theme color


shade - Defines the percent of the color shade, the values can be from -1 to 1.

For example, to define Theme color 2, 50% darker, as seen below, the
IThemeColorProperty object should be defined as follows:

JavaScript

let themeColorProperty = {
id: 2,
shade: -0.5
};
Text alignment property value
Defines the text alignment

JavaScript

const TextAlignment = {
Left: 'left',
Center: 'center',
Right: 'right',
};

Legend position property value


Defines the legend position on the visual
JavaScript

const LegendPosition = {
Top: 'Top',
Bottom: 'Bottom',
Right: 'Right',
Left: 'Left',
TopCenter: 'TopCenter',
BottomCenter: 'BottomCenter',
RightCenter: 'RightCenter',
LeftCenter: 'LeftCenter',
};

Default property value

A value that is used to define the property default value. For example, you can set the
title to the auto generated title of the visual.

JavaScript

interface IDefaultProperty {
}

If a property was not changed (using either the UI or the API), its value is defined as
IDefaultProperty , both on the getProperty and the setProperty methods.

Default property value should be defined as follows:

JavaScript

const defaultValue = {
schema: "http://powerbi.com/product/schema#default",
value: {}
};

Properties APIs
This section lists the APIs that are used to format visual properties.

Retrieving a property
Retrieve a property value of a visual according to the property selector.

TypeScript
getProperty(selector: IVisualPropertySelector):
Promise<IVisualPropertyValue>

For example:

JavaScript

const selector = { ... };

let propertyValue = await visual.getProperty(selector);

Setting a property
Set a property value to a visual according to the property selector.

TypeScript

setProperty(selector: IVisualPropertySelector, value: IVisualPropertyValue):


Promise<void>

For example:

JavaScript

const selector = { ... };


const propertyValue = { ... };

await visual.setProperty(selector, propertyValue);

Resetting a property
Reset a property value of a visual according to the property selector, this will return the
property to its default value, for example, you can set the title to the auto generated
title of the visual.

TypeScript

resetProperty(selector: IVisualPropertySelector): Promise<void>

For example:

JavaScript
const selector = { ... };

await visual.resetProperty(selector);

Full example
Below you can see an example of aligning to the center the title of the visual with the
name VisualContainer1 (unique identifer).

JavaScript

let pages = await report.getPages()

// Retrieve the active page.


let activePage = pages.find(function (page) {
return page.isActive
});

let visuals = await activePage.getVisuals();

// Retrieve the wanted visual. (replace "VisualContainer1" with the


requested visual name)
let visual = visuals.find(function (visual) {
return visual.name === "VisualContainer1";
});

// Build a selector for title alignment


const selector = {
objectName: "title",
propertyName: "alignment"
};

// Build the property value


const propertyValue = {
schema: "http://powerbi.com/product/schema#property",
value: models.TextAlignment.Center
};

await visual.setProperty(selector, propertyValue);

Next steps
Report authoring overview

Add, delete or rename a report page


Change the visual type
Article • 01/24/2021

You can change the type of an existing visual in a Power BI report, such as changing a
bar chart into a pie chart. See a list of available out-of-the-box visual types.

How to change an existing visual type using


the API
Use the changeType method and specify the desired type.

JavaScript

changeType(visualType: string): Promise<void>

Code example
The following code example shows how to change an existing visual type to a pieChart
type.

JavaScript

await visual.changeType('pieChart');

Limitations
changeType will fail if the target visual type is not installed.
Different visual types have different data binding rules. If any data fields were
applied to a visual and changeType is used, then the data fields might be mapped
to a different dataRole if such mapping is defined on the visual type metadata. If
no such mapping exists between the visual types, changeType fails. See Visual data
binding to learn more.

Next steps
Create a visual
Configure data fields

Format visual properties


Remove a visual
Article • 01/24/2021

This API provides a way to remove a visual from a report page programmatically.

7 Note

When making changes to a report, make sure to recapture any affected bookmarks.

How to remove a visual from a report page


Remove a visual from a report page by using the deleteVisual method. visualName is a
unique identifier that can be retrieved from the created visual response or by using the
GetVisuals API.

JavaScript

deleteVisual(visualName: string): Promise<void>

Code examples
JavaScript

await page.deleteVisual("8d0e01e7a860c2e5706d");

Next steps
Change the visual type

Configure data fields

Format visual properties


Add, delete or rename a report page
Article • 01/25/2021

You can use page operation APIs to add or delete a page from a report during a Power
BI embedded analytics session.

Add a page
To add a new page to the current report, use the addPage method of the Power BI Client
Report class:

TypeScript

addPage(displayName?: string): Promise<Page>

displayName sets the display name for the new page. If not specified, the display
name is set to Page#<NUM> .
The function returns a Page instance of the new page.

For example, add a page with the display name Sales to the current report:

TypeScript

let newPage = await report.addPage("Sales");

Delete a page
To delete a page from a report, you can use the deletePage method of the Report class,
or the delete method of the Page class, depending on context. The return value
resolves after the page is deleted.

Delete a page using a Report instance


To delete a page from a report by using a Report instance:

TypeScript

deletePage(pageName: string): Promise<void>


pageName is a unique identifier that's different from the displayName . You can use the

report.getPages API to get the pageName .

For example, delete a page with the name ReportSection123 :

TypeScript

await report.deletePage("ReportSection123");

ReportSection123 is the pageName the getPages API returned for the Sales page

Delete a page using a Page instance


To delete a page from a report by using a Page instance:

TypeScript

delete(): Promise<void>

For example:

TypeScript

newPage.delete();

Rename a page
To rename a page on a report, you can use the renamePage method of the Report class,
or the setDisplayName method of the Page class, depending on context. The return
value resolves after the page is renamed.

Rename a page using a Report instance


To rename a page from a report by using the Report instance:

TypeScript

renamePage(pageName: string, displayName: string): Promise<void>

pageName is a unique identifier that's different from the displayName . You can use the

report.getPages API to get the pageName .


For example, rename the page with the name ReportSection123 to New Sales:

TypeScript

report.renamePage("ReportSection123", "New Sales");

ReportSection123 is the pageName the getPages API returned for the Sales page.

Rename a page using a Page instance


To rename a page from a report by using the Page instance:

TypeScript

setDisplayName(displayName: string): Promise<void>

For example, rename the page to New Sales:

TypeScript

newPage.setDisplayName("New Sales");

Limitations
Page operations work only after the report is loaded.

Next steps
Get pages and visuals

Page navigation

Report authoring overview

Create, edit, and save an embedded report


Power BI embedded analytics
documentation
Learn to use the two Power BI embedded analytics solutions, Power BI Embedded, and
embedding using Power BI Premium.

Get started

b GET STARTED

What is Power BI embedded analytics?

Frequently asked questions

h WHAT'S NEW

Multitenancy solutions

i REFERENCE

Power BI Developer in a Day course

Client APIs

h WHAT'S NEW

Power BI embedded analytics Client APIs

Embed reports or dashboards

g TUTORIAL

Tutorial: Embed Power BI content into an application for your customers

Tutorial: Embed a Power BI report in an application for your organization

c HOW-TO GUIDE

Embed Power BI paginated reports


Embed using a service principal

i REFERENCE

Embedding setup tool

Developer samples and scripts

Plan for production

Y ARCHITECTURE

Capacity and SKUs

Capacity planning

p CONCEPT

Performance best practices

Power BI permissions

Questions and answers

Troubleshoot your embedded application

References and resources

h WHAT'S NEW

Playground

i REFERENCE

Power BI REST APIs

Developer center

Power BI libraries

Power BI embedded analytics Client APIs

Learn
d TRAINING

Power BI Dev Camp

i REFERENCE

Dev Camp website

You might also like