Skip to content

Storyteller instance#

Storyteller.sharedInstance is the SDK singleton. You use it to initialize the SDK, set the global delegate, theme, and privacy options, and open Stories or Clips from your own code. Storyteller.User is a second singleton that stores user attributes and followed categories. The SDK creates both when the script or package loads.

Members at a glance#

Storyteller.sharedInstance has these properties:

Property Type Access
version string Read
isInitialized boolean Read-only
isPlayerVisible (deprecated) boolean Read-only
isPresentingContent boolean Read-only
isPlayerMuted boolean Read-only
delegate IStorytellerDelegate Read and write
theme Subset<IUiTheme> Read and write
currentTheme IStorytellerTheme Read-only
uiStyle UiStyle Read-only
eventTrackingOptions StorytellerEventTrackingOptions Read and write
customInstanceHost string Write-only
currentApiKey string or null Read-only

It has these methods:

Method Returns
initialize(apiKey, userInput?) Promise<void>
getStoriesCount(categoryIds) Promise<number>
getClipsCount(collectionId) Promise<number>
openDeepLink(url, options?) Promise<boolean>
openStory(id) Promise<void>
openStoryByExternalId(externalId) Promise<void>
openPage(pageId) Promise<void>
openCategory(categoryId, storyId?) Promise<void>
openCollection(collectionId, destination?, openedReason?) Promise<void>
openClipByExternalId(collectionId, externalId) Promise<void>
dismissPlayer(animated, reason?) void
disablePlayback() void
enablePlayback() void
enableLogging() void

Deprecated members and a note on internal members are at the end of Methods.

Properties#

These properties are on Storyteller.sharedInstance.

version#

version: string

The SDK version, such as '11.1.0'. See Use additional SDK methods.

isInitialized#

get isInitialized(): boolean

true after an initialize call succeeds. Once true, it stays true for the rest of the page session, including while a later initialize call runs.

isPlayerVisible#

get isPlayerVisible(): boolean

Deprecated in 11.1.0. Use isPresentingContent instead.

Returns the same value as isPresentingContent. A StorytellerClipsPlayerView or StorytellerEmbeddedClipsPlayerView on your page doesn't make it true.

isPresentingContent#

get isPresentingContent(): boolean

true while a Story player or Clips player that the SDK opened covers your page. It stays true when the user moves from one player to another inside a player. When your page calls an open method or openDeepLink for the other player, the SDK closes the open player first, so the value is briefly false. A StorytellerClipsPlayerView or StorytellerEmbeddedClipsPlayerView on your page doesn't make it true.

When the value changes, the SDK calls the global delegate's onPlayerPresented or onPlayerDismissed.

isPlayerMuted#

get isPlayerMuted(): boolean

true when the Story or Clips player is muted. While a player plays, the value is the sound state the user hears, including a mute that the browser forces. Before any player opens, the value is true. After a player closes, the value keeps that player's last state.

The SDK doesn't notify you when the value changes.

delegate#

get delegate(): IStorytellerDelegate
set delegate(delegateObj: IStorytellerDelegate)

The global callbacks for Stories, Clips, analytics, sharing, ads, in-app links, category follows, and players opening and closing. Assigning an object replaces all eight callbacks, so a callback that you leave out is cleared. Reading the property returns a new object that holds the current callbacks, so you can spread it to add one callback and keep the others:

Storyteller.sharedInstance.delegate = {
  ...Storyteller.sharedInstance.delegate,
  onPlayerPresented: () => {
    document.querySelector('video')?.pause();
  },
};
  • Type: IStorytellerDelegate
  • Since: 10.0.0 moved the delegate to the shared instance. 11.1.0 added getBottomBannerAdConfig, categoryFollowActionTaken, onPlayerPresented, and onPlayerDismissed
  • Guide: Handle global callbacks

theme#

get theme(): Subset<IUiTheme>
set theme(theme: Subset<IUiTheme>)

The global theme for every view. Pass a UiTheme or a plain object with optional light and dark themes. IUiTheme is the shape of UiTheme; the SDK doesn't export it by name. A view's configuration.theme overrides the global theme for that view.

Note

Each initialize call replaces the global theme with a default UiTheme. Set theme after initialize resolves, and set it again after a later initialize call, such as a user change.

await Storyteller.sharedInstance.initialize('demo-api-key');

Storyteller.sharedInstance.theme = new Storyteller.UiTheme({
  light: { colors: { primary: '#1C62EB' } },
});

currentTheme#

get currentTheme(): IStorytellerTheme

