Interface H5PObject

This is an interface which represents the window.H5P, or simply H5P, object in the H5P Core library. The object works as a namespace for a lot of utilities and classes that are used when creating both widgets and content types in H5P.

interface H5PObject {
    $body: JQuery<HTMLBodyElement>;
    $window: JQuery<Window>;
    ClipboardItem: typeof H5PClipboardItem;
    ConfirmationDialog: typeof H5PConfirmationDialog;
    ContentCopyrights: typeof H5PContentCopyrights;
    ContentType: typeof H5PContentType;
    Coords: typeof H5PCoords;
    DefinitionList: typeof H5PDefinitionList;
    Dialog: typeof H5PDialog;
    EventDispatcher: typeof EventDispatcher;
    Field: typeof H5PFieldClass;
    MediaCopyright: typeof H5PMediaCopyright;
    Thumbnail: typeof H5PThumbnail;
    Tooltip: typeof H5PTooltip;
    Version: typeof H5PVersion;
    canHasFullscreen: boolean;
    communicator: undefined | H5PCommunicator;
    copyrightLicenses: H5PCopyrightLicenses;
    externalEmbed?: boolean;
    fullScreenBrowserPrefix: undefined | "" | "webkit" | "moz" | "ms";
    fullscreenSupported: boolean;
    instances: IH5PContentType<unknown>[];
    isFramed: boolean;
    isFullscreen: boolean;
    jQuery: JQueryStatic;
    opened: Record<H5PContentId, Date>;
    preventInit?: boolean;
    safariBrowser?: number;
    addQueryParameter(path, parameter): string;
    attachToastTo(element, message, config?): void;
    buildMetadataCopyrights(metadata): H5PMediaCopyright;
    classFromName(name): IH5PContentType<unknown>;
    clipboardify<TParams>(clipboardItem): void;
    cloneObject<T>(object, recursive?): T;
    createTitle(rawTitle, maxLength?): string;
    createUUID(): string;
    cssLoaded(path): boolean;
    deleteUserData(contentId, dataId, subContentId?): void;
    error(error): void;
    exitFullScreen(): void;
    findCopyrights(info, parameters, contentId, extras?): void;
    fullScreen($element, instance, exitCallback?, body?, forceSemiFullScreen?): void;
    getClipboard(): undefined | {
        generic?: unknown;
    } & Record<string, unknown>;
    getContentForInstance(contentId?): undefined | {
        contentUserData?: unknown[];
        displayOptions?: H5PDisplayOptions;
        embedCode?: string;
        exportUrl: string;
        fullScreen: "0" | "1";
        jsonContent?: string;
        library: string;
        metadata: H5PMetadata;
        resizeCode: string;
        scripts: undefined | string[];
        styles: undefined | string[];
        title: string;
        url: string;
    };
    getContentPath(contentId): string;
    getCopyrights<TContentType>(instance, parameters, contentId, metadata): undefined | string;
    getCrossOrigin(source): null | string;
    getCrossOrigin(source): undefined | string;
    getLibraryConfig(machineName): unknown;
    getLibraryPath(library): string;
    getPath(path, contentId): string;
    getUserData(contentId, dataId, done, subContentId?): void;
    init(target): void;
    isEmpty(value): boolean;
    jsLoaded(path): boolean;
    libraryFromString<TLibraryName, TMajorVersion, TMinorVersion>(library): false | {
        machineName: TLibraryName;
        majorVersion: TMajorVersion;
        minorVersion: TMinorVersion;
    };
    newRunnable<TLibraryParam, TState>(library, contentId, $attachTo?, skipResize?, extras?): IH5PContentType<unknown> & {
        $: JQueryStatic;
        libraryInfo: H5PLibraryInfo;
        subContentId: TLibraryParam["subContentId"];
    };
    on<TData>(instance, eventType, handler): void;
    openEmbedDialog($element, embedCode, resizeCode, size): void;
    openReuseDialog($element, contentData, library, instance, contentId): void;
    semiFullScreen($element, instance, exitCallback, $body): void;
    setClipboard<TParams>(clipboardItem): void;
    setFinished(contentId, score, maxScore, time?): void;
    setSource(element, source, contentId): void;
    setUserData(contentId, dataId, data, extras?): void;
    shuffleArray<T>(array): T[];
    t(key, placeholderVars?, namespace?): string;
    trigger<TData>(instance, eventType, data, extras): void;
    trim(value): string;
}

