BlazeSDK class

Use this reference for the Experiences Web SDK entry point: initialization, global options, widget methods, playback helpers, and types. API identifiers keep the Blaze prefix in code.

How this page is organized

## Methods groups the global static methods on BlazeSDK:

  • Lifecycle: isInitialized, Initialize, and readiness (onBlazeSDKConnect).
  • Widget constructors: WidgetGridView, WidgetRowView, WidgetEmbeddedStory, WidgetEmbeddedVideo, and the shared IWidgetViewOptions table.
  • Theme: Theme() and the available theme presets.
  • Privacy and tracking: setDoNotTrack, setDisableAnalytics, setDisableUserActivity, clearLocalUserActivity.
  • Viewer identity and localization: setExternalUserId, logout, setExternalUserToken, setPreferredLanguage, setGeoLocation.
  • Personalization: isInColdStart.
  • Interaction: setOnItemClick.
  • Playback: playContent, playStory, playStories, appendContentToPlayer, setBeforeContentPlayCallback.
  • Moments playback: setDefaultMomentsPlaybackConfiguration, updateMomentsPlaybackConfiguration, and the IBlazeMomentsPlaybackConfiguration type.
  • Player control: closeCurrentPlayer, pauseCurrentPlayer, resumeCurrentPlayer.
  • App context: getAppContextManager.

## Ads covers Web prefetch, the Moments banner, ad frequency, and the ad handlers. ## Complete integration example puts several widget calls together.

Content and customization types live on their own pages:

Methods

Lifecycle

isInitialized(): boolean

The isInitialized method returns a boolean that indicates whether the SDK is already initialized. This helps prevent duplicate initialization calls and lets you run logic depending on the SDK's readiness. Call this method before initializing to confirm that the SDK hasn’t already been set up elsewhere in your application.

Initialize(apiKey: string, options: IBlazeSDKOptions): Promise<void>

The SDK injects a <blaze-sdk api-key="…" /> element into the document as part of startup. Initialize returns a promise that resolves once that element is added to the page, not when the SDK is ready.

Call Initialize once per page load. Later calls are ignored. Run it as early as your app allows (for example, right after you create the root container). Pass a valid IBlazeSDKOptions object when you need global behavior (privacy, identity, geo, player styling, and so on).

To know when the SDK is ready, listen for onBlazeSDKConnect. Register the listener before or right after you call Initialize. The event fires asynchronously, once, after startup completes. If you register later, call isInitialized() first: it returns true once the event has fired.

ParameterTypeRequiredDescription
apiKeystringYesAPI key
options.doNotTrack?booleannoSets do not track
options.externalUserId?stringnoSets the viewer ID for a logged-in viewer. Your app supplies this value. See Viewer ID specifications.
options.externalUserToken?string | nullnoSets the external user token used for protected or tokenized playback. Same as calling setExternalUserToken.
options.geoLocation?stringnoSets the geolocation feature globally. This value overrides the default IP-based country detection.
options.runInShadowDom?booleannoRuns the SDK inside a shadow dom. default = true
options.shouldModifyUrlWithStoryId?booleannoControls whether the SDK updates the browser URL when story content opens. The two URL options don't work independently, so set it to the same value as options.shouldModifyUrlWithContentId.
options.shouldModifyUrlWithContentId?booleannoControls whether the SDK updates the browser URL using the content ID when content opens. The two URL options don't work independently, so set it to the same value as options.shouldModifyUrlWithStoryId.
options.disableAutoLoadingContent?booleannoDefault false. When true, the SDK doesn't open the Story, Moment, or Video that a shared link in the page URL points to when the SDK starts. See Share links.
options.playerStyleCustomization?Partial <StoryPlayerStyle>noSet the global style on the player
options.momentsPlaybackConfiguration?IBlazeMomentsPlaybackConfigurationnoSets the default moments playback behavior. Same as calling setDefaultMomentsPlaybackConfiguration. See Moments playback.
options.prefetchingPolicy?string - 'low' | 'default'noDefault is the value if not defined
options.shouldAllowHorizontalStoriesbooleannoIf not defined, it displays vertical content on Desktop. Contact your account manager for more info.
options.layoutDirection'LTR' | 'RTL'noSet the SDK direction. Default 'LTR'.
options.shouldAllowClosedCaptionsbooleannoDefault false. When true, the Stories, Moments, and Videos players show closed captions. The captions button also needs to be visible in the player style. See Closed captions.
options.shouldAllowMultiAudiobooleannoDefault true. The video player shows an audio track selector for stream videos with two or more audio tracks. Pass false to turn it off in every video player. See Multi-audio.
options.followedEntitiesFollowedEntityInput[]noReplaces the viewer's entire followed-entities list. Each entry is an object, and entityType must be written, as undefined when the type is unknown. See Follow entities for the full shape, and for what this does to state on other devices before you call it on every page load.
options.disableAnalyticsbooleannoDisable analytics to WSC Sports, but allow delegation events
options.disableUserActivitybooleannoDefault false. When true, the SDK doesn't sync the viewer's activity with the server. Same as calling setDisableUserActivity.
options.preferredLanguagestringnoEnables dynamic content localization by communicating the viewer's preferred language to the backend API.
options.restoreExternalUserIdbooleannoDefault true. When true and no externalUserId is passed, the viewer from the previous page load is restored from browser storage. Pass false to start this page load anonymous; a stored viewer is then logged out. Ignored when externalUserId is passed.
document.addEventListener("onBlazeSDKConnect", onBlazeSDKConnect);

