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. 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 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>
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) void
disablePlayback() void
enablePlayback() void
enableLogging() void

Deprecated members and an internal member are listed at the end of Methods.

Properties#

These properties are on Storyteller.sharedInstance.

version#

version: string

The SDK version, such as '11.0.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

true while a Story or Clip player is open, and false after it is dismissed.

delegate#

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

The global callbacks for Stories, Clips, analytics, sharing, ads, and in-app links. Assigning an object replaces all four callbacks, so a callback that you leave out is cleared. Reading the property returns a new object that holds the current callbacks.

Storyteller.sharedInstance.delegate = {
  onUserActivityOccurred: (type, data) => {
    console.log(type, data.context);
  },
};

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. 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. 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. The SDK also uses it for the players it creates for the open methods and hash URLs when no matching view exists on the page. On your pages the value is UiStyle.auto. 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
User setup fails The error from that step

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 a Story or Clip 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 default player at #stories/... or #clips/....
  4. The promise resolves after the SDK sets 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.

openStory#

openStory(id: string): Promise<void>

Opens the Story with this Story ID. The Story plays in single-Story mode.

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. The Story plays in single-Story mode.

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 },
  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 } 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 Set by the SDK The OpenedReason reported in analytics events. OpenedReason.deepLink is the only accepted value
  • Rejects: when the collection cannot be loaded
  • Since: 10.7.0 made the method async and added destination
  • Guide: Use additional SDK methods

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): void

Closes the open Story or Clip player. It has no effect when no player is open. The dismissed event reports DismissedReason.instanceMethod. A StorytellerEmbeddedClipsPlayerView ignores this call.

Parameter Type Required Default Description
animated boolean Yes None true plays the close animation

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.0.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

Internal members#

The declarations include requestUserActivityHistory_(): Promise<void>. It reloads the current user's activity history, a step that initialize already runs. No guide documents it, and integrations do not need to call it.

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.

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

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

Member Returns
setUserAttribute(key, value) true, -1, or undefined
getUserAttribute(key) string or undefined
getUserAttributes() Record<string, string>
removeUserAttribute(key) void
setLocale(locale) void
locale string or undefined

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 stored value cannot be read back
  • Throws: Error('Key and value are required when setting user attributes') when key or value is empty
  • Guide: Setting 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.

The declarations also include parseUserAttributesToQueryStringAlphabetically(): string. The SDK uses it to build request query strings from the stored attributes.