forked from microsoft/PowerBI-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembed.ts
871 lines (753 loc) · 24.3 KB
/
embed.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as models from 'powerbi-models';
import * as sdkConfig from './config';
import { EmbedUrlNotSupported, invalidEmbedUrlErrorMessage } from './errors';
import { ICustomEvent, IEvent, IEventHandler, Service } from './service';
import { addParamToUrl, assign, autoAuthInEmbedUrl, createRandomString, getTimeDiffInMilliseconds, remove, isCreate, validateEmbedUrl } from './util';
declare global {
interface Document {
// Mozilla Fullscreen
mozCancelFullScreen: any;
// Ms Fullscreen
msExitFullscreen: any;
// Safari Fullscreen
webkitExitFullscreen: void;
}
interface HTMLIFrameElement {
// Mozilla Fullscreen
mozRequestFullScreen: Function;
// Ms Fullscreen
msRequestFullscreen: Function;
// Safari Fullscreen
webkitRequestFullscreen: { (): void };
}
}
export type IBootstrapEmbedConfiguration = models.IBootstrapEmbedConfiguration;
export type IEmbedConfigurationBase = models.IEmbedConfigurationBase;
// TODO: Re-use ILoadConfiguration interface to prevent duplicating properties.
export type IEmbedConfiguration = models.IEmbedConfiguration;
export type IVisualEmbedConfiguration = models.IVisualEmbedConfiguration;
export type IReportEmbedConfiguration = models.IReportEmbedConfiguration;
export type IDashboardEmbedConfiguration = models.IDashboardEmbedConfiguration;
export type ITileEmbedConfiguration = models.ITileEmbedConfiguration;
export type IQnaEmbedConfiguration = models.IQnaEmbedConfiguration;
export type IQuickCreateConfiguration = models.IQuickCreateConfiguration;
export type IReportCreateConfiguration = models.IReportCreateConfiguration;
export type ILocaleSettings = models.ILocaleSettings;
export type IQnaSettings = models.IQnaSettings;
export type IEmbedSettings = models.ISettings;
/** @hidden */
export interface IInternalEventHandler<T> {
test(event: IEvent<T>): boolean;
handle(event: ICustomEvent<T>): void;
}
/** @hidden */
export interface ISessionHeaders {
uid: string;
sdkSessionId: string;
tokenProviderSupplied?: boolean;
bootstrapped?: boolean;
sdkVersion?: string;
}
/**
* Base class for all Power BI embed components
*
* @export
* @abstract
* @hidden
* @class Embed
*/
export abstract class Embed {
/** @hidden */
static allowedEvents = ["loaded", "saved", "rendered", "saveAsTriggered", "error", "dataSelected", "buttonClicked", "info"];
/** @hidden */
static accessTokenAttribute = 'powerbi-access-token';
/** @hidden */
static embedUrlAttribute = 'powerbi-embed-url';
/** @hidden */
static nameAttribute = 'powerbi-name';
/** @hidden */
static typeAttribute = 'powerbi-type';
/** @hidden */
static defaultEmbedHostName = "https://app.powerbi.com";
/** @hidden */
static type: string;
/** @hidden */
static maxFrontLoadTimes = 2;
/** @hidden */
allowedEvents: string[] = [];
/** @hidden */
protected commands: models.ICommandExtension[];
/** @hidden */
protected initialLayoutType: models.LayoutType;
/** @hidden */
groups: models.IMenuGroupExtension[];
/**
* Gets or sets the event handler registered for this embed component.
*
* @type {IInternalEventHandler<any>[]}
* @hidden
*/
eventHandlers: IInternalEventHandler<any>[];
/**
* Gets or sets the eventHooks.
*
* @type {models.EventHooks}
* @hidden
*/
eventHooks: models.EventHooks;
/**
* Gets or sets the Power BI embed service.
*
* @type {service.Service}
* @hidden
*/
service: Service;
/**
* Gets or sets the HTML element that contains the Power BI embed component.
*
* @type {HTMLElement}
* @hidden
*/
element: HTMLElement;
/**
* Gets or sets the HTML iframe element that renders the Power BI embed component.
*
* @type {HTMLIFrameElement}
* @hidden
*/
iframe: HTMLIFrameElement;
/**
* Saves the iframe state. Each iframe should be loaded only once.
* After first load, .embed will go into embedExisting path which will send
* a postMessage of /report/load instead of creating a new iframe.
*
* @type {boolean}
* @hidden
*/
iframeLoaded: boolean;
/**
* Gets or sets the configuration settings for the Power BI embed component.
*
* @type {IEmbedConfigurationBase}
* @hidden
*/
config: IEmbedConfigurationBase;
/**
* Gets or sets the bootstrap configuration for the Power BI embed component received by powerbi.bootstrap().
*
* @type {IBootstrapEmbedConfiguration}
* @hidden
*/
bootstrapConfig: IBootstrapEmbedConfiguration;
/**
* Url used in the load request.
*
* @hidden
*/
loadPath: string;
/**
* Url used in the load request.
*
* @hidden
*/
phasedLoadPath: string;
/**
* Type of embed
*
* @hidden
*/
embedtype: string;
/**
* Handler function for the 'ready' event
*
* @hidden
*/
frontLoadHandler: () => any;
/**
* The time the last /load request was sent
*
* @hidden
*/
lastLoadRequest: Date;
/**
* Creates an instance of Embed.
*
* Note: there is circular reference between embeds and the service, because
* the service has a list of all embeds on the host page, and each embed has a reference to the service that created it.
*
* @param {service.Service} service
* @param {HTMLElement} element
* @param {IEmbedConfigurationBase} config
* @hidden
*/
constructor(service: Service, element: HTMLElement, config: IEmbedConfigurationBase, iframe?: HTMLIFrameElement, phasedRender?: boolean, isBootstrap?: boolean) {
if (autoAuthInEmbedUrl(config.embedUrl)) {
throw new Error(EmbedUrlNotSupported);
}
Array.prototype.push.apply(this.allowedEvents, Embed.allowedEvents);
this.eventHandlers = [];
this.service = service;
this.element = element;
this.iframe = iframe;
this.iframeLoaded = false;
this.embedtype = config.type.toLowerCase();
this.commands = [];
this.groups = [];
this.populateConfig(config, isBootstrap);
if (isCreate(this.embedtype)) {
this.setIframe(false /* set EventListener to call create() on 'load' event*/, phasedRender, isBootstrap);
} else {
this.setIframe(true /* set EventListener to call load() on 'load' event*/, phasedRender, isBootstrap);
}
}
/**
* Create is not supported by default
*
* @hidden
* @returns {Promise<void>}
*/
create(): Promise<void> {
throw new Error(`no create support`);
}
/**
* Saves Report.
*
* @returns {Promise<void>}
*/
async save(): Promise<void> {
try {
const response = await this.service.hpm.post<void>('/report/save', null, { uid: this.config.uniqueId }, this.iframe.contentWindow);
return response.body;
} catch (response) {
throw response.body;
}
}
/**
* SaveAs Report.
*
* @returns {Promise<void>}
*/
async saveAs(saveAsParameters: models.ISaveAsParameters): Promise<void> {
try {
const response = await this.service.hpm.post<void>('/report/saveAs', saveAsParameters, { uid: this.config.uniqueId }, this.iframe.contentWindow);
return response.body;
} catch (response) {
throw response.body;
}
}
/**
* Get the correlationId for the current embed session.
*
* ```javascript
* // Get the correlationId for the current embed session
* report.getCorrelationId()
* .then(correlationId => {
* ...
* });
* ```
*
* @returns {Promise<string>}
*/
async getCorrelationId(): Promise<string> {
try {
const response = await this.service.hpm.get<string>(`/getCorrelationId`, { uid: this.config.uniqueId }, this.iframe.contentWindow);
return response.body;
} catch (response) {
throw response.body;
}
}
/**
* Sends load configuration data.
*
* ```javascript
* report.load({
* type: 'report',
* id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
* accessToken: 'eyJ0eXA ... TaE2rTSbmg',
* settings: {
* navContentPaneEnabled: false
* },
* pageName: "DefaultPage",
* filters: [
* {
* ... DefaultReportFilter ...
* }
* ]
* })
* .catch(error => { ... });
* ```
*
* @hidden
* @param {models.ILoadConfiguration} config
* @param {boolean} phasedRender
* @returns {Promise<void>}
*/
async load(phasedRender?: boolean): Promise<void> {
if (!this.config.accessToken) {
console.debug("Power BI SDK iframe is loaded but powerbi.embed is not called yet.");
return;
}
if (!this.iframeLoaded) {
console.debug("Power BI SDK is trying to post /report/load before iframe is ready.");
return;
}
const path = phasedRender && this.config.type === 'report' ? this.phasedLoadPath : this.loadPath;
const headers: ISessionHeaders = {
uid: this.config.uniqueId,
sdkSessionId: this.service.getSdkSessionId(),
bootstrapped: this.config.bootstrapped,
sdkVersion: sdkConfig.default.version
};
if (!!this.eventHooks?.accessTokenProvider) {
headers.tokenProviderSupplied = true;
}
const timeNow: Date = new Date();
if (this.lastLoadRequest && getTimeDiffInMilliseconds(this.lastLoadRequest, timeNow) < 100) {
console.debug("Power BI SDK sent more than two /report/load requests in the last 100ms interval.");
return;
}
this.lastLoadRequest = timeNow;
try {
const response = await this.service.hpm.post<void>(path, this.config, headers, this.iframe.contentWindow);
return response.body;
} catch (response) {
throw response.body;
}
}
/**
* Removes one or more event handlers from the list of handlers.
* If a reference to the existing handle function is specified, remove the specific handler.
* If the handler is not specified, remove all handlers for the event name specified.
*
* ```javascript
* report.off('pageChanged')
*
* or
*
* const logHandler = function (event) {
* console.log(event);
* };
*
* report.off('pageChanged', logHandler);
* ```
*
* @template T
* @param {string} eventName
* @param {IEventHandler<T>} [handler]
*/
off<T>(eventName: string, handler?: IEventHandler<T>): void {
const fakeEvent: IEvent<any> = { name: eventName, type: null, id: null, value: null };
if (handler) {
remove((eventHandler) => eventHandler.test(fakeEvent) && (eventHandler.handle === handler), this.eventHandlers);
this.element.removeEventListener(eventName, <any>handler);
}
else {
const eventHandlersToRemove = this.eventHandlers
.filter((eventHandler) => eventHandler.test(fakeEvent));
eventHandlersToRemove
.forEach((eventHandlerToRemove) => {
remove((eventHandler) => eventHandler === eventHandlerToRemove, this.eventHandlers);
this.element.removeEventListener(eventName, <any>eventHandlerToRemove.handle);
});
}
}
/**
* Adds an event handler for a specific event.
*
* ```javascript
* report.on('pageChanged', (event) => {
* console.log('PageChanged: ', event.page.name);
* });
* ```
*
* @template T
* @param {string} eventName
* @param {service.IEventHandler<T>} handler
*/
on<T>(eventName: string, handler: IEventHandler<T>): void {
if (this.allowedEvents.indexOf(eventName) === -1) {
throw new Error(`eventName must be one of ${this.allowedEvents}. You passed: ${eventName}`);
}
this.eventHandlers.push({
test: (event: IEvent<T>) => event.name === eventName,
handle: handler
});
this.element.addEventListener(eventName, <any>handler);
}
/**
* Reloads embed using existing configuration.
* E.g. For reports this effectively clears all filters and makes the first page active which simulates resetting a report back to loaded state.
*
* ```javascript
* report.reload();
* ```
*/
async reload(): Promise<void> {
return await this.load();
}
/**
* Set accessToken.
*
* @returns {Promise<void>}
*/
async setAccessToken(accessToken: string): Promise<void> {
if (!accessToken) {
throw new Error("Access token cannot be empty");
}
let embedType = this.config.type;
embedType = (embedType === 'create' || embedType === 'visual' || embedType === 'qna' || embedType === 'quickCreate') ? 'report' : embedType;
try {
const response = await this.service.hpm.post<void>('/' + embedType + '/token', accessToken, { uid: this.config.uniqueId }, this.iframe.contentWindow);
this.config.accessToken = accessToken;
this.element.setAttribute(Embed.accessTokenAttribute, accessToken);
this.service.accessToken = accessToken;
return response.body;
} catch (response) {
throw response.body;
}
}
/**
* Gets an access token from the first available location: config, attribute, global.
*
* @private
* @param {string} globalAccessToken
* @returns {string}
* @hidden
*/
private getAccessToken(globalAccessToken: string): string {
const accessToken = this.config.accessToken || this.element.getAttribute(Embed.accessTokenAttribute) || globalAccessToken;
if (!accessToken) {
throw new Error(`No access token was found for element. You must specify an access token directly on the element using attribute '${Embed.accessTokenAttribute}' or specify a global token at: powerbi.accessToken.`);
}
return accessToken;
}
/**
* Populate config for create and load
*
* @hidden
* @param {IEmbedConfiguration}
* @returns {void}
*/
populateConfig(config: IBootstrapEmbedConfiguration, isBootstrap: boolean): void {
if (this.bootstrapConfig) {
this.config = assign({}, this.bootstrapConfig, config);
// reset bootstrapConfig because we do not want to merge it in re-embed scenario.
this.bootstrapConfig = null;
}
else {
// Copy config - important for multiple iframe scenario.
// Otherwise, if a user uses the same config twice, same unique Id which will be used in different iframes.
this.config = assign({}, config);
}
this.config.embedUrl = this.getEmbedUrl(isBootstrap);
this.config.groupId = this.getGroupId();
this.addLocaleToEmbedUrl(config);
this.config.uniqueId = this.getUniqueId();
const extensions = this.config?.settings?.extensions as models.IExtensions;
this.commands = extensions?.commands ?? [];
this.groups = extensions?.groups ?? [];
this.initialLayoutType = this.config?.settings?.layoutType ?? models.LayoutType.Master;
// Adding commands in extensions array to this.commands
const extensionsArray = this.config?.settings?.extensions as models.IExtension[];
if (Array.isArray(extensionsArray)) {
this.commands = [];
extensionsArray.map((extension: models.IExtension) => { if (extension?.command) { this.commands.push(extension.command); } });
}
if (isBootstrap) {
// save current config in bootstrapConfig to be able to merge it on next call to powerbi.embed
this.bootstrapConfig = this.config;
this.bootstrapConfig.bootstrapped = true;
}
else {
this.config.accessToken = this.getAccessToken(this.service.accessToken);
}
this.eventHooks = (<IEmbedConfiguration>this.config).eventHooks;
this.validateEventHooks(this.eventHooks);
delete (<IEmbedConfiguration>this.config).eventHooks;
this.configChanged(isBootstrap);
}
/**
* Validate EventHooks
*
* @private
* @param {models.EventHooks} eventHooks
* @hidden
*/
private validateEventHooks(eventHooks: models.EventHooks): void {
if (!eventHooks) {
return;
}
for (let key in eventHooks) {
if (eventHooks.hasOwnProperty(key) && typeof eventHooks[key] !== 'function') {
throw new Error(key + " must be a function");
}
}
const applicationContextProvider = eventHooks.applicationContextProvider;
if (!!applicationContextProvider) {
if (this.embedtype.toLowerCase() !== "report") {
throw new Error("applicationContextProvider is only supported in report embed");
}
this.config.embedUrl = addParamToUrl(this.config.embedUrl, "registerQueryCallback", "true");
}
const accessTokenProvider = eventHooks.accessTokenProvider;
if (!!accessTokenProvider) {
if ((['create', 'quickcreate', 'report'].indexOf(this.embedtype.toLowerCase()) === -1) || this.config.tokenType !== models.TokenType.Aad) {
throw new Error("accessTokenProvider is only supported in report SaaS embed");
}
}
}
/**
* Adds locale parameters to embedUrl
*
* @private
* @param {IEmbedConfiguration | models.ICommonEmbedConfiguration} config
* @hidden
*/
private addLocaleToEmbedUrl(config: IEmbedConfiguration | models.ICommonEmbedConfiguration): void {
if (!config.settings) {
return;
}
const localeSettings = config.settings.localeSettings;
if (localeSettings && localeSettings.language) {
this.config.embedUrl = addParamToUrl(this.config.embedUrl, 'language', localeSettings.language);
}
if (localeSettings && localeSettings.formatLocale) {
this.config.embedUrl = addParamToUrl(this.config.embedUrl, 'formatLocale', localeSettings.formatLocale);
}
}
/**
* Gets an embed url from the first available location: options, attribute.
*
* @private
* @returns {string}
* @hidden
*/
private getEmbedUrl(isBootstrap: boolean): string {
let embedUrl = this.config.embedUrl || this.element.getAttribute(Embed.embedUrlAttribute);
if (isBootstrap && !embedUrl) {
// Prepare flow, embed url was not provided, use hostname to build embed url.
embedUrl = this.getDefaultEmbedUrl(this.config.hostname);
}
if (typeof embedUrl !== 'string' || embedUrl.length === 0) {
throw new Error(`Embed Url is required, but it was not found. You must provide an embed url either as part of embed configuration or as attribute '${Embed.embedUrlAttribute}'.`);
}
return embedUrl;
}
/**
* @hidden
*/
private getDefaultEmbedUrl(hostname: string): string {
if (!hostname) {
hostname = Embed.defaultEmbedHostName;
}
const endpoint = this.getDefaultEmbedUrlEndpoint();
// Trim spaces to fix user mistakes.
hostname = hostname.toLowerCase().trim();
if (hostname.indexOf("https://") === 0) {
return `${hostname}/${endpoint}`;
}
return `https://${hostname}/${endpoint}`;
}
/**
* Gets a unique ID from the first available location: options, attribute.
* If neither is provided generate a unique string.
*
* @private
* @returns {string}
* @hidden
*/
private getUniqueId(): string {
return this.config.uniqueId || this.element.getAttribute(Embed.nameAttribute) || createRandomString();
}
/**
* Gets the group ID from the first available location: options, embeddedUrl.
*
* @private
* @returns {string}
* @hidden
*/
private getGroupId(): string {
return this.config.groupId || Embed.findGroupIdFromEmbedUrl(this.config.embedUrl);
}
/**
* Gets the report ID from the first available location: options, attribute.
*
* @abstract
* @returns {string}
*/
abstract getId(): string;
/**
* Raise a config changed event.
*
* @hidden
* @returns {void}
*/
abstract configChanged(isBootstrap: boolean): void;
/**
* Gets default embed endpoint for each entity.
* For example: report embed endpoint is reportEmbed.
* This will help creating a default embed URL such as: https://app.powerbi.com/reportEmbed
*
* @hidden
* @returns {string} endpoint.
*/
abstract getDefaultEmbedUrlEndpoint(): string;
/**
* Requests the browser to render the component's iframe in fullscreen mode.
*/
fullscreen(): void {
const requestFullScreen = this.iframe.requestFullscreen || this.iframe.msRequestFullscreen || this.iframe.mozRequestFullScreen || this.iframe.webkitRequestFullscreen;
requestFullScreen.call(this.iframe);
}
/**
* Requests the browser to exit fullscreen mode.
*/
exitFullscreen(): void {
if (!this.isFullscreen(this.iframe)) {
return;
}
const exitFullscreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen;
exitFullscreen.call(document);
}
/**
* Returns true if the iframe is rendered in fullscreen mode,
* otherwise returns false.
*
* @private
* @param {HTMLIFrameElement} iframe
* @returns {boolean}
* @hidden
*/
private isFullscreen(iframe: HTMLIFrameElement): boolean {
const options = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullscreenScreenElement', 'msFullscreenElement'];
return options.some((option) => document[option] === iframe);
}
/**
* Validate load and create configuration.
*
* @hidden
*/
abstract validate(config: IEmbedConfigurationBase): models.IError[];
/**
* Sets Iframe for embed
*
* @hidden
*/
private setIframe(isLoad: boolean, phasedRender?: boolean, isBootstrap?: boolean): void {
if (!this.iframe) {
const iframeContent = document.createElement("iframe");
const embedUrl = this.config.uniqueId ? addParamToUrl(this.config.embedUrl, 'uid', this.config.uniqueId) : this.config.embedUrl;
if (!validateEmbedUrl(embedUrl)) {
throw new Error(invalidEmbedUrlErrorMessage);
}
iframeContent.style.width = '100%';
iframeContent.style.height = '100%';
iframeContent.setAttribute("src", embedUrl);
iframeContent.setAttribute("scrolling", "no");
iframeContent.setAttribute("allowfullscreen", "true");
const node = this.element;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
node.appendChild(iframeContent);
this.iframe = node.firstChild as HTMLIFrameElement;
}
if (isLoad) {
if (!isBootstrap) {
// Validate config if it's not a bootstrap case.
const errors = this.validate(this.config);
if (errors) {
throw errors;
}
}
this.iframe.addEventListener('load', () => {
this.iframeLoaded = true;
this.load(phasedRender);
}, false);
if (this.service.getNumberOfComponents() <= Embed.maxFrontLoadTimes) {
this.frontLoadHandler = () => {
this.frontLoadSendConfig(this.config);
};
// 'ready' event is fired by the embedded element (not by the iframe)
this.element.addEventListener('ready', this.frontLoadHandler, false);
}
} else {
this.iframe.addEventListener('load', () => this.create(), false);
}
}
/**
* Set the component title for accessibility. In case of iframes, this method will change the iframe title.
*/
setComponentTitle(title: string): void {
if (!this.iframe) {
return;
}
if (title == null) {
this.iframe.removeAttribute("title");
} else {
this.iframe.setAttribute("title", title);
}
}
/**
* Sets element's tabindex attribute
*/
setComponentTabIndex(tabIndex?: number): void {
if (!this.element) {
return;
}
this.element.setAttribute("tabindex", (tabIndex == null) ? "0" : tabIndex.toString());
}
/**
* Removes element's tabindex attribute
*/
removeComponentTabIndex(_tabIndex?: number): void {
if (!this.element) {
return;
}
this.element.removeAttribute("tabindex");
}
/**
* Adds the ability to get groupId from url.
* By extracting the ID we can ensure that the ID is always explicitly provided as part of the load configuration.
*
* @hidden
* @static
* @param {string} url
* @returns {string}
*/
static findGroupIdFromEmbedUrl(url: string): string {
const groupIdRegEx = /groupId="?([^&]+)"?/;
const groupIdMatch = url.match(groupIdRegEx);
let groupId: string;
if (groupIdMatch) {
groupId = groupIdMatch[1];
}
return groupId;
}
/**
* Sends the config for front load calls, after 'ready' message is received from the iframe
*
* @hidden
*/
private async frontLoadSendConfig(config: IEmbedConfigurationBase): Promise<void> {
if (!config.accessToken) {
return;
}
const errors = this.validate(config);
if (errors) {
throw errors;
}
// contentWindow must be initialized
if (this.iframe.contentWindow == null) {
return;
}
try {
const response = await this.service.hpm.post<void>("/frontload/config", config, { uid: this.config.uniqueId }, this.iframe.contentWindow);
return response.body;
} catch (response) {
throw response.body;
}
}
}