if (!BlazeSDK.isInitialized()) {
    BlazeSDK.Initialize('<API-KEY>',{
     geoLocation: 'IL', // Country code by two letters
     externalUserId: 'user-123',
     doNotTrack: false,
     runInShadowDom: true, // default value is true
     shouldModifyUrlWithStoryId: true, // default value is true
     shouldModifyUrlWithContentId: true, // default value is true. Set both options to the same value
     playerStyleCustomization: { // only for Stories, not supported to Moments
       iconsPosition: 'VERTICAL'
     },
     prefetchingPolicy: 'default',
     shouldAllowHorizontalStories: false, // by default false
     layoutDirection: "LTR", // by default LTR
     followedEntities: [
        { entityId: 'player-123', entityType: 'Player' },
        { entityId: 'team-123', entityType: 'Team' },
        { entityId: 'property-123', entityType: 'Property', providerName: 'stats-perform' },
     ],
     disableAnalytics: false,
     disableUserActivity: false
   })
}
📘

Share links

Share links don't depend on shouldModifyUrlWithStoryId or shouldModifyUrlWithContentId. A share link is always the current page URL with one of these hashes added:

  • Story: #blaze/story/<storyId>/page/<pageId>
  • Moment: #blaze/moment/<momentId>
  • Video: #blaze/video/<videoId>

If the page URL already has a hash, the SDK adds the content hash after it with &. Make sure the host page loads normally when its URL includes this hash. See Share links.

Prefetch Policy

LevelDescription
LowInitially, no pre-fetch While playing, the next page of the currently playing story, and the first unread page of the next story
DefaultInitially, pre-fetches the first story page in line. While playing, the next two pages of the currently playing story, the first unread page of the next story, and the first unread page of the previous story.

Widget constructors

WidgetGridView(containerId: string, options?: IWidgetViewOptions): IWidgetView

WidgetRowView(containerId: string, options?: IWidgetViewOptions): IWidgetView

WidgetEmbeddedStory(containerId: string, options?: IWidgetViewOptions): IWidgetView

WidgetEmbeddedVideo(containerId: string, options?: IWidgetViewOptions): IWidgetView

For guidance on when to use an embedded video widget versus a row or grid widget, plus an end-to-end example, see WidgetEmbeddedVideo.

BlazeSDK.WidgetRowView(...) and BlazeSDK.WidgetGridView(...) support options.widgetRemoteIdentifier?: string. When you provide this identifier, the widget loads its data source and layout styling from a remote widget configuration. After that, local runtime mutators, including theme and data source updates, are ignored because the widget is remote-managed.

You still need to pass a regular data source with widgetRemoteIdentifier. The widget isn't created without one, and it uses that data source when the remote configuration can't be loaded.

BlazeSDK.WidgetEmbeddedStory(...) and BlazeSDK.WidgetEmbeddedVideo(...) do not accept widgetRemoteIdentifier.

Returns an IWidgetView object

ParameterTypeRequiredDescription
containerIdstringYesThe widget will be appended to the HTML element with the given container ID
options?IWidgetViewOptionsNoOptional. Here, you can determine the labels and theme for the created view
options.dataSourceBlazeDataSourceTypeif not labels or storyIds provided
options.labelsstringstring[]\BlazeWidgetLabelIf storyIds were not specifiedArray of strings is deprecated but still supported, string as value or create your labels with LabelBuilder
options.storyIdsstring[]If labels was not specified
  • deprecated - use contentIds instead Fetching and displaying the specific stories indicated with ['storyId1', 'storyId2'].\
