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>;
    canHasFullscreen: boolean;
    ClipboardItem: typeof H5PClipboardItem;
    communicator: undefined | H5PCommunicator;
    ConfirmationDialog: typeof H5PConfirmationDialog;
    ContentCopyrights: typeof H5PContentCopyrights;
    ContentType: typeof H5PContentType;
    Coords: typeof H5PCoords;
    copyrightLicenses: H5PCopyrightLicenses;
    DefinitionList: typeof H5PDefinitionList;
    Dialog: typeof H5PDialog;
    EventDispatcher: typeof EventDispatcher;
    externalEmbed?: boolean;
    Field: typeof H5PFieldClass;
    fullscreenSupported: boolean;
    instances: IH5PContentType[];
    isFramed: boolean;
    isFullscreen: boolean;
    jQuery: JQueryStatic;
    MediaCopyright: typeof H5PMediaCopyright;
    opened: Record<H5PContentId, Date>;
    preventInit?: boolean;
    safariBrowser?: number;
    Thumbnail: typeof H5PThumbnail;
    Tooltip: typeof H5PTooltip;
    Version: typeof H5PVersion;
    addQueryParameter(path: string, parameter: string): string;
    attachToastTo(
        element: HTMLElement,
        message: string,
        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;
        },
    ): void;
    buildMetadataCopyrights(metadata: H5PMetadata): H5PMediaCopyright;
    classFromName(name: `H5P.${string}`): IH5PContentType;
    clipboardify<
        TParams extends Record<string, unknown> = Record<string, unknown>,
    >(
        clipboardItem: TParams | H5PClipboardItem<TParams>,
    ): void;
    cloneObject<T>(object: T, recursive?: boolean): T;
    createTitle(rawTitle: string, maxLength?: number): string;
    createUUID(): string;
    cssLoaded(path: string): boolean;
    error(error: string | Error): void;
    exitFullScreen(): void;
    findCopyrights(
        info: H5PContentCopyrights,
        parameters:
            | Record<
                string,
                | { library?: string
                | { library: string } } & Partial<H5PMedia>
                | ({ library?: string | { library: string } } & Partial<H5PMedia>)[],
            >
            | ({ library?: string | { library: string } } & Partial<H5PMedia>)[],
        contentId: H5PContentId,
        extras?: { machineName: string; metadata: H5PMetadata },
    ): void;
    fullScreen(
        $element: JQuery,
        instance: IH5PContentType,
        exitCallback?: () => void,
        body?: JQuery,
        forceSemiFullScreen?: boolean,
    ): void;
    getClipboard(): undefined | { generic?: unknown } & Record<string, unknown>;
    getContentForInstance(
        contentId?: H5PContentId,
    ):
        | 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: H5PContentId): string;
    getCopyrights<TContentType extends IH5PContentType<TContentType>>(
        instance: TContentType,
        parameters: TContentType["params"],
        contentId: H5PContentId,
        metadata: H5PMetadata,
    ): undefined | string;
    getCrossOrigin(source: string): null | string;
    getCrossOrigin(source: H5PMedia): undefined | string;
    getLibraryConfig(machineName: string): unknown;
    getLibraryPath(library: `${string}-${number}.${number}`): string;
    getPath(path: string, contentId: H5PContentId): string;
    init(target: HTMLElement): void;
    isEmpty(value: unknown): boolean;
    jsLoaded(path: string): boolean;
    libraryFromString<
        TLibraryName extends string,
        TMajorVersion extends number,
        TMinorVersion extends number,
    >(
        library: `${TLibraryName} ${TMajorVersion}.${TMinorVersion}`,
    ):
        | false
        | {
            machineName: TLibraryName;
            majorVersion: TMajorVersion;
            minorVersion: TMinorVersion;
        };
    newRunnable<
        TLibraryParam extends H5PNewRunnableLibraryParam,
        TState = unknown,
    >(
        library: TLibraryParam,
        contentId: H5PContentId,
        $attachTo?: JQuery,
        skipResize?: boolean,
        extras?: H5PExtrasWithState<TState>,
    ): IH5PContentType & {
        $: JQueryStatic;
        libraryInfo: H5PLibraryInfo;
        subContentId: TLibraryParam["subContentId"];
    };
    on<TData = unknown>(
        instance: EventDispatcher,
        eventType: string,
        handler: (event: H5PEvent<TData>) => void,
    ): void;
    openEmbedDialog(
        $element: JQuery,
        embedCode: string,
        resizeCode: string,
        size: { height: number; width: number },
    ): void;
    openReuseDialog(
        $element: JQuery,
        contentData: { displayOptions: H5PDisplayOptions },
        library: Record<string, unknown>,
        instance: IH5PContentType,
        contentId: H5PContentId,
    ): void;
    semiFullScreen(
        $element: JQuery,
        instance: IH5PContentType,
        exitCallback: undefined | () => void,
        $body: undefined | JQuery,
    ): void;
    setClipboard<TParams extends Record<string, unknown>>(
        clipboardItem: TParams | H5PClipboardItem<TParams>,
    ): void;
    setFinished(
        contentId: H5PContentId,
        score: number,
        maxScore: number,
        time?: number,
    ): void;
    setSource(
        element: HTMLImageElement | HTMLVideoElement | HTMLAudioElement,
        source: H5PMedia,
        contentId: H5PContentId,
    ): void;
    shuffleArray<T>(array: T[]): T[];
    t(
        key: string,
        placeholderVars?: Record<string, string>,
        namespace?: string,
    ): string;
    trigger<TData = unknown>(
        instance: EventDispatcher,
        eventType: unknown,
        data: TData,
        extras: undefined | { bubbles?: boolean; external?: boolean },
    ): void;
    trim(value: string): string;
}

