Javascript API Overview Powerbi
Javascript API Overview Powerbi
Get started
e OVERVIEW
b GET STARTED
Embed a report
Embed a dashboard
Client APIs
p CONCEPT
c HOW-TO GUIDE
i REFERENCE
Stack Overflow
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.
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.
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.
Also known as app owns data Also known as user owns data
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
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.
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.
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.
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.
The documentation set also includes articles that explain how to use the APIs, alongside
code examples. The articles are divided into the following sections:
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 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.
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
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.
JavaScript
let embedConfiguration = {
type: 'report',
id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Aad,
accessToken: 'e4...rf'
};
JavaScript
let embedConfiguration = {
type: 'report',
id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Embed,
accessToken: 'h4...rf'
};
Next steps
Tutorial: Embed Power BI content using a sample embed for your customers
application
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.
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.
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.
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.
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,
}
}
}
},
...
}
}
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") {
JavaScript
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
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.
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.
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
}
};
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.
For more information about report themes, see Use report themes in Power BI Desktop.
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.
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.
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.
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.
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
// 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;
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:
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.
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.
JavaScript
JavaScript
// Open the bookmarks list div and show the applied bookmark
bookmarksList.addClass("show position");
bookmarksDropdown.addClass(displayClass);
...
JavaScript
function onBookmarkClicked(element) {
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
The embedded report has a Create quick visual button that users can select to create
new visuals based on the data.
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.
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.
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.
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
// Update state
visualCreatorShowcaseState.newVisual = newVisual.visual;
visualCreatorShowcaseState.visualType = newVisual.visual.type;
const visual = newVisual.visual;
const newVisualType = 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
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.
JavaScript
// Open the modal and set the fields, properties and title for the
visual
openModalAndFillState(event.detail);
});
baseReportState.report.on("buttonClicked", function () {
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.
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;
}
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
permissions - Operations that you grant to users for the embedded report. These
values are available:
Read - Users can view 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).
type - The kind of content that you're embedding. Use 'report' for a Power BI
report.
bookmark
contrastMode
filters
pageName
settings
slicers
theme
viewMode
TypeScript
interface IReportCreateConfiguration {
accessToken: string;
datasetId: string;
embedUrl?: string;
settings?: models.IEmbedSettings;
theme?: IReportTheme;
tokenType?: models.TokenType;
type: string;
}
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];
Next steps
Embed a report visual
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.
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.
Example
TypeScript
interface IQuickCreateConfiguration {
type?: "quickCreate";
accessToken: string;
settings?: ISettings;
tokenType?: TokenType;
theme?: IReportTheme;
embedUrl?: string;
datasetCreateConfig: IDatasetCreateConfiguration;
reportCreationMode?: ReportCreationMode;
eventHooks?: EventHooks;
}
Content.Create
Dataset.ReadWrite.All
Report.Read.All
Workspace.Read.All
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
Example
TypeScript
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.
TypeScript
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
}
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
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
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.
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
Example
TypeScript
Next Steps
Understanding the different embedding solutions
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.
TypeScript
interface IVisualLoadConfiguration {
accessToken?: string;
embedUrl?: string;
id?: string;
pageName: string;
tokenType?: models.TokenType;
type: string;
visualName: string;
}
accessToken - The token that gives you access to the Power BI data that you're
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).
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
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];
JavaScript
Next steps
Embed a report
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?.
TypeScript
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
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.
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.
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).
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];
Make sure you include all DatasetIds used for binding in the multi-resource embed
token.
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.
TypeScript
interface ILoadQnaConfiguration {
accessToken: string;
datasetIds: string[];
embedUrl: string;
question?: string;
tokenType?: models.TokenType;
type: string;
viewMode?: models.QnaMode;
}
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
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.
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.
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];
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
This example shows how to use this method to change the displayed question:
JavaScript
For instance, you can record the questions that users enter. You might use these
questions later, for AI or telemetry purposes.
JavaScript
qna.on("visualRendered", function(event) {
...
});
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
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 .
TypeScript
interface IDashboardLoadConfiguration {
accessToken: string;
embedUrl?: string;
id: string;
pageView?: models.PageView
tokenType?: models.TokenType;
type: string;
}
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
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
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).
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];
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
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.
TypeScript
interface ITileLoadConfiguration {
accessToken: string;
dashboardId: string;
embedUrl: string;
id: string;
tokenType?: models.TokenType;
type: string;
}
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).
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 dashboard
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
For detailed usage information, see the Power BI React readme file.
To import React into your web app, add the imports listed below.
JavaScript
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.
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.
Bash
Next steps
Embed a report
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
For detailed usage information, see the Power BI Angular readme file.
To import Angular into your web app, add the imports listed below.
JavaScript
@NgModule({
imports: [
...
...
PowerBIEmbedModule
],
exports: ...,
declarations: ...
})
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.
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.
Bash
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
For detailed usage information, see the Power BI Vue readme file.
To import Vue into your web app, add the imports listed below.
JavaScript
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.
eventHandlers - A map object for event names and their handlers. See How to
handle events for more information.
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:
Bash
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.
Python
Python
If you are using Jupyter Notebook 5.2 or earlier, you may also need to enable the
nbextension:
Python
Embed a report
This example shows how to embed a Power BI report using the package.
Python
Python
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
pandas
matplotlib
Python
cd demo
jupyter notebook
3. Run demo.ipynb .
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.
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.
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();
});
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
JavaScript
id: string
title?: string
type?: string (type of button)
bookmark?: string
commandTriggered
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
dataSelected
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
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
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.
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
Page navigation
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.
JavaScript
await report.setAccessToken(newAccessToken);
JavaScript
// 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)
}
}
);
7 Note
JavaScript
let config = {
type: 'report',
tokenType: models.TokenType.Aad,
accessToken: “eyJ0 …”,
embedUrl: “https: …”,
eventHooks: {
accessTokenProvider: getNewAccessToken
}
};
Next steps
Understanding the different embedding solutions
Use bootstrap for better performance
Article • 05/21/2023
available.
powerbi.bootstrap allows you to start embedding before all the required parameters are
available. The bootstrap API prepares and initializes the iframe.
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;
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.
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.
JavaScript
powerbi.bootstrap(
reportContainerDivElement,
{
type: 'report',
}
);
JavaScript
powerbi.bootstrap(
reportContainerDivElement,
{
type: 'dashboard',
embedUrl: "https://app.powerbi.com/dashboardEmbed?
dashboardId=06e3ba63-47ea-4579-b010-
fdb5484b325a&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6mLndpbmRvd3MubmV0In0="
}
);
JavaScript
powerbi.bootstrap(
reportContainerDivElement,
{
type: 'report',
hostname: "https://app.powerbi.com"
}
);
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) .
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.
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
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.
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();
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
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 .
JavaScript
For more information about handling events, see How to handle events.
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).
JavaScript
JavaScript
try {
...
If you're not using the async / await pattern, you can use the catch function to catch
potential error. For example:
JavaScript
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.
TypeScript
getCorrelationId(): Promise<string>
Example
TypeScript
This example shows how to get the correlation ID when an error occurs.
TypeScript
Limitations
The getCorrelationId function only works after the report is loaded.
Next steps
How to handle events
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.
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
JavaScript
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
JavaScript
JavaScript
To learn more about the tabindex attribute, see the MDN Web Docs tabindex article.
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
};
JavaScript
enum ContrastMode {
None = 0,
HighContrast1 = 1,
HighContrast2 = 2,
HighContrastBlack = 3,
HighContrastWhite = 4
}
) 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.
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
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
JavaScript
JavaScript
element.on('preloaded', function () {
...
});
Next steps
How to handle events
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.
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:
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
JavaScript
let embedConfig = {
...
settings: {
navContentPaneEnabled: false
}
};
7 Note
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
}
}
}
};
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.
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.
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).
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
}
};
TypeScript
enum HyperlinkClickBehavior {
Navigate,
NavigateAndRaiseEvent,
RaiseEvent
}
NavigateAndRaiseEvent - The URL will be loaded into a new browsing context, and
dataHyperlinkClicked event.
JavaScript
let embedConfig = {
...
settings: {
hyperlinkClickBehavior: HyperlinkClickBehavior.RaiseEvent
}
};
JavaScript
report.on('dataHyperlinkClicked', () => {
...
});
For more information about handling events, see How to handle events.
JavaScript
let embedConfig = {
...
settings: {
visualRenderedEvents: true
}
};
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.
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
interface IApplyBookmarkStateRequest {
state: string;
}
interface IApplyBookmarkByNameRequest {
name: string;
}
JavaScript
let embedConfig = {
...
bookmark: {
name: "Bookmark4f76333c3ea205286501"
}
};
JavaScript
let embedConfig = {
...
bookmark: {
state: bookmarkState
}
};
TypeScript
enum ContrastMode {
None = 0,
HighContrast1 = 1,
HighContrast2 = 2,
HighContrastBlack = 3,
HighContrastWhite = 4
}
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.
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.
If the content is in edit mode, and you'd like to switch to view mode, use this JavaScript
code:
JavaScript
...
If the content is in view mode, and you'd like to switch to edit mode, use this JavaScript
code:
JavaScript
...
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.
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.
TypeScript
report.updateSettings(settings: ISettings):
Promise<IHttpPostMessageResponse<void>>
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
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.
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
All - Users can create, view, edit, save, and save a copy of the report.
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.
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
Copy - Users can save a copy of the report by using Save As.
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");
JavaScript
report.switchMode("edit");
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.
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();
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);
Call report.isSaved to make sure the report is saved. This method can help prevent
losing unsaved changes.
JavaScript
The saveAsTriggered event is raised when a user clicks on Save As in the UI. Use this
information to show your custom dialog.
JavaScript
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);
JavaScript
Next steps
Bind datasets dynamically to a report
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.
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"
}]
}
};
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.
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.
MobilePortrait - Optimized for portrait view. This is the mobile layout you created
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
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);
TypeScript
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.
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.
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.
JavaScript
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.
JavaScript
let 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.
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
...
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
Next steps
Enhance your users' experience with bookmarks
Apply report themes in Power BI
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.
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
JavaScript
Code examples
JavaScript
console.log(log);
Output
Report pages:
ReportSectioneb8c865100f8508cc533 - Tiles
ReportSection600dd9293d71ade01765 - Market Share
ReportSectiona271643cba2213c935be - YTD Category
ReportSection1c45b5dc6513ae89b4e3 - Sentiment
ReportSection2ff5a27ac612830bbd93 - Tooltip
ReportSection6da8317ad6cbcae5b3bb - Empty Page
JavaScript
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
Limitations
The report must be loaded in order to use the getPages or getVisuals functions.
Next steps
Page navigation
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.
TypeScript
getPages(): Promise<Page[]>
For example:
JavaScript
TypeScript
JavaScript
await report.setPage("page2");
TypeScript
setActive(): Promise<void>
For example:
JavaScript
await page.setActive();
JavaScript
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.
Basic - IBasicFilter
Advanced - IAdvancedFilter
Top N - ITopNFilter
Relative date - IRelativeDateFilter
Relative time - IRelativeTimeFilter
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.
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.
Basic filter
Basic filter has a single operator with one or more values.
TypeScript
operator - For basic filter the operator can be one of the following:
TypeScript
values - An array of values for the filter, all values need to be of the same type.
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
TypeScript
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;
}
TypeScript
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
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
operator - The operator for Top N filter can be one of the following:
TypeScript
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
};
TypeScript
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.
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.
Days ✔ ✖
Weeks ✔ ✖
CalendarWeeks ✔ ✖
Months ✔ ✖
CalendarMonths ✔ ✖
Years ✔ ✖
CalendarYears ✔ ✖
Minutes ✖ ✔
Hours ✖ ✔
TypeScript
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
};
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
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
Filters operation
When calling updateFilters you need to pass the filter operation you want to preform.
The available operations are:
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.
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
JavaScript
Adding new filters, alongside the existing filters, for all pages.
JavaScript
JavaScript
await report.updateFilters(models.FiltersOperations.RemoveAll);
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.
JavaScript
Replacing all existing filters applied to a specific page, with a new set of filters.
JavaScript
JavaScript
await page.updateFilters(models.FiltersOperations.RemoveAll);
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.
JavaScript
JavaScript
JavaScript
await visual.updateFilters(models.FiltersOperations.RemoveAll);
Limitations
Having more than two conditions when building an Advanced filter may cause
undefined behavior.
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.
to the report.
play - Controls the slide show presentation mode for the report's bookmarks.
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.
TypeScript
getBookmarks(): Promise<models.IReportBookmark[]>
For example:
JavaScript
bookmarksManager property.
TypeScript
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.
TypeScript
capture(options?:ICaptureBookmarkOptions): Promise<models.IReportBookmark>
For example:
JavaScript
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
});
TypeScript
For example:
JavaScript
await report.bookmarksManager.applyState(capturedBookmark.state);
For example:
JavaScript
JavaScript
let embedConfig = {
...
panes: {
bookmarks: {
visible: true
}
}
};
JavaScript
let embedConfig = {
...
panes: {
bookmarks: {
visible: false
}
}
};
For information about updating report settings, see Configure report settings.
TypeScript
Before entering bookmarks slide show mode, make sure that there is at least one
bookmark on the report with getBookmarks API.
JavaScript
await report.bookmarksManager.play(models.BookmarksPlayMode.Presentation);
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.
TypeScript
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.
TypeScript
interface IExportDataResult {
data: string;
}
Example
To export the first 100 rows of summarized data:
JavaScript
console.log(result.data);
Next steps
Get pages and visuals
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.
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]
});
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]
});
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]
});
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.
Hierarchy filter
The IHierarchyFilter describes the slicer hierarchy. Use the getSlicerState and
setSlicerState methods with this filter.
JavaScript
JavaScript
interface IHierarchyFilterNode {
value?: PrimitiveValueType;
keyValues?: PrimitiveValueType[];
children?: IHierarchyFilterNode[];
operator?: HierarchyFilterNodeOperators;
}
of the following:
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"
}
]
}
]
};
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"
}
]
}
]
};
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"
}
]
}
]
}
Slicer APIs
You can use the following methods for visuals with the slicer type:
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.
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
JavaScript
await visual.setSlicerState(state);
TypeScript
interface ISlicerState {
filters: ISlicerFilter[];
targets?: SlicerTarget[];
}
To reset a slicer, call setSlicerState with an empty array of filters.
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.
TypeScript
interface IReportLoadConfiguration {
...
slicers?: ISlicer[];
}
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.
JavaScript
let slicers = [
{
selector: {
$schema: "http://powerbi.com/product/schema#visualSelector",
visualName: "d1feb8891635af3b335a"
},
state: {
filters: [advancedFilter]
}
}
];
let embedConfig = {
...
slicers: slicers,
};
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,
};
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.
JavaScript
let embedConfig = {
...
settings: {
layoutType: models.LayoutType.Custom
customLayout: {...}
}
};
For more information about report settings, see Configure report settings.
JavaScript
interface ICustomLayout {
pageSize?: IPageSize;
displayOption?: DisplayOption;
pagesLayout?: PagesLayout;
}
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
JavaScript
interface IPageLayout {
defaultLayout: IVisualLayout,
visualsLayout: { [key: string]: IVisualLayout; };
}
TypeScript
defaultLayout?: IVisualLayout
TypeScript
visualsLayout: VisualsLayout
TypeScript
interface IVisualLayout {
x?: number;
y?: number;
z?: number;
width?: number;
height?: number;
displayState?: IVisualContainerDisplayState;
}
of the visual.
JavaScript
interface IVisualContainerDisplayState {
mode: VisualContainerDisplayMode;
}
JavaScript
enum VisualContainerDisplayMode {
Visible,
Hidden
}
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
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
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.
TypeScript
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.
TypeScript
The Power BI Client Report class, defines the applyTheme method as:
TypeScript
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);
This example is useful if you want to apply a custom theme to a new report.
TypeScript
7 Note
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
Next steps
Configure report settings
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.
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.
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
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",
}
}
}]
}
}
};
...
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
}
}
}]
}
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
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
}]
}
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: [...]
}
};
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
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.
TypeScript
JavaScript
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
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);
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
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.
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:
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.
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:
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.
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);
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);
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
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.
TypeScript
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[];
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
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
};
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]
};
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
You can hide the Power BI embedded analytics default error messages on reports, and
instead show custom error messages that fit your app design.
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
// If the error level isn't Fatal, log the error and continue.
if (error.level !== models.TraceType.Fatal) {
console.error(error);
return;
}
Next steps
Configure report settings
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:
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
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",
}
}
]
}
}
};
JavaScript
let config = {
...
settings: {
...
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
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,
...
};
JavaScript
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
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:
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
}
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.
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"]
};
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"]
};
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"
}]
}
JavaScript
let columnAggregation = {
$schema: "http://powerbi.com/product/schema#columnAggr",
table: "Store",
column: "Sales",
aggregationFunction: "Sum"
};
Next steps
Control report filters
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:
) 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.
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.
TypeScript
let config = {
type: 'report',
...
settings: {
personalBookmarksEnabled: true
}
};
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.
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
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.
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.
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
TypeScript
resetPersistentFilters(): Promise<void>
TypeScript
savePersistentFilters(): Promise<void>
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
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.
1. Verify that your Azure Active Directory (Azure AD) app has the
UserState.ReadWrite.All permission.
JavaScript
let config = {
type: 'report',
...
settings: {
personalBookmarksEnabled: true
}
};
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
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
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).
JavaScript
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
7 Note
JavaScript
const customLayout = {
x: 20,
y: 35,
width: 1600,
height: 1200
}
JavaScript
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
Next steps
Change the visual type
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
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.
TypeScript
interface IVisualDataRole {
name: string;
kind: VisualDataRoleKind;
kindPreference?: VisualDataRoleKindPreference;
displayName?: string;
description?: string;
}
You can retrieve visual metadata for both out-of-the-box and custom visuals installed on
the report.
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');
TypeScript
getCapabilities(): Promise<models.IVisualCapabilities>
Example
Below is a code example for finding the capabilities in a visual at the visual level.
JavaScript
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
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.
TypeScript
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"
};
TypeScript
This method has the dataRole variable, which is the name of the data role from which to
retrieve the data fields.
For example:
JavaScript
TypeScript
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
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
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.
JavaScript
tooltip
visible Boolean
textSize Number
fontFamily String
transparency Number
background
visible Boolean
transparency Number
visualHeader
visible Boolean
transparency Number
border
visible Boolean
radius Number
lockAspect
enabled Boolean
title
visible Boolean
textSize Number
Object name Property name Type
fontFamily String
titleText String
legend
visible Boolean
dataLabels
visible Boolean
categoryAxis
visible Boolean
valueAxis
visible Boolean
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
7 Note
JavaScript
export interface IVisualPropertyValue {
schema?: string;
value: any;
}
schema - Defines the type of the value. There are two schemas available:
JavaScript
interface IThemeColorProperty {
id: number;
shade: number;
}
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',
};
const LegendPosition = {
Top: 'Top',
Bottom: 'Bottom',
Right: 'Right',
Left: 'Left',
TopCenter: 'TopCenter',
BottomCenter: 'BottomCenter',
RightCenter: 'RightCenter',
LeftCenter: 'LeftCenter',
};
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.
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
Setting a property
Set a property value to a visual according to the property selector.
TypeScript
For example:
JavaScript
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
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
Next steps
Report authoring overview
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.
JavaScript
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
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.
JavaScript
Code examples
JavaScript
await page.deleteVisual("8d0e01e7a860c2e5706d");
Next steps
Change the visual type
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
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
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.
TypeScript
TypeScript
await report.deletePage("ReportSection123");
ReportSection123 is the pageName the getPages API returned for the Sales page
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.
TypeScript
pageName is a unique identifier that's different from the displayName . You can use the
TypeScript
ReportSection123 is the pageName the getPages API returned for the Sales page.
TypeScript
TypeScript
newPage.setDisplayName("New Sales");
Limitations
Page operations work only after the report is loaded.
Next steps
Get pages and visuals
Page navigation
Get started
b GET STARTED
h WHAT'S NEW
Multitenancy solutions
i REFERENCE
Client APIs
h WHAT'S NEW
g TUTORIAL
c HOW-TO GUIDE
i REFERENCE
Y ARCHITECTURE
Capacity planning
p CONCEPT
Power BI permissions
h WHAT'S NEW
Playground
i REFERENCE
Developer center
Power BI libraries
Learn
d TRAINING
i REFERENCE