Please note: In case you specify both "labels" and "storyIds" properties, only the "labels" property will be applied.
options.contentIdsstring[]if labels were not specified

deprecated Fetching and displaying the specific stories/moments indicated with ['1234', '5678'].

Please note: In case you specify both "labels" and "storyIds" properties, only the "labels" property will be applied.

options.contentType?'story' | 'moment' | 'video'if not provided, will be storyTo use specific content, it is recommended to set it
options.videoFilters?IVideoFilterOptionsNoFilter video content by type ('Video' = on-demand, 'Stream' = live streams) and stream state ('Live', 'Upcoming', 'Ended'). Use the VideoFilterBuilder helper for common scenarios. See VideoFiltersBuilder.
options.labelsPriority?stringNodeprecated The order is which the string will order the label's result. A string with an opening of '[' and close by ']'. Example: '[teama, teamb]'
options.widgetRemoteIdentifier?stringNoSupported only by BlazeSDK.WidgetRowView(...) and BlazeSDK.WidgetGridView(...). Loads the widget data source and layout styling from a remote widget configuration. When set, local runtime mutators, including theme and data source updates, are ignored. You still need to pass a data source, which is used when the remote configuration can't be loaded.
options.theme?IWidgetTheme | ThemeTypeNoA theme for this view: your own theme object, or the name of a preset theme.
options.maxItemsCount?numberNodeprecated Specify the max items to fetch from server
options.maxDisplayItemsCount?numberNoSpecify the max items to display. You can display 3 items while having 10 items returned from server.
options.orderType?stringNo

Specify the items order type. Unread items will show first by selected order type, following by read items also ordered by selected order type.

Possible order types: Manual, AtoZ, ZtoA, RecentlyUpdatedFirst, RecentlyUpdatedLast, RecentlyCreatedFirst, RecentlyCreatedLast, StartTimeAsc, StartTimeDesc

options.perItemStyleOverrides?PerItemStyleOverridesno

The perItemStyleOverrides property in IWidgetViewOptions facilitates custom styling for individual items within a widget based on specific entity identifiers.

This feature enhances flexibility by allowing unique visual representations for each item within the widget.

options.shouldOrderWidgetByReadStatus?booleannoIf set to false, read/unread does not change item order. Items follow the data source orderType or server order. Default is true. See Ordering and item limits.
options.actionHandlers?ActionHandler[]noArray of actions. Each action has an actionId and options.
options.momentsPlaybackConfiguration?IBlazeMomentsPlaybackConfigurationnoOverrides the SDK default moments playback behavior for the player opened from this widget. See Moments playback.
const myTheme: IWidgetTheme = BlazeSDK.Theme('row-rectangle');

const myDataSource = BlazeSDK.DataSourceBuilder().labels({
   labels: 'live-stories',
   orderType: 'RecentlyUpdatedFirst',
   maxItems: 10,
	 advancedOrdering: 'LiveFirst',

})

const options: IWidgetViewOptions = {
   dataSource: myDataSource, // Use a data source instead of labels
   maxDisplayItemsCount: 1, // Display only 1 item
   theme: myTheme, // Set the theme of the widget
   shouldOrderWidgetByReadStatus: true, // the default value is true
   perItemStyleOverrides: {
        "playerId": [
            {
                name: "35450",
                theme: rowCircleThemePlayer
            },
            {
                name: "28237",
                theme: rowCircleThemePlayer
            },
            {
                name: "46046",
                theme: rowCircleThemePlayer
            }
        ],
        "teamId": [
            {
                name: "real-madrid",
                theme: rowCircleThemeRealMadrid
            }
        ]
    },
    actionHandlers: [
        {
          actionId: 'addCustomActionButton',
          options: {
            id: 'go-to-fans-page',
            buttonName: 'go-to-fans-page',
            onClick: (e, entities) => {
              console.log(entities?.gameId, entities?.playerId, entities?.teamId);
            },
          },
        },
        {
          actionId: 'addCustomActionButton',
          options: {
            id: 'go-to-social-page',
            buttonName: 'go-to-social-page',
            onClick: (e, entities) => {
              console.log(entities?.gameId, entities?.playerId, entities?.teamId);
            },
          },
        },
	{
          actionId: 'addFollowButton',
          options: {
            onClick: (e, data) => {
              console.log(data.sourceId,
                          data.sourceContentType,
                          data.newFollowingState,
                          data.followEntity.entityType,
 			  data.followEntity.entityId,
			  data.followEntity.providerName); // optional, opaque data-provider name
            },
          },
        },
     ],
};