The resolved global Theme for the current color scheme. IStorytellerTheme is the shape of Theme; the SDK doesn't export it by name. The SDK picks the light or dark theme from theme, fills unset values with SDK defaults, and rebuilds it when the system color scheme changes. The value exists after initialize runs or after you assign theme.

uiStyle#

get uiStyle(): UiStyle

The UiStyle of the global theme. Its value is always UiStyle.auto, so the global theme follows the system color scheme. The SDK also uses it for the players it creates when an open method or a hash URL finds no matching view on the page. Set a view's style with configuration.uiStyle.

eventTrackingOptions#

get eventTrackingOptions(): StorytellerEventTrackingOptions
set eventTrackingOptions(newOptions: Partial<StorytellerEventTrackingOptions>)

The privacy and tracking options. Every option defaults to true, and disabledFunctionalFeatures defaults to [].

Assigning an object replaces every option: a field that you leave out returns to its default. To change one option, spread the current value:

Storyteller.sharedInstance.eventTrackingOptions = {
  ...Storyteller.sharedInstance.eventTrackingOptions,
  enableAdTracking: false,
};

Reading the property returns the effective values. When enableFunctionalCookies is false, enablePersonalization and enableStorytellerTracking read as false. Set the options before initialize when enableRemoteViewingStore must apply to the stored user ID.

customInstanceHost#

set customInstanceHost(customInstanceHost: string)

Sets the API host for SDK requests in place of the default Storyteller API host. The SDK removes a trailing / and stores the value in local storage under Storyteller.customInstanceHost. The property has no getter, and no task guide covers it.

  • Since: 8.0.0

currentApiKey#

get currentApiKey(): string | null

The API key from the latest initialize call. Before that call, it returns the key stored in local storage from an earlier page load, or null when no key is stored.

Methods#

These methods are on Storyteller.sharedInstance.

initialize#

initialize(apiKey: string, userInput?: UserInput): Promise<void>

Starts the SDK for an API key and user. Create views after the promise resolves.

Parameter Type Required Default Description
apiKey string Yes None Your Storyteller Web SDK API key
userInput UserInput No {} User options. Pass a plain object such as { externalId: 'user-id' }

UserInput has one optional field, externalId:

class UserInput {
  constructor(public externalId?: string | null) {}
}
externalId value Result
A string Sets the current user. The SDK stores a SHA-256 hash of the ID. A new ID resets the user data stored in the browser, including user attributes
null Clears the user ID and resets the stored user data
Omitted Keeps the stored user ID. The SDK creates a random ID when none is stored, or when apiKey differs from the previous key

When eventTrackingOptions.enableRemoteViewingStore is false, the SDK deletes the stored user ID and ignores externalId.

The call behaves as follows:

  • Concurrent calls with the same apiKey and externalId return the same promise. A call with different values waits for the active call to settle, then runs
  • After a successful call, later calls apply the new user and resolve without a new Settings request. With logging enabled, the SDK logs Storyteller has already been initialized. Reusing the existing instance.
  • The SDK records the sdkInitialized activity event after the Settings request succeeds or fails

The promise rejects with these values:

Condition Rejection value
apiKey is empty and the SDK is not initialized The string Storyteller couldn't be initialized because no API key was provided.
The Settings request returns HTTP 401 or 404 An Error whose message starts with InvalidApiKeyError
The Settings request returns HTTP 408 An Error whose message starts with NetworkTimeoutError
Any other Settings failure, including an empty response An Error whose message starts with NetworkError
Saving the user ID fails, or the request for the user's viewing history fails The error from that step. The SDK doesn't send sdkInitialized

The error classes are not exported. Check the message prefix to tell them apart.

try {
  await Storyteller.sharedInstance.initialize('demo-api-key', {
    externalId: 'user-id',
  });
} catch (error) {
  console.error('Storyteller could not start.', error);
}

getStoriesCount#

getStoriesCount(categoryIds: string[]): Promise<number>

Returns the number of available Stories in the given categories. The SDK sends one count request per category and adds the results.

Parameter Type Required Default Description
categoryIds string[] Yes None Story category IDs
  • Returns: the total count. An empty array resolves to 0 at once, without a request
  • Waits: until an initialize call succeeds. The promise stays pending until then
  • Rejects: when a count request fails, or a response is empty or has no numeric count
  • Since: 10.13.16
  • Guide: Use additional SDK methods

getClipsCount#

getClipsCount(collectionId: string): Promise<number>

Returns the number of available Clips in a collection.

