Skip to main content
The Vidinfra Player SDK is a lightweight, type safe JavaScript library for controlling embedded video players inside iframes. It uses the postMessage API for secure, real time communication, making custom player integration simple and efficient.

Key Features

  • Unified API: One class manages both controlling existing iframes and embedding new players.
  • Type-safe: Full TypeScript support with comprehensive type definitions for a reliable development - experience.
  • Framework-agnostic: Works seamlessly with any JavaScript framework or plain JavaScript.
  • Secure: Built-in origin validation for postMessage communication to ensure safe interactions.
  • Event-driven: Listen to real-time player events such as play, pause, and time updates.
  • Lightweight: The SDK is approximately 15KB when minified, making it efficient and easy to use.

Installation

NPM Installation

To install the Vidinfra Player SDK via npm, run the following command:
npm install @vidinfra/player

CDN Installation

Alternatively, you can load the SDK via a CDN:
<script src="https://unpkg.com/@vidinfra/player/dist/player.global.js"></script>
This method allows you to use the SDK without needing to install it locally, making it easy to integrate into static or non-Node.js projects.

Quick Start

The Player SDK allows you to control existing iframe players and create embedded players on the fly. Below are the basic instructions for both use cases.

Control an Existing Iframe

If you already have an iframe on your page and want to control the video player inside it, you can easily use the Player class. With just a few lines of code, you can target an existing iframe, wait for it to be ready, and start playing the video.
import { Player } from "@vidinfra/player";

const player = new Player("iframe");

player.on("play", () => {
  console.log("Video started playing");
});

await player.whenReady();
await player.play();

Creating an Embedded Player

If you want to embed a video player directly into your page, Vidinfra can automatically create and inject an iframe for you. You can configure the player with your desired settings like autoplay, volume, and aspect ratio.
import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});

player.setVolume(0.5);
To learn how to copy a video ID, check the Quickstart Guide in the Vidinfra section.

Usage

Controlling an Existing Iframe

If you already have an iframe in your HTML, you can control it by passing the iframe element or a CSS selector.

Javascript

import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();
await player.play();

CDN

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe
  id="vidinfra-iframe-player"
    src="https://player.vidinfra.com/{librayID}/default/{videoID}?autoplay=false&loop=false&muted=false&controls=true&preload=true"
    loading="lazy"
    style="border: none; position: absolute; top: 0; height: 100%; width: 100%;"
    allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"
    allowfullscreen="true">
  </iframe>
</div>

Creating an Embedded Player

You can dynamically create an embedded player by specifying a target element for the player:

Javascript

import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});

CDN

<div id="vidinfra-player"></div>

<script src="https://unpkg.com/@vidinfra/player/dist/player.global.js"></script>
<script>
  const player = new Vidinfra.Player("vidinfra-player", {
    libraryId: default,
    videoId: default,
    playerId: default,
    autoplay: false,
    loop: false,
    muted: false,
    controls: true,
    preload: true,
    aspectRatio: "16:9"
  });
</script>

API Reference

Constructor

new Player(element: HTMLIFrameElement | HTMLElement | string)
new Player(element: HTMLElement | string, options: PlayerOptions)

Parameters

  • element - An iframe element, CSS selector for an iframe, or a container element for embedding
  • options - Configuration options for creating an embedded player (required when creating an embed)

PlayerOptions

The PlayerOptions defines all the customizable settings for configuring a Vidinfra player. Here, you specify key details about the video and player behavior. You can set the videoโ€™s library ID, video ID, and the playerโ€™s size, playback options, and more.
interface PlayerOptions {
  // Vidinfra player (required)
  libraryId: string | number;
  videoId: string | number;
  playerId?: string | number; // Optional, defaults to 'default'

  // Display options
  width?: number | string;
  height?: number | string;
  aspectRatio?: string; // e.g., "16:9", "4:3"

  // Playback options
  autoplay?: boolean;
  loop?: boolean;
  muted?: boolean;
  controls?: boolean;
  preload?: boolean;

  // Advanced options
  loading?: "lazy" | "eager";
  allow?: string;
  className?: string;
  baseUrl?: string;
}

Playback Methods

These methods control the basic playback behavior of the video. They include actions like starting, pausing, seeking, and changing playback speed. Start video playback.
play(): Promise<void>
Pause video playback.
pause(): Promise<void> 
Toggle between play and pause states.
togglePlay(): Promise<void>
Seek to a specific time in seconds.
seek(time: number): Promise<void> 
Set playback speed (e.g., 0.5, 1.0, 2.0).
setPlaybackRate(rate: number): Promise<void> 
Get current playback rate.
getPlaybackRate(): Promise<number> 
Get current playback position in seconds.
getCurrentTime(): Promise<number> 
Get total video duration in seconds.
getDuration(): Promise<number> 
Check if video is currently paused.
getPaused(): Promise<boolean> 