const widgetView: IWidgetView = BlazeSDK.WidgetRowView('<DOM-CONTAINER-ID>', options);

//widgetView has an interface, which allows you to interact with the widget in the DOM 
//widgetView.reload()

For perItemStyleOverrides and actionHandlers, see Per item style overrides and Action handlers.

Theme

Theme(preset?: ThemeType): IWidgetTheme

Returns an IWIdgetTheme object with default theme preset

ParameterTypeRequiredDescription
presetThemeTypeNothe preset theme name like "grid-3-columns" / "row-circle"
contentType'story''moment''video'NoIf not provided it will return a playerStyle of story.
const theme = BlazeSDK.Theme('row-rectangle','story');
const theme: IWidgetTheme = BlazeSDK.Theme('row-rectangle');

Theme Type

ValueDescription
row-circleA row layout with circular items.
row-circle-animatedA row layout with circular items and animated GIF thumbnails. Supported for stories, moments, and videos.
row-rectangleA row layout with rectangular items.
grid-2-columnsA grid layout with 2 columns.
grid-3-columnsA grid layout with 3 columns.
row-rectangle-horizontalA horizontal row layout with rectangular items.
row-rectangle-animatedA horizontal row layout with rectangular animated items. Supported for moments, long-form videos, and stories (shown as portrait tiles).
grid-2-columns-horizontalA horizontal grid layout with 2 columns.
grid-3-columns-horizontalA horizontal grid layout with 3 columns.
defaultThe default theme style - row-circle

For the full theme object, its properties per surface, and how to apply one, see Theme.

Privacy and tracking

setDoNotTrack(value: boolean): void

ParameterTypeRequiredDescription
valuebooleanYesSet the value of Do Not Track after the client has created the widget or initialized the SDK.
BlazeSDK.setDoNotTrack(true);

WSC Sports can enforce do not track for the app. When enforcement is on, the app cannot set this value to false. See Viewer privacy considerations and privacy compliance.

setDisableAnalytics(value: boolean): void

ParameterTypeRequiredDescription
valuebooleanYesEnables or disables analytics data transmission to WSC Sports. When set to true, no analytics data of any kind is sent to WSC Sports endpoints.
BlazeSDK.setDisableAnalytics(true);

WSC Sports can enforce analytics off for the app. When enforcement is on, the app cannot set this value to false. See Viewer privacy considerations and privacy compliance.

setDisableUserActivity(value: boolean): void

ParameterTypeRequiredDescription
valuebooleanYesEnables or disables user activity tracking and syncing at runtime. When set to true, local database still tracks activities, but activities remain device-local only.
BlazeSDK.setDisableUserActivity(true);

clearLocalUserActivity(): Promise<void>

Clears all user activity data from the device's local storage only, without affecting remote data.

BlazeSDK.clearLocalUserActivity();

Viewer identity and localization

setExternalUserId(value: string): Promise<void>

ParameterTypeRequiredDescription
valuestringYesThe viewer ID for the current viewer. The SDK sends it with all analytics events, and keeps it across page loads until you call logout(). Call it after Initialize; before that it rejects. A blank or invalid value is ignored. Setting the ID the SDK already has does nothing. See Viewer ID specifications.
await BlazeSDK.setExternalUserId('1234');
await BlazeSDK.logout(); // viewer signed out

logout(): Promise<void>

Logs out the current viewer. Their local activity and follows are cleared and the SDK continues as an anonymous viewer. Calling it while already anonymous does nothing. Call it after Initialize; before that it rejects. It also rejects when the logout could not be completed, and the viewer stays logged in, so call it again.

logout() emits the user_logout analytics event before the viewer ID is cleared, so the event still carries the outgoing ID. Switching to a different viewer with setExternalUserId does not emit it.

To log the viewer out on page load, pass restoreExternalUserId: false to Initialize instead.

await BlazeSDK.logout();

setExternalUserToken(token: string | null): void