Properties

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

A jQuery wrapper around window.

canHasFullscreen: boolean

Use fullscreenSupported instead

ClipboardItem: typeof H5PClipboardItem
communicator: undefined | H5PCommunicator

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

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

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

copyrightLicenses: H5PCopyrightLicenses

Maps copyright license codes to their human readable counterpart.

DefinitionList: typeof H5PDefinitionList
Dialog: typeof H5PDialog
EventDispatcher: typeof EventDispatcher
externalEmbed?: boolean

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

Field: typeof H5PFieldClass

Simple data structure class for storing a single field

fullscreenSupported: boolean

True if the current browser supports fullscreen mode.

instances: IH5PContentType[]

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
MediaCopyright: typeof H5PMediaCopyright

An ordered list of copyright fields for media

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

Thumbnail: typeof H5PThumbnail

A simple and elegant class for creating thumbnails of images

Tooltip: typeof H5PTooltip

Create an accessible tooltip

1.25 / moodle-1.23

Version: typeof H5PVersion

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

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

    const result = H5P.addQueryParameter(path, parameter);
    // result === "https://example.com?foo=bar"
    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"
    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"
    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.

    • Optionalconfig: {
          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.

      • Optionalduration?: 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.

        • Optionalhorizontal?: "left" | "right" | "before" | "centered" | "after"

          Default: centered

        • OptionalnoOverflowBottom?: boolean

          True to prevent overflow bottom. Default: false

        • OptionalnoOverflowLeft?: boolean

          True to prevent overflow left. Default: false

        • OptionalnoOverflowRight?: boolean

          True to prevent overflow right. Default: false

        • OptionalnoOverflowTop?: boolean

          True to prevent overflow top. Default: false

        • OptionalnoOverflowX?: boolean

          True to prevent overflow left and right. Default: false

        • OptionalnoOverflowY?: boolean

          True to prevent overflow top and bottom. Default: false

        • OptionaloffsetHorizontal?: number

          Extra horizontal offset. Default: 0

        • OptionaloffsetVertical?: number

          Extra vertical offset. Default: 0

        • OptionaloverflowReference?: HTMLElement

          DOM reference for overflow. Default: document.body

        • Optionalvertical?: "top" | "bottom" | "centered" | "above" | "below"

          Default: below

      • Optionalstyle?: string

        Id for the tooltip. Default: h5p-toast

    Returns void

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

    H5P.attachToastTo(parentElement, message)
  • Recursively clone the given object

    Type Parameters

    • T

    Parameters

    • object: T

      Object to clone

    • Optionalrecursive: boolean

    Returns T

    A clone of object

  • Create title as an HTML string

    Parameters

    • rawTitle: string
    • OptionalmaxLength: number

      Default: 60

    Returns string

  • Returns string

  • Check if styles path/key is loaded

    Parameters

    • path: string

    Returns boolean

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

    • Optionalextras: { 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
    • instance: IH5PContentType
    • OptionalexitCallback: () => void
    • Optionalbody: JQuery
    • OptionalforceSemiFullScreen: 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

    Use getPath instead

  • 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

    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

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

    Parameters

    Returns void

  • Parameters

    • value: unknown

    Returns boolean

    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.

    // 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

  • Parse library string into values.

    Type Parameters

    • TLibraryName extends string
    • TMajorVersion extends number
    • TMinorVersion extends number

    Parameters

    Returns
        | false
        | {
            machineName: TLibraryName;
            majorVersion: TMajorVersion;
            minorVersion: TMinorVersion;
        }

    library as an object with machineName, majorVersion and minorVersion properties, or false if the library parameter is invalid

  • Type Parameters

    • TData = unknown

    Parameters

    Returns void

  • Display a dialog containing the embed code

    Parameters

    • $element: JQuery

      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

    Returns void

  • Enter semi fullscreen for the given H5P instance

    Parameters

    • $element: JQuery

      Content container.

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

      Callback function called when user exits fullscreen.

    • $body: undefined | JQuery

      For internal use. Gives the body of the iframe.

    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

    • Optionaltime: number

      Reported time consumption/usage

    Returns void

    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

    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"
  • Shuffle an array in place

    Type Parameters

    • T

    Parameters

    • array: T[]

    Returns T[]

    Use Array#sort instead

  • Translate text strings.

    Parameters

    • key: string

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

    • OptionalplaceholderVars: Record<string, string>

      Data for placeholders.

    • Optionalnamespace: 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

    Use String#trim instead