Properties

$body: JQuery<HTMLBodyElement>
$window: JQuery<Window>

A jQuery wrapper around window.

ClipboardItem: typeof H5PClipboardItem
ConfirmationDialog: typeof H5PConfirmationDialog
ContentCopyrights: typeof H5PContentCopyrights

Copyrights for an H5P Content Library

ContentType: typeof H5PContentType

H5P.ContentType is a base class for all content types. Used by newRunnable().

Functions here may be overridable by the libraries. In special cases, it is also possible to override H5P.ContentType on a global level.

NOTE that this doesn't actually 'extend' the event dispatcher but instead it creates a single instance which all content types shares as their base prototype. (in some cases this may be the root of strange event behavior)

Coords: typeof H5PCoords

Deprecated

Helper object for keeping coordinates in the same format all over.

DefinitionList: typeof H5PDefinitionList
Dialog: typeof H5PDialog
EventDispatcher: typeof EventDispatcher
Field: typeof H5PFieldClass

Simple data structure class for storing a single field

MediaCopyright: typeof H5PMediaCopyright

An ordered list of copyright fields for media

Thumbnail: typeof H5PThumbnail

A simple and elegant class for creating thumbnails of images

Tooltip: typeof H5PTooltip

Create an accessible tooltip

Since

1.25 / moodle-1.23

Version: typeof H5PVersion
canHasFullscreen: boolean

Deprecated

Use fullscreenSupported instead

communicator: undefined | H5PCommunicator

When embedded, the communicator helps talk to the parent page.

copyrightLicenses: H5PCopyrightLicenses

Maps copyright license codes to their human readable counterpart.

externalEmbed?: boolean

Indicates if H5P is embedded on an external page using iframe.

fullScreenBrowserPrefix: undefined | "" | "webkit" | "moz" | "ms"

If the current browser supports Element#requestFullscreen, this property will be set to an empty string.

If the current browser does not support Element#requestFullscreen but has a vendor-prefixed version of it, this property will contain the prefix.

If the current browser does not support fullscreen mode at all, this property will be undefined.

fullscreenSupported: boolean

True if the current browser supports fullscreen mode.

instances: IH5PContentType<unknown>[]

A list over H5P instances on the current page.

isFramed: boolean

True if H5P content is rendered inside an iframe.

isFullscreen: boolean

True if H5P content is in fullscreen mode.

Use H5P.fullscreen() or H5P.semiFullScreen() to enter fullscreen mode. Use H5P.exitFullScreen() to exit fullscreen mode.

jQuery: JQueryStatic

Keeps track of when each H5P content instance was initiated.

preventInit?: boolean

Prevent H5P Core from initializing. Must be overriden before document ready.

safariBrowser?: number

Is set to the Safari version number if the current browser is Safari (but only if it does not support fullscreen mode).