Sets or replaces the external user token used for protected or tokenized playback. Pass null to clear the current token.

ParameterTypeRequiredDescription
tokenstring | nullYesThe external user token for protected or tokenized playback, or null to clear it.
BlazeSDK.setExternalUserToken('token-123');
BlazeSDK.setExternalUserToken(null);

setPreferredLanguage(value: string): void

ParameterTypeRequiredDescription
valuestringYesSet a preferred language for the SDK, make sure to use standard formats
BlazeSDK.setPreferredLanguage('en')

setGeoLocation(value: string): void

ParameterTypeRequiredDescription
valuestringYesUpdates the geographic location used for content geo-blocking. This value overrides the default IP-based country detection. Use a two-letter country code (for example, 'US', 'IL').
BlazeSDK.setGeoLocation('IL')

Personalization

isInColdStart(contentType: ContentType): boolean | null

Returns whether the current viewer is in cold start for the given content type.

ParameterTypeRequiredDescription
contentType'story' | 'moment' | 'video'YesThe content type to check.
  • true: the viewer's For You feed for this content type is served cold-start content instead of the personalized model.
  • false: the personalized model is served.
  • null: the status is unknown. For example, the viewer is anonymous (no externalUserId set), or user activity has not been fetched yet in this session.

The value refreshes with every user activity fetch (initialization, returning to the page, or a viewer switch). It does not change mid-session as the viewer interacts.

const status = BlazeSDK.isInColdStart('moment');

Interaction

setOnItemClick(callback: ItemClickCallback | undefined): void

Registers a single, SDK wide callback that runs when a viewer clicks a widget item (tile) in a row or grid widget, before the player opens. Return { shouldPreventOpen: true } from the callback to stop the default player from opening (for example, to route to your own screen); return { shouldPreventOpen: false } to allow normal behavior. Pass undefined to remove the callback.

This is separate from delegation events (the delegates option / addDelegateListener), which are CustomEvents for SDK lifecycle changes and cannot prevent the default click action.

ParameterTypeRequiredDescription
callbackItemClickCallback | undefinedYesThe callback to run on item click, or undefined to clear it.

The callback receives an ItemClickContext:

PropertyTypeDescription
containerIdstringThe container ID of the widget that was clicked.
itemIContentThe clicked content item.
itemIndexInContainernumberThe zero based index of the item within its container.
contentTypeContentTypeThe content type of the item (story, moment, or video).
contentThumbnailUrl?stringURL of the item's static thumbnail. In an animated row, it's the image the item rests on: its GIF poster (first frame), or its static thumbnail when it has no poster. Never a GIF. undefined when there's no such image.

item also carries recommendationVersion when the item came from a recommendations data source, naming the model version that produced it.

BlazeSDK.setOnItemClick((context) => {
  console.log('Clicked:', context.item.title, context.contentThumbnailUrl);
  return { shouldPreventOpen: false };
});

// Remove the callback
BlazeSDK.setOnItemClick(undefined);

Playback

playContent(contentType: ContentType, options: PlayContentOptions): Promise<void>

ParameterTypeRequired
contentType'story' | 'moment' | 'video'Yes
optionsPlayContentOptionsYes

The PlayContentOptions type defines the configuration options for the playContent function, allowing customization of content playback through data sources, action handlers, and styling options.

  • dataSource (BlazeDataSourceType): The source of the content to be played, providing the necessary data for rendering.
  • actionHandlers (ActionHandler[]?): Optional. An array of actions.
  • style (StoryPlayerStyle | VideoPlayerStyle?): Optional. Specifies the player’s visual styling. Custom action buttons are hidden by default, so set them visible in the player style. For stories, set isVisible (full screen) or isEmbeddedVisible (embedded) to true on the playerStyle.iconsButton entry whose value is 'CUSTOM_ACTION_BUTTON_ONE' or 'CUSTOM_ACTION_BUTTON_TWO'. For moments, set playerStyle.buttons.custom_action_button_one or custom_action_button_two, then .mobile, .tablet, or .desktop, then .isVisible to true. The video player doesn't show custom action buttons.
  • shouldOrderContentByReadStatus: Whether to order the content by read status, displaying unread items first. Default is true.
  • playbackConfiguration (IBlazeMomentsPlaybackConfiguration?): Optional. Moments only. Sets the playback behavior for this player. When omitted, the SDK default applies. See Moments playback.