Volume Methods

These methods manage the audio settings for the player. You can adjust the volume, mute, or check the current audio state. Set volume level (0-1).
setVolume(volume: number): Promise<void>
Get current volume level.
getVolume(): Promise<number>
Mute audio.
mute(): Promise<void>
Unmute audio.
unmute(): Promise<void>
Set muted state.
setMuted(muted: boolean): Promise<void>
Get current muted state.
getMuted(): Promise<boolean>

Display Methods

These methods manage the visual behavior of the player, including fullscreen and control visibility. Toggle fullscreen mode.
toggleFullscreen(): Promise<void> 
Enter fullscreen mode.
requestFullscreen(): Promise<void> 
Exit fullscreen mode.
exitFullscreen(): Promise<void> 
Show player controls.
showControls(): Promise<void> 
Hide player controls.
hideControls(): Promise<void> 
Set controls visibility.
setControlsVisible(visible: boolean): Promise<void> 

Watermark Methods

These methods add a watermark to your video, which can be customized with text and styling options. Add a watermark overlay to the video.
addWatermark(config: WatermarkConfig): Promise<void> 
WatermarkConfig:
interface WatermarkConfig {
  text: string;
  color?: string;
  opacity?: number;
  fontSize?: number;
}

Utility Methods

These methods help you interact with the playerโ€™s internal state and configuration. Check if player is ready to receive commands.
isReady(): boolean 
Returns a promise that resolves when the player is ready.
whenReady(): Promise<void>
Get the iframe element.
getIframe(): HTMLIFrameElement
Get the wrapper element (only available for embedded players).
getWrapper(): HTMLElement | null
Get the iframe source URL.
getSrc(): string
Update player options (only available for embedded players).
update(options: Partial<PlayerOptions>): void
Clean up event listeners and remove the player.
destroy(): void

Event Methods

These methods allow you to listen for events like play, pause, and custom player events. Register an event listener.
on(event: string, callback: Function): this
Remove an event listener.
off(event: string, callback?: Function): this
Register a one-time event listener.
once(event: string, callback: Function): this 

Events

The player emits the following events:
EventDescription
readyPlayer is ready to receive commands
playPlayback has started
playingPlayback is playing
pausePlayback has paused
endedPlayback has ended
timeupdatePlayback position changed
volumechangeVolume or muted state changed
seekingSeeking started
seekedSeeking completed
waitingWaiting for data
canplayEnough data to play
canplaythroughCan play through without buffering
loadedmetadataMetadata loaded
loadeddataFrame data loaded
durationchangeDuration changed
ratechangePlayback rate changed
fullscreenchangeFullscreen state changed
errorPlayback error occurred

Examples

Basic Playback Control

import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();

document.getElementById("play-btn").addEventListener("click", () => {
  player.play();
});

document.getElementById("pause-btn").addEventListener("click", () => {
  player.pause();
});

player.on("timeupdate", (state) => {
  const currentTime = Math.floor(state.currentTime);
  const duration = Math.floor(state.duration);
  console.log(`${currentTime}s / ${duration}s`);
});

Volume Control

import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();

const volumeSlider = document.getElementById("volume");
volumeSlider.addEventListener("input", (e) => {
  const volume = e.target.value / 100;
  player.setVolume(volume);
});

const muteBtn = document.getElementById("mute");
muteBtn.addEventListener("click", async () => {
  const isMuted = await player.getMuted();
  player.setMuted(!isMuted);
});

Creating and Controlling an Embed

import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});

player.on("ready", () => {
  console.log("Player created and ready");
});

player.on("play", () => {
  console.log("Video playing");
});

setTimeout(() => {
  player.update({ loop: true });
}, 5000);

TypeScript Example

import { Player, PlayerOptions, WatermarkConfig } from "@vidinfra/player";

const options: PlayerOptions = {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
};

const player = new Player("vidinfra-player", options);

await player.whenReady();

const volume: number = await player.getVolume();
const duration: number = await player.getDuration();

const watermark: WatermarkConfig = {
  text: "Confidential",
  color: "#ffffff",
  opacity: 0.3,
  fontSize: 24
};

await player.addWatermark(watermark);

Security

The Player automatically validates the origin of postMessage communications based on the iframeโ€™s source URL. For iframe-side implementations, you should also validate the origin of incoming messages:
window.addEventListener("message", (event) => {
  const allowedOrigin = "https://trusted-parent.com";
  if (event.origin !== allowedOrigin) return;
  
  // Handle message
});

Browser Support

  • Modern browsers with ES6+ support
  • Requires postMessage API
  • Fullscreen API support varies by browser

TypeScript

Full TypeScript definitions are included with the package:
import { Player, PlayerOptions, WatermarkConfig, WatermarkOptions } from "@vidinfra/player";