Parameter Type Required Default Description
collectionId string Yes None Clips collection ID
  • Waits: until an initialize call succeeds. The promise stays pending until then
  • Rejects: with Error('Collection is required to load Clips count') for an empty ID, and when the request fails or the response is empty or has no numeric count
  • Since: 10.13.16
  • Guide: Use additional SDK methods

Open methods#

The open methods show the Story player or the Clips player from your code. They share this behavior:

  1. The SDK looks for the content in the views on the page. It uses only views with URLs enabled, which means the player.disableUrls or clipPlayer.disableUrls theme property is false.
  2. When a view has the content, the SDK sets location.hash to that view's player URL, such as #top-stories/story-id.
  3. Otherwise, the SDK loads the content from the API and opens it in a player it creates, at #stories/... or #clips/....
  4. The promise resolves once the SDK has opened the player by setting location.hash. It rejects when the SDK cannot load the content or the content does not exist.

The rejection value can be an Error or a string. Handle every rejection:

try {
  await Storyteller.sharedInstance.openStory('story-id');
} catch (error) {
  console.error('The Story could not be opened.', error);
}

Call the open methods after initialize resolves. See Basename for the hash URL format.

openDeepLink(url: string, options?: OpenDeepLinkOptions): Promise<boolean>

Opens the Story, Page, category, Clip, or collection that a Storyteller content URL points to.

Parameter Type Required Default Description
url string Yes None A Storyteller content URL, or a player hash such as #clips/collection-id. See supported URL formats
options OpenDeepLinkOptions No None context to report in the events of this opening
  • Returns: false when the URL isn't a supported Storyteller link, and nothing opens. true once the SDK has found the content and opened the player route; the player then renders
  • Rejects: when the content can't be loaded, when a Clip category URL has no collection ID, and when a Story or Page URL names a category that doesn't contain the Story
  • Since: 11.1.0
  • Guides: Open a content URL, Use additional SDK methods

The events of this opening carry options.context in place of the context configured on the view that opens the content. When you leave out context, the events carry the view's configured context. Events from a player that the SDK creates, because no view on the page has the content, carry none. The SDK passes context only to your callbacks.

To check a URL without opening it, call parseDeepLink.

openStory#

openStory(id: string): Promise<void>

Opens the Story with this Story ID. Its events report storyPlaybackMode as 'singleStory'.

Parameter Type Required Default Description
id string Yes None Story ID
  • Rejects: when the Story cannot be loaded, or with the string No Story with the provided ID was found.
  • Since: 10.7.0 made the method async
  • Guide: Use additional SDK methods

openStoryByExternalId#

openStoryByExternalId(externalId: string): Promise<void>

Opens the Story with this external ID. Its events report storyPlaybackMode as 'singleStory'.

Parameter Type Required Default Description
externalId string Yes None Story external ID
  • Rejects: when the Story cannot be loaded, or with the string No Story with the provided External ID was found.
  • Since: 10.7.0
  • Guide: Use additional SDK methods

openPage#

openPage(pageId: string): Promise<void>

Opens the Story that contains this Page, starting at the Page.

Parameter Type Required Default Description
pageId string Yes None Story Page ID

openCategory#

openCategory(categoryId: string, storyId?: string): Promise<void>

Opens the Story player for a category. On the page, the SDK uses a Stories view whose only category is categoryId.

Parameter Type Required Default Description
categoryId string Yes None Story category ID
storyId string No None Story to open first. When it is missing or not in the category, the first Story in the category opens

openCollection#

openCollection(
  collectionId: string,
  destination?: {
    categoryId?: string;
    clipId?: string;
    initialFeed?: ClipFeed;
  },
  openedReason?: OpenedReason.deepLink
): Promise<void>

Opens the Clips player for a collection.

Parameter Type Required Default Description
collectionId string Yes None Clips collection ID
destination { categoryId?: string; clipId?: string; initialFeed?: ClipFeed } No None Clip or Clip category to show first. clipId takes priority when you pass both. When the destination is missing or not found, the first Clip in the collection opens
openedReason OpenedReason.deepLink No None The OpenedReason of the first Clip's openedClip event. OpenedReason.deepLink is the only accepted value

Without openedReason, the first Clip reports openedReason: deepLink, unless the open lands on a Category (destination.categoryId): then it reports categoryListTap. Pass Storyteller.OpenedReason.deepLink to make a Category open report deepLink too. openDeepLink always reports deepLink.

destination.initialFeed takes a ClipFeed: 'forYou', the default, or 'following'. 'following' opens the Following tab of a collection that has the For You and Following tabs. The SDK ignores it and logs a warning when you also pass clipId or categoryId. A collection without the tabs opens For You and logs a warning.

openClipByExternalId#