const dataSource = BlazeSDK.DataSourceBuilder().labels({
  labels: BlazeSDK.LabelBuilder().atLeastOneOf('top-stories', 'live-stories'),
  maxItems: 4,
})
const playerStyle = BlazeSDK.Theme('default').playerStyle;
playerStyle.iconsButton.filter(icon => icon.value === 'CUSTOM_ACTION_BUTTON_ONE')[0].isVisible = true;
playerStyle.iconsButton.filter(icon => icon.value === 'CUSTOM_ACTION_BUTTON_TWO')[0].isVisible = true;

const actionHandlers = [
        {
          actionId: 'addCustomActionButton',
          options: {
            id: 'go-to-fans-page',
            buttonName: 'go-to-fans-page',
            onClick: (e, entities) => {
              console.log(entities?.gameId, entities?.playerId, entities?.teamId);
            },
          },
        },
        {
          actionId: 'addCustomActionButton',
          options: {
            id: 'go-to-social-page',
            buttonName: 'go-to-social-page',
            onClick: (e, entities) => {
              console.log(entities?.gameId, entities?.playerId, entities?.teamId);
            },
          },
        },
      ];

BlazeSDK.playContent('story',{
  dataSource,
  style: playerStyle,
  actionHandlers,
  shouldOrderContentByReadStatus: true
});

playStory(storyId: string, style?: StoryPlayerStyle ): void

Deprecated: use playContent instead of playStory.

ParameterTypeRequiredDescription
storyIdstringYesthe ID of the story you would like to play
styleStoryPlayerStylenoif not provided, will use the default player style
actionHandlersActionHandler[]noArray of actions. Each action has an actionId and options.

const playerStyle = BlazeSDK.Theme('default').playerStyle;

BlazeSDK.playStory('66c0d0c6607d0c10cf3dd98d',playerStyle)

playStories(dataSource: BlazeDataSourceType, style?: StoryPlayerStyle, actionHandlers?: ActionHandler[]): Promise<void>

Deprecated: use playContent instead of playStories.

ParameterTypeRequiredDescription
dataSourceBlazeDataSourceTypeYes
styleStoryPlayerStylenoif not provided, will use the default player style
actionHandlersActionHandler[]noArray of actions. Each action has an actionId and options.
const dataSource = BlazeSDK.DataSourceBuilder().labels({
  labels: BlazeSDK.LabelBuilder().atLeastOneOf('top-stories', 'live-stories'),
  maxItems: 4,
})
const playerStyle = BlazeSDK.Theme('default').playerStyle;

BlazeSDK.playStories(dataSource, playerStyle)

appendContentToPlayer(contentType: ContentType, dataSource: BlazeDataSourceType, options?): Promise<void>

This function supports only moment content type for now

This function allows you to append content to the current opened player. It receives a content type, data source and options object, and append it to the end of the current content list of the player.

function appendContentToPlayer(contentType: ContentType, dataSource: BlazeDataSourceType, options?: {
    shouldOrderContentByReadStatus?: boolean;
}): Promise<void>

Usage examples:

BlazeSDK.appendContentToPlayer('moment', 
                                BlazeSDK.DataSourceBuilder().labels({ labels: "my-label" })
                              );
BlazeSDK.appendContentToPlayer('moment', 
                               BlazeSDK.DataSourceBuilder().ids({ ids: ["6706731d200c07e22d70a2ed","663a1c0a4e167da3d5a3ddf9"] }),
                               { shouldOrderContentByReadStatus: false } 
                              );

setBeforeContentPlayCallback(callback: BeforeContentPlayCallback | undefined): void

The callback runs only when enableClientPlaybackModification is true in the app configuration. If the callback throws an error or returns an invalid result, the SDK falls back to the original URL so playback continues. Keep callback execution time short to avoid delays in video playback.

Don't expose sensitive tokens or credentials in client-side code.

ParameterTypeRequiredDescription
callbackBeforeContentPlayCallback | undefinedYesCallback function that receives the original video URL and returns a modified URL before content playback begins. Pass undefined to remove an existing callback.
BeforeContentPlayCallback interfaces
InterfacePropertyTypeDescription
BeforeContentPlayContextoriginalUrlstringThe original video URL that needs to be processed before playback
BeforeContentPlayResultresultUrlstringThe modified/tokenized URL that will be used for actual video playback

BeforeContentPlayCallback: (context: BeforeContentPlayContext) => Promise<BeforeContentPlayResult> | BeforeContentPlayResult

