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<unknown>[];
    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<unknown>;
    clipboardify<TParams>(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<HTMLElement>, instance: IH5PContentType<unknown>, exitCallback?: (() => void), body?: JQuery<HTMLElement>, 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>(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, TMajorVersion, TMinorVersion>(library: `${TLibraryName} ${TMajorVersion}.${TMinorVersion}`): false | {
        machineName: TLibraryName;
        majorVersion: TMajorVersion;
        minorVersion: TMinorVersion;
    };
    newRunnable<TLibraryParam, TState>(library: TLibraryParam, contentId: H5PContentId, $attachTo?: JQuery<HTMLElement>, skipResize?: boolean, extras?: H5PExtrasWithState<TState>): IH5PContentType<unknown> & {
        $: JQueryStatic;
        libraryInfo: H5PLibraryInfo;
        subContentId: TLibraryParam["subContentId"];
    };
    on<TData>(instance: EventDispatcher, eventType: string, handler: ((event: H5PEvent<TData>) => void)): void;
    openEmbedDialog($element: JQuery<HTMLElement>, embedCode: string, resizeCode: string, size: {
        height: number;
        width: number;
    }): void;
    openReuseDialog($element: JQuery<HTMLElement>, contentData: {
        displayOptions: H5PDisplayOptions;
    }, library: Record<string, unknown>, instance: IH5PContentType<unknown>, contentId: H5PContentId): void;
    semiFullScreen($element: JQuery<HTMLElement>, instance: IH5PContentType<unknown>, exitCallback: undefined | (() => void), $body: undefined | JQuery<HTMLElement>): void;
    setClipboard<TParams>(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>(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<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
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"
        • OptionalnoOverflowBottom?: boolean
        • OptionalnoOverflowLeft?: boolean
        • OptionalnoOverflowRight?: boolean
        • OptionalnoOverflowTop?: boolean
        • OptionalnoOverflowX?: boolean
        • OptionalnoOverflowY?: boolean
        • OptionaloffsetHorizontal?: number
        • OptionaloffsetVertical?: number
        • OptionaloverflowReference?: HTMLElement
        • Optionalvertical?:
              | "top"
              | "bottom"
              | "centered"
              | "above"
              | "below"
      • Optionalstyle?: string

        Id for the tooltip. Default: h5p-toast

    Returns void

    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

    • 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<HTMLElement>
    • instance: IH5PContentType<unknown>
    • OptionalexitCallback: (() => void)
        • (): void
        • Returns void

    • Optionalbody: JQuery<HTMLElement>
    • 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

  • 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

    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

  • 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

    • 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