openClipByExternalId(collectionId: string, externalId: string): Promise<void>

Opens the Clips player for a collection at the Clip with this external ID. When no view on the page has the Clip, the SDK loads collection pages until it finds the Clip, up to 100 pages.

Parameter Type Required Default Description
collectionId string Yes None Clips collection ID
externalId string Yes None Clip external ID
  • Rejects: when the collection cannot be loaded, or with a string message when the collection does not contain the Clip
  • Since: 10.7.0
  • Guide: Use additional SDK methods

dismissPlayer#

dismissPlayer(animated: boolean, reason?: string): void

Closes the open Story player or Clips player, and any StorytellerClipsPlayerView on your page. It has no effect when neither is showing. The dismissedStory or dismissedClip event reports DismissedReason.instanceMethod. When you pass a reason, the event also reports it in customDismissedReason. A StorytellerEmbeddedClipsPlayerView ignores this call.

Parameter Type Required Default Description
animated boolean Yes None true plays the close animation
reason string No None Your reason for closing the player, reported as customDismissedReason. The SDK ignores an empty or whitespace-only string. Don't include personal data

disablePlayback#

disablePlayback(): void

Pauses the open Story player and the active Clip video. Players that open while playback is disabled stay paused.

enablePlayback#

enablePlayback(): void

Allows playback again after disablePlayback, and resumes the open Story player and the active Clip. Playback is enabled by default.

enableLogging#

enableLogging(): void

Turns on SDK info, warning, and log messages in the browser console. The SDK always writes errors to the console, with or without this call.

Deprecated members#

These members still work in 11.1.0. Replace them with the members listed:

Member Behavior Replacement
openClip(id: string, onError?: (message: string) => void): void Opens a Clip that a Clips view on the page has loaded. Calls onError with a message when no view has the Clip openCollection or openClipByExternalId
enableEventTracking(): void Sets every tracking option to its default eventTrackingOptions
disableEventTracking(): void Sets every tracking option to its default, except enableStorytellerTracking: false eventTrackingOptions
get currentUserId(): string Always returns ''. Deprecated in 10.11.0 None
get isPlayerVisible(): boolean Returns the value of isPresentingContent. Deprecated in 11.1.0 isPresentingContent

Internal members#

The type declarations also show members whose names end in _. They are for the SDK's own use. Don't call them.

Storyteller.User#

Storyteller.User stores user attributes for personalization and audience targeting. The SDK keeps them in local storage and adds them to its content requests. It also manages the categories that the user follows.

Storyteller.User.setUserAttribute('location', 'New York');

Set attributes after initialize resolves. A new externalId in initialize clears the stored attributes and followed categories. See Identify and personalize users and Followed categories.

Member Returns
setUserAttribute(key, value) true, -1, or undefined
setUserAttributes(attributes) void
getUserAttribute(key) string or undefined
getUserAttributes() Record<string, string>
removeUserAttribute(key) void
setLocale(locale) void
locale string or undefined
followedCategories string[]
isCategoryFollowed(categoryId) boolean
addFollowedCategory(categoryId) Promise<void>
addFollowedCategories(categoryIds) Promise<void>
removeFollowedCategory(categoryId) Promise<void>
removeFollowedCategories(categoryIds) Promise<void>
setFollowedCategories(categoryIds) Promise<void>
getFollowableCategories() Promise<StorytellerFollowableCategories>

Storyteller.User also has a public parseUserAttributesToQueryStringAlphabetically(): string method. The SDK calls it to build the user attribute query string for its content requests, so you don't need to call it.

setUserAttribute#

setUserAttribute(key: string, value: string): true | -1 | undefined

Stores one attribute. An existing value for the key is replaced.

Parameter Type Required Default Description
key string Yes None Attribute name
value string Yes None Attribute value
  • Returns: true when the attribute is stored. undefined when eventTrackingOptions.enablePersonalization is false: the SDK does not store the attribute and logs a warning, which shows when logging is enabled. -1 when the SDK stored the attribute but reading it back returns no value
  • Throws: Error('Key and value are required when setting user attributes') when key or value is empty
  • Guide: Setting User Attributes

setUserAttributes#

setUserAttributes(attributes: Record<string, string>): void

Replaces all custom attributes in one update. Stored keys that attributes leaves out are removed, and {} removes them all. The locale from setLocale stays unless attributes includes stLocale. When the new set equals the stored set, the SDK doesn't store it again, so open Stories don't reload.