interface BeforeContentPlayContext {
  originalUrl: string;
}

interface BeforeContentPlayResult {
  resultUrl: string;
}

type BeforeContentPlayCallback = (
  context: BeforeContentPlayContext
) => Promise<BeforeContentPlayResult> | BeforeContentPlayResult;
Async URL tokenization
// URL tokenization example for protected content
BlazeSDK.setBeforeContentPlayCallback(async (context) => {
  const { originalUrl } = context;

  const response = await fetch(`https://example-service.com/tokenGen?url=${originalUrl}`)
  const data = await response.json()

  return {
    resultUrl: data.data.url
  };
});
Synchronous URL modification
// Synchronous URL modification example
BlazeSDK.setBeforeContentPlayCallback((context) => {
  const { originalUrl } = context;
  
  const url = new URL(originalUrl);
  url.searchParams.set('token', getUserToken());
  url.searchParams.set('timestamp', Date.now().toString());
  
  return {
    resultUrl: url.toString()
  };
});
Remove callback
// Remove callback
BlazeSDK.setBeforeContentPlayCallback(undefined);

Moments playback

Moments playback configuration controls what the moments player does when a moment finishes: replay it, or play it a set number of times and then advance to the next moment. By default, the player replays the current moment until the viewer navigates ({ loopBehavior: { type: 'infiniteLoop' } }).

IBlazeMomentsPlaybackConfiguration

PropertyTypeRequiredDescription
loopBehaviorBlazeMomentsLoopBehaviorYesWhat the player does when a moment finishes.

BlazeMomentsLoopBehavior is one of:

ValueBehavior
{ type: 'infiniteLoop' }Replays the current moment until the viewer navigates. This is the default.
{ type: 'loopAndAdvance', numberOfPlays: number }Plays the current moment numberOfPlays times, then advances to the next moment. numberOfPlays must be an integer of at least 1. The last moment in the list always loops.

Notes:

  • The configuration applies to content moments only. Ad moments always advance after a single play.
  • An invalid value doesn't throw. The SDK reports it on onErrorThrown and uses a working value instead: an invalid numberOfPlays becomes 1 (error code 400), and a missing or unknown loopBehavior falls back to infiniteLoop (error code 401).

You can set the configuration at several levels. A per-widget, per-call, or open-player value overrides the SDK default for that player:

LevelHow to set it
SDK defaultmomentsPlaybackConfiguration in Initialize options, or setDefaultMomentsPlaybackConfiguration
WidgetmomentsPlaybackConfiguration in the widget options. Applies to the player opened from that widget. See WidgetView class.
Single callplaybackConfiguration in playContent('moment', options)
Open playerupdateMomentsPlaybackConfiguration

setDefaultMomentsPlaybackConfiguration(configuration: IBlazeMomentsPlaybackConfiguration): void

Sets the SDK default moments playback behavior. It applies to every moments player that doesn't have a widget, call, or open-player override.

BlazeSDK.setDefaultMomentsPlaybackConfiguration({
  loopBehavior: { type: 'loopAndAdvance', numberOfPlays: 2 },
});

updateMomentsPlaybackConfiguration(configuration: IBlazeMomentsPlaybackConfiguration | null): void

Changes the playback behavior of the moments player that is currently open. It has no effect when no moments player is open. Pass null to remove the override; the open player then uses the SDK default.

BlazeSDK.updateMomentsPlaybackConfiguration({
  loopBehavior: { type: 'infiniteLoop' },
});
BlazeSDK.updateMomentsPlaybackConfiguration(null);

Player control

closeCurrentPlayer(): void

Closes the currently open player.

BlazeSDK.closeCurrentPlayer();

pauseCurrentPlayer(): void

Pause the story in the opened modal.

BlazeSDK.pauseCurrentPlayer();

resumeCurrentPlayer(): void

Resume the story in the opened modal.

BlazeSDK.resumeCurrentPlayer();

App context

getAppContextManager(): Record<string, any>

The app context manager allow you to send custom properties to your own enrichment layer. for example:

BlazeSDK.getAppContextManager().userName = "Lorem Ipsum"

Ads