Methods

  • Helper for adding a query parameter to an existing path that may already contain one or a hash.

    Parameters

    • path: string

      URL to add query parameter to.

    • parameter: string

      Query parameter to add on the format key1=value1&key2=value2.

    Returns string

    Example: No existing query parameter

    const path = "https://example.com";
    const parameter = "foo=bar";

    const result = H5P.addQueryParameter(path, parameter);
    // result === "https://example.com?foo=bar"

    Example: With existing query parameter

    const path = "https://example.com?foo=bar";
    const parameter = "baz=qux";

    const result = H5P.addQueryParameter(path, parameter);
    // result === "https://example.com?foo=bar&baz=qux"

    Example: Multiple parameters

    const path = "https://example.com?foo=bar";
    const parameter = "baz=qux&quux=quuz";

    const result = H5P.addQueryParameter(path, parameter);
    // result === "https://example.com?foo=bar&baz=qux&quux=quuz"

    Example: With hash

    const path = "https://example.com#foo";
    const parameter = "bar=baz";

    const result = H5P.addQueryParameter(path, parameter);
    // result === "https://example.com?bar=baz#foo"
  • Show a toast message.

    The reference element could be DOM elements the toast should be attached to, or e.g. the document body for general toast messages.

    Parameters

    • element: HTMLElement

      Reference element to show toast message for.

    • message: string

      Message to show.

    • Optional config: {
          duration?: number;
          position: {
              horizontal?: "left" | "right" | "before" | "centered" | "after";
              noOverflowBottom?: boolean;
              noOverflowLeft?: boolean;
              noOverflowRight?: boolean;
              noOverflowTop?: boolean;
              noOverflowX?: boolean;
              noOverflowY?: boolean;
              offsetHorizontal?: number;
              offsetVertical?: number;
              overflowReference?: HTMLElement;
              vertical?: "top" | "bottom" | "centered" | "above" | "below";
          };
          style?: string;
      }

      Configuration.

      • Optional duration?: number

        Toast message length in ms. Default: 3000

      • position: {
            horizontal?: "left" | "right" | "before" | "centered" | "after";
            noOverflowBottom?: boolean;
            noOverflowLeft?: boolean;
            noOverflowRight?: boolean;
            noOverflowTop?: boolean;
            noOverflowX?: boolean;
            noOverflowY?: boolean;
            offsetHorizontal?: number;
            offsetVertical?: number;
            overflowReference?: HTMLElement;
            vertical?: "top" | "bottom" | "centered" | "above" | "below";
        }

        Relative positioning of the toast.

        • Optional horizontal?: "left" | "right" | "before" | "centered" | "after"
        • Optional noOverflowBottom?: boolean
        • Optional noOverflowLeft?: boolean
        • Optional noOverflowRight?: boolean
        • Optional noOverflowTop?: boolean
        • Optional noOverflowX?: boolean
        • Optional noOverflowY?: boolean
        • Optional offsetHorizontal?: number
        • Optional offsetVertical?: number
        • Optional overflowReference?: HTMLElement
        • Optional vertical?: "top" | "bottom" | "centered" | "above" | "below"
      • Optional style?: string

        Id for the tooltip. Default: h5p-toast

    Returns void

    Example

    const parentElement = document.body
    const message = "Hello world!"

    H5P.attachToastTo(parentElement, message)
  • Store item in the H5P Clipboard

    Type Parameters

    • TParams extends Record<string, unknown> = Record<string, unknown>

    Parameters

    Returns void

  • Recursively clone the given object

    Type Parameters

    • T

    Parameters

    • object: T

      Object to clone

    • Optional recursive: boolean

    Returns T

    A clone of object

  • Create title as an HTML string

    Parameters

    • rawTitle: string
    • Optional maxLength: number

      Default: 60

    Returns string

  • Returns string

  • Check if styles path/key is loaded

    Parameters

    • path: string

    Returns boolean

  • Private

    Delete user data for given content

    Parameters

    • contentId: H5PContentId

      What content to remove data for

    • dataId: string

      Identifies the set of data for this content

    • Optional subContentId: H5PContentId

      Identifies which data belongs to sub content

    Returns void

  • Parameters

    Returns void

  • Returns void

  • Gather a flat list of copyright information from the given parameters.

    Parameters

    • info: H5PContentCopyrights

      Used to collect all information in.

    • parameters: Record<string, {
          library?: string | {
              library: string;
          };
      } & Partial<H5PMedia> | ({
          library?: string | {
              library: string;
          };
      } & Partial<H5PMedia>)[]> | ({
          library?: string | {
              library: string;
          };
      } & Partial<H5PMedia>)[]

      To search for file objects in.

    • contentId: H5PContentId

      Used to insert thumbnails for images.

    • Optional extras: {
          machineName: string;
          metadata: H5PMetadata;
      }

      Extras.

      • machineName: string

        Library name of some kind. Metadata of the content instance.

      • metadata: H5PMetadata

        Metadata

    Returns void

  • Parameters

    • $element: JQuery<HTMLElement>
    • instance: IH5PContentType<unknown>
    • Optional exitCallback: (() => void)
        • (): void
        • Returns void

    • Optional body: JQuery<HTMLElement>
    • Optional forceSemiFullScreen: boolean

    Returns void

  • Returns undefined | {
        generic?: unknown;
    } & Record<string, unknown>

  • Function for getting content for a certain ID

    Parameters

    Returns undefined | {
        contentUserData?: unknown[];
        displayOptions?: H5PDisplayOptions;
        embedCode?: string;
        exportUrl: string;
        fullScreen: "0" | "1";
        jsonContent?: string;
        library: string;
        metadata: H5PMetadata;
        resizeCode: string;
        scripts: undefined | string[];
        styles: undefined | string[];
        title: string;
        url: string;
    }

  • Parameters

    Returns string

    Deprecated

    Use getPath instead

  • Gather copyright information for the given content.

    Type Parameters

    Parameters

    • instance: TContentType

      H5P instance to get copyright information for.

    • parameters: TContentType["params"]

      Parameters of the content instance.

    • contentId: H5PContentId

      Identifies the H5P content

    • metadata: H5PMetadata

      Metadata of the content instance.

    Returns undefined | string

    Copyright information.

  • Get the crossOrigin policy to use for img, video and audio tags on the current site.

    Parameters

    • source: string

      URL to the source

    Returns null | string

    crossOrigin attribute value required by the source

    Deprecated

    Use getCrossOrigin with the source as a H5PMedia instead

  • Get the crossOrigin policy to use for img, video and audio tags on the current site. If the source points to external media, or H5PIntegration.crossorigin has a falsy value, undefined will be returned.

    Parameters

    • source: H5PMedia

      File object from parameters/json_content

    Returns undefined | string

    crossOrigin attribute value required by the source

  • Get config for a library

    Parameters

    • machineName: string

    Returns unknown

  • Get the path to the library

    Parameters

    • library: `${string}-${number}.${number}`

      The library identifier in the format "machineName-majorVersion.minorVersion".

    Returns string

    The full path to the library

  • Find the path to the content files based on the id of the content. Also identifies and returns absolute paths

    Parameters

    • path: string

      Relative to content folder or absolute

    • contentId: H5PContentId

      ID of the content requesting the path

    Returns string

    Complete URL to path

  • Private

    Get user data for given content

    Parameters

    • contentId: H5PContentId

      What content to get data for

    • dataId: string

      Identifies the set of data for this content

    • done: ((error?, data?) => void)

      Callback with error and data parameters

        • (error?, data?): void
        • Parameters

          • Optional error: Error
          • Optional data: null | Record<string, unknown>

          Returns void

    • Optional subContentId: H5PContentId

      Identifies which data belongs to sub content

    Returns void

  • Initialize H5P content. Scans for ".h5p-content" in the document and initializes H5P instances where found.

    Parameters

    Returns void

  • Parameters

    • value: unknown

    Returns boolean

    Since

    next version after 1.24.4 (not released as of 2023-12-26)

    Recursive function that detects deep empty structures.

    Will return true if the value is null, undefined, an empty string, an empty array or an empty object. Will also return true if the value is an array or object that contains only empty values.

    Example

    // True for all of:

    H5P.isEmpty({});
    H5P.isEmpty([]);
    H5P.isEmpty("");
    H5P.isEmpty(null);
    H5P.isEmpty(undefined);
    H5P.isEmpty({ a: "" });
    H5P.isEmpty({ a: ["", [], {}] });
    H5P.isEmpty({ a: {} });
    H5P.isEmpty({ a: { b: "" } });
  • Check if JavaScript path/key is loaded

    Parameters

    • path: string

    Returns boolean

  • Type Parameters

    • TData = unknown

    Parameters

    Returns void

  • Display a dialog containing the embed code

    Parameters

    • $element: JQuery<HTMLElement>

      Element to insert dialog after

    • embedCode: string

      The embed code

    • resizeCode: string

      The advanced resize code

    • size: {
          height: number;
          width: number;
      }

      The content's size

      • height: number
      • width: number

    Returns void

  • Display a dialog containing the download button and copy button

    Parameters

    Returns void

  • Enter semi fullscreen for the given H5P instance

    Parameters

    • $element: JQuery<HTMLElement>

      Content container.

    • instance: IH5PContentType<unknown>
    • exitCallback: undefined | (() => void)

      Callback function called when user exits fullscreen.

    • $body: undefined | JQuery<HTMLElement>

      For internal use. Gives the body of the iframe.

    Returns void

  • Set item in the H5P Clipboard

    Type Parameters

    • TParams extends Record<string, unknown>

    Parameters

    Returns void

  • Post finished results for user

    Parameters

    • contentId: H5PContentId

      Identifies the content

    • score: number

      Achieved score/points

    • maxScore: number

      The maximum score/points that can be achieved

    • Optional time: number

      Reported time consumption/usage

    Returns void

    Deprecated

    Do not use this function directly, trigger the finish event instead

  • Helper for setting the crossOrigin attribute + the complete correct source. Note: This will start loading the resource.

    Runs getPath internally.

    Parameters

    Returns void

    Example

    const imageElement = document.createElement("img");
    const image = {
    path: "path/to/image.png",
    };
    const contentId = "1";

    H5P.setSource(imageElement, image, contentId);
    // imageElement.src === "https://example.com/path/to/image.png"
  • Private

    Set user data for given content

    Parameters

    • contentId: H5PContentId

      What content to get data for

    • dataId: string

      Identifies the set of data for this content

    • data: unknown

      The data that is to be stored

    • Optional extras: {
          async?: boolean;
          deleteOnChange?: boolean;
          preloaded?: boolean;
          subContentId?: H5PContentId;
          errorCallback(error): void;
      }

      Extra properties

      • Optional async?: boolean

        Default: true

      • Optional deleteOnChange?: boolean

        If the data should be invalidated when the content changes. Default: false

      • Optional preloaded?: boolean

        If the data should be loaded when content is loaded. Default: true

      • Optional subContentId?: H5PContentId

        Identifies which data belongs to sub content

      • errorCallback:function
        • Callback with error as parameters

          Parameters

          Returns void

    Returns void

  • Shuffle an array in place

    Type Parameters

    • T

    Parameters

    • array: T[]

    Returns T[]

    Deprecated

    Use Array#sort instead

  • Translate text strings.

    Parameters

    • key: string

      Translation identifier, may only contain a-zA-Z0-9. No spaces or special chars.

    • Optional placeholderVars: Record<string, string>

      Data for placeholders.

    • Optional namespace: string

      Translation namespace. Defaults to H5P.

    Returns string

    Translated text

  • Trigger an event on an instance

    Helper function that triggers an event if the instance supports event handling

    Type Parameters

    • TData = unknown

    Parameters

    • instance: EventDispatcher

      Instance of H5P content

    • eventType: unknown

      Type of event to trigger

    • data: TData
    • extras: undefined | {
          bubbles?: boolean;
          external?: boolean;
      }

    Returns void

  • Remove all empty spaces before and after the value

    Parameters

    • value: string

    Returns string

    Deprecated

    Use String#trim instead