Parameter Type Required Default Description
attributes Record<string, string> Yes None The complete set of attributes. A plain object, or one made with Object.create(null), whose keys and values are non-empty strings
  • Throws: an Error, before anything changes, when attributes isn't a plain object, when a key or value is empty or a value isn't a string, or when a key is __proto__
  • Personalization off: when eventTrackingOptions.enablePersonalization is false, the SDK checks the input, stores nothing, and logs a warning
  • Since: 11.1.0
  • Guide: Replace all user attributes

getUserAttribute#

getUserAttribute(key: string): string | undefined

Returns the stored value for key, or undefined when none is stored.

getUserAttributes#

getUserAttributes(): IUserAttributes

Returns all stored attributes as an object. IUserAttributes is Record<string, string>. Returns {} when none are stored.

removeUserAttribute#

removeUserAttribute(key: string): void

Removes one attribute.

setLocale#

setLocale(locale: string): void

Sets the Clips locale. The SDK stores it as the stLocale user attribute, so it follows the same rules as setUserAttribute.

Parameter Type Required Default Description
locale string Yes None Language code, such as 'es'

locale#

get locale(): string | undefined

The stored stLocale attribute, or undefined.

followedCategories#

get followedCategories(): string[]

The IDs of the categories that the user follows. With app-managed following, the IDs keep the order in which the user followed them. Returns [] when eventTrackingOptions.enablePersonalization is false. Reading it doesn't make a request.

isCategoryFollowed#

isCategoryFollowed(categoryId: string): boolean

Returns true when the user follows the category. The comparison ignores case, and it doesn't make a request.

Parameter Type Required Default Description
categoryId string Yes None Category external ID

addFollowedCategory#

addFollowedCategory(categoryId: string): Promise<void>

Follows one category. It behaves like addFollowedCategories with one ID.

Parameter Type Required Default Description
categoryId string Yes None Category external ID

addFollowedCategories#

addFollowedCategories(categoryIds: string[]): Promise<void>

Follows categories when your tenant uses app-managed following. IDs match without regard to case. IDs that the user already follows are skipped without a request. For the other IDs, the SDK looks up each category's type from Storyteller and skips IDs that Storyteller doesn't return.

Parameter Type Required Default Description
categoryIds string[] Yes None Category external IDs
  • Waits: until an initialize call succeeds. The promise stays pending until then
  • No change: the promise resolves without changes with Storyteller-managed following, when eventTrackingOptions.enablePersonalization is false, and when the user changes or personalization is turned off before the call runs
  • Rejects: with a TypeError when the input is not category ID strings. When the category lookup fails, with an Error whose message starts with NetworkError, NetworkTimeoutError, or InvalidApiKeyError, the same errors that initialize uses. The followed categories don't change when the promise rejects
  • Since: 11.1.0
  • Guide: Follow and unfollow categories

removeFollowedCategory#

removeFollowedCategory(categoryId: string): Promise<void>

Unfollows one category. It behaves like removeFollowedCategories with one ID.

Parameter Type Required Default Description
categoryId string Yes None Category external ID

removeFollowedCategories#

removeFollowedCategories(categoryIds: string[]): Promise<void>

Unfollows categories when your tenant uses app-managed following. IDs match without regard to case. The SDK changes the follows on the device and doesn't make a request.

Parameter Type Required Default Description
categoryIds string[] Yes None Category external IDs
  • Waits: until an initialize call succeeds. The promise stays pending until then
  • No change: the promise resolves without changes with Storyteller-managed following, when eventTrackingOptions.enablePersonalization is false, and when the user changes or personalization is turned off before the call runs
  • Rejects: with a TypeError when the input is not category ID strings
  • Since: 11.1.0
  • Guide: Follow and unfollow categories

setFollowedCategories#

setFollowedCategories(categoryIds: string[]): Promise<void>

Replaces the whole set of followed categories when your tenant uses app-managed following. The SDK looks up the categories from Storyteller and drops IDs that Storyteller doesn't return. An empty array clears the followed categories without a request.

Parameter Type Required Default Description
categoryIds string[] Yes None The complete list of category external IDs that the user follows
  • Waits: until an initialize call succeeds. The promise stays pending until then
  • No change: the promise resolves without changes with Storyteller-managed following, when eventTrackingOptions.enablePersonalization is false, and when the user changes or personalization is turned off before the call runs
  • Rejects: with a TypeError when the input is not category ID strings, and with the addFollowedCategories errors when the lookup fails. The previous followed categories remain when the promise rejects
  • Since: 11.1.0
  • Guide: Replace the followed categories

getFollowableCategories#

getFollowableCategories(): Promise<StorytellerFollowableCategories>

Returns the categories that your tenant lets users follow, with whether the current user follows each one. It works with both following models.