Stories and Moments on Web use the existing ads configuration. See Ad capabilities in Experiences.

  • Prefetch: Stories and Moments preload the next VAST ad before the break. The look-ahead distance is the configured distance, or 2 items when that distance is not set. A distance of 0 turns prefetch off. provideAdExtraParams on setImaHandler can run at preload time, before the Viewer reaches the slot.
  • Moments banner: Web SDK 0.37.1 or later can show a 320×50 banner under the seek bar in the Moments player. The banner is attached when the content is published. setGoogleCustomNativeAdsHandler supplies extra params when the banner requests an ad. For a banner, args.path is the banner ad unit ID.
  • Frequency: when more Moments are added to the feed, the existing ad frequency keeps counting. The count does not start over. There is no added setting and no added call.

setGoogleCustomNativeAdsHandler

Allows you to send optional properties for custom native ads. It is an optional method.

type CustomNativeTargeting = Record<string, string | string[]>;
type CustomNativeArgs = {
  path: string;
};

interface CustomNativeAdHandler {
  provideAdExtraParams?: (args: CustomNativeArgs, contentExtraInfo?: ContentExtraInfo) => CustomNativeTargeting;
}

provideAdExtraParams

method signature

function provideAdExtraParams(args: { path: string }, contentExtraInfo?: ContentExtraInfo): CustomNativeTargeting;

// Usage example:
BlazeSDK.setGoogleCustomNativeAdsHandler({
  provideAdExtraParams: (args, contentExtraInfo) => {
    return {
    	"gdpr": "1",
    	"age": ["1", "2"],
    	"next": JSON.stringify(contentExtraInfo?.next),
    	"prev": JSON.stringify(contentExtraInfo?.previous)     
}
}});

Optional function that will be triggered every time a custom native ad or a banner ad (in the Stories and Moments players) requests an ad. For banner ads, args.path is the banner's ad unit ID. Use this to customize how (and if) each viewer consent (or any other extra query params) behaves. If not implemented, the SDK will use the default value, which equals to {}.

setImaHandler

Allows you to send optional properties for custom native ads. It is an optional method.

type ImaExtraParams = Record<string, string>;

interface ImaAdHandler {  
  provideAdExtraParams?: (contentExtraInfo?: ContentExtraInfo) => ImaExtraParams;
}

provideAdExtraParams

method signature

function provideAdExtraParams(contentExtraInfo? : ContentExtraInfo): ImaExtraParams;

// Usage example:  
BlazeSDK.setImaHandler({  
  provideAdExtraParams: (contentExtraInfo) => {  
    return {
    	"cust_params": "gdpr=1"
    }  
}});

Optional function that will be triggered every time a ima ad request an ad. Use this to customize how (and if) each viewer consent (or any other extra query params) behaves. If not implemented, the SDK will use the default value, which equals to .

In Stories and Moments, the SDK can preload the upcoming VAST ad so it starts without a loading delay. The look-ahead distance is the configured distance, or 2 items when that distance is not set. A distance of 0 turns this preload off. The request, and this function, run when the ad is preloaded, which can be before the viewer reaches the ad slot, and also for preloaded ads that end up not being shown.

Ad types

ContentExtraInfo

ParameterTypeDescription
previous?ExtraInfoPrevious content's ExtraInfo
current?ExtraInfoCurrent content's ExtraInfo
next?ExtraInfoNext content's ExtraInfo

ExtraInfo

TypeDescription
Record<string,string>Content's ExtraInfo

Complete integration example

const filters = BlazeSDK.VideoFilterBuilder();

// Live games section
const liveGames = BlazeSDK.WidgetRowView('live-container', {
  dataSource: BlazeSDK.DataSourceBuilder().labels({
    labels: 'sports-games',
    advancedOrdering: 'LiveFirst',
    maxItems: 10
  }),
  contentType: 'video',
  videoFilters: filters.liveOnly()
});

// Upcoming schedule
const schedule = BlazeSDK.WidgetGridView('schedule-container', {
  dataSource: BlazeSDK.DataSourceBuilder().labels({
    labels: 'sports-games',
    orderType: 'OldestFirst',
    maxItems: 20
  }),
  contentType: 'video',
  videoFilters: filters.upcomingOnly()
});

// Replays library
const replays = BlazeSDK.WidgetRowView('replays-container', {
  dataSource: BlazeSDK.DataSourceBuilder().labels({
    labels: 'sports-games',
    orderType: 'RecentlyUpdatedFirst',
    maxItems: 20
  }),
  contentType: 'video',
  videoFilters: filters.endedOnly()
});

Did this page help you?