@vidyard/embed-code

4.3.15 • Public • Published

Vidyard Embed Code

Vidyard Player embed and API

Table of Contents

What is Vidyard Embed Code

The Vidyard embed code helps embed Vidyard players into web pages and applications. It provides programmatic playback control, the ability to listen on playback events, GDPR consent control and integration with third party MAP platforms.

In addition, the Vidyard Embed code is fully responsive (filling the width of the container element by default), it enhances SEO with JSON-LD tags and it improves the accessibility of the player on your page.

By default the Vidyard embed code has 2 components, the embed script and the placeholder image:

  1. The Vidyard Embed script comes in 3 flavours: NPM Package, Script Tag and UMD module hosted on the Vidyard CDN. Only one version needs to be included to allow full access to all the players on that page.
  2. The placeholder image is an <img /> tag that displays the thumbnail of the video and contains data attributes that control how the player is rendered. Each player uses a separate placeholder image.

The Vidyard Embed code is designed to be lightweight and asynchronous. The placeholder image reserves a place in the layout for the video player while minimizing impact on the loading performance of the page.

NPM Package

The Vidyard Embed code can be bundled as an NPM dependency into your project:

npm install --save @vidyard/embed-code
# or using Yarn
yarn add @vidyard/embed-code

Then imported directly in your JavaScript:

import VidyardEmbed from '@vidyard/embed-code';

// render all players from placeholder images in the document
VidyardEmbed.api.renderDOMPlayers();

// render a player programmatically, see method documentation below
VidyardEmbed.api.renderPlayer({...})

Script Tag

Served from the Vidyard Global Content Delivery Network at https://play.vidyard.com/embed/v4.js.

The script tag is auto executing. This means that on script load it will scan the document for Vidyard embed placeholder images and will replace them with Vidyard players.

<!-- The script tag should live in the head of your page if at all possible -->
<script src="https://play.vidyard.com/embed/v4.js" type="text/javascript" async></script>

<!-- Put this wherever you would like your player to appear -->
<img
  style="max-width: 100%;"
  class="vidyard-player-embed"
  src="https://play.vidyard.com/UUID.jpg"
  data-uuid="UUID"
  data-v="4"
  data-type="inline"
/>

UMD Module

The UMD is also available from the Vidyard Global Content Delivery Network at https://play.vidyard.com/embed/v4.umd.js. It will not auto execute when imported, requiring the client to render the players by calling vidyardEmbed.api.renderPlayer or vidyardEmbed.api.renderDOMPlayers.

<!-- The script tag should live in the head of your page if at all possible -->
<script src="https://play.vidyard.com/embed/v4.umd.js" type="text/javascript" async></script>

<!-- Put this wherever you would like your player to appear -->
<img
  style="max-width: 100%;"
  class="vidyard-player-embed"
  src="https://play.vidyard.com/UUID.jpg"
  data-uuid="UUID"
  data-v="4"
  data-type="inline"
/>

<script>
  window['onVidyardAPI'] = (vidyardEmbed) => {
    vidyardEmbed.api.renderDOMPlayers();
  };
</script>

Embed Options

Data Attributes

Included as data attributes on the placeholder image (options must be prepended with data-):

  • data-type: specifies the type of embedlightbox or inline
  • data-uuid: the unique identifier string of the player
  • data-aspect: the aspect ratio of the player landscape, portrait, height / width * 100 (custom value)
  • all other player options, can be found in the Vidyard knowledge base.

Listening to Ready

Note: This only applies to the Embed Script and UMD module embed types (not the NPM Package).

By default, the Embed Script Tag is loaded asynchronously by using the async attribute on the script tag. The client code is notified when the embed code has loaded and is ready to be used using the following methods.

For Internet Explorer 9 we dispatch an onVidyardAPI custom event on document that can be listened to instead of using the global callback:

// initApp is the client's function that interacts with the Vidyard API
window.vidyardEmbed
  ? initApp(window.vidyardEmbed)
  : document.addEventListener('onVidyardAPI', ({ detail: vyApi }) => initApp(vyApi));

Or by adding assigning a callback onto the global onVidyardAPI value that will be called once the embed script is loaded

// initApp is the client's function that interacts with the Vidyard API
// this needs to be defined before the v4 embed script is added to the page
window['onVidyardAPI'] = (vyApi) => initApp(vyApi);

It is a good idea to check for the presence of the API global and fallback to the onVidyardAPI

// initApp is the client's function that interacts with the Vidyard API
// this can be defined anywhere in the client code
window.vidyardEmbed
  ? initApp(window.vidyardEmbed)
  : (window.onVidyardAPI = (vyApi) => initApp(vyApi));

Or with promises:

// this can be defined anywhere in the client code
new Promise(res => window.vidyardEmbed
  ? res(window.vidyardEmbed)
  : (window['onVidyardAPI'] = (vyApi) => res(vyApi))
).then((vyApi) => {
  console.log('The Vidyard API is ready ', vyApi);
});

Unstructured Metadata

To pass unstructured metadata to the player, use the data-vydata attribute. Data attributes use the DOMStringMap format which limits the characters we can use for the key, so all complex nested data is passed as a stringified and URI encoded JSON.

const placeholderImg = document.querySelector("[data-uuid='UUID']");
placeholderImg.setAttribute(
  "data-vydata",
  encodeURIComponent(
    JSON.stringify({
      location: "here",
      more: "yes"
    })
  )
);

Overriding the Player Instance

By default the embed code is pointing at the production instance of play.vidyard.com, this can be overridden by using the data-playbackurl attribute on the script tag.

<script src="https://play.vidyard.com/embed/v4.js" data-playbackurl="play-staging.vidyard.com" type="text/javascript" async ></script>

Or by setting a global variable before including the embed script.

window.VIDYARD_PLAYBACK_URL = 'play-staging.vidyard.com';

Or by calling the debug method

window.vidyardEmbed._debug.setPlaybackURL('play-staging.vidyard.com');

Embed API

The vidyardEmbed named export and the window.VidyardV4 object expose the following APIs:

import vidyardEmbed from '@vidyard/embed-code';

const {
  api: {
    GDPR: { consent, hasConsentOnReady },
    addReadyListener,
    getPlayerMetadata,
    getPlayersByUUID,
    progressEvents,
    renderDOMPlayers,
    renderPlayer,
  }
} = vidyardEmbed;

GDPR.consent([true|false])

  • Sets consent for every player on your page to true or false.
  • This method assigns consent on a per subdomain basis.
import vidyardEmbed from '@vidyard/embed-code';

userHasGivenConsent() {    // client page code
  vidyardEmbed.api.GDPR.consent(true);
}

GDPR.hasConsentOnReady(callback)

  • Callback receives true or false upon all player ready.
  • This function is intended to determine whether or not to display a consent prompt upon page load.
import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.GDPR.hasConsentOnReady((consent) => {
  if (!consent) {
    showConsentPrompt();   // client page code
  } else {
    greet();               // client page code
  }
});

addReadyListener(callback[data, UUID])

  • Callback to call when the player is ready.
  • The data object is undefined for the ready event.
  • The UUID is optional filter for individual players.
  • If omitted the callback will apply to all players on the page.
import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.addReadyListener((data, player) => {
  console.log('the player is ready', player);
  player.seek(20);
  player.play();
});

getPlayersByUUID(UUID)

  • Returns an Array of all of the initialized players that match the given UUID.
  • If the same player is embedded multiple times the returned Array will have a player object for each one.
  • After you get player object, you can call the player API like play(), resume(), seek(), ready() etc. For more details about player API, please visit the Vidyard Knowledgebase
import vidyardEmbed from '@vidyard/embed-code';

const players = vidyardEmbed.api.getPlayersByUUID('UUID');
players[0].ready();

progressEvents(callback)

  • Allows you to trigger a given callback a player hits a certain viewing milestone (% of video watched).
  • The passed in callback gets a { player, chapter, event } = result object.
  • For more details, please visit the Vidyard Knowledgebase
import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.addReadyListener((data, player) => {
  vidyardEmbed.api.progressEvents(({ chapter, event, player }) => {
    const { name } = player.metadata.chapters_attributes[chapter].video_attributes;
    console.log(`${name}: ${event}%`);

    if (event === 4) {
      player.pause();
    }

  }, [1, 2, 3, 4, 25, 50, 75, 100]);
}, 'UUID');

renderDOMPlayers([container])

  • Renders all players in a given container, if a container is omitted it defaults to document.
  • The Script Tag version of the embed code will auto execute and render all players in the DOM by calling this method internally.
import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.renderDOMPlayers();

Or player in a specific container:

import vidyardEmbed from '@vidyard/embed-code';

const playersContainer = document.getElementById('video-content');
vidyardEmbed.api.renderDOMPlayers(playersContainer);

renderPlayer(options)

  • Renders the player programmatically.
  • The options can either be an HTMLImageElement in the DOM or a configuration object.
  • The configuration object needs to have a uuid and a container properties.

Note: The renderPlayer API method will not work inside the ready event as described above when using the standard v4.js script. It will, however, work inside the ready event when using the UMD module or NPM package, or using the standard v4.js script outside of the ready event (in which case, do not use the async attribute on the v4.js script tag).

import vidyardEmbed from '@vidyard/embed-code';

const placeholderImage = document.querySelectorAll('img.vidyard-player-embed')[0];
vidyardEmbed.api.renderPlayer(placeholderImage);

Or using a data object:

import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.renderPlayer({
  uuid: 'UUID',
  container: document.getElementById('player-container');
  // optional
  type: 'lightbox',
  aspect: 'landscape',
  vydata: encodeURIComponent(JSON.stringify({location: 'here', more: 'yes'}),
  // ...
  // any additional parameters
});

destroyPlayer(player)

  • Removes the player from the DOM.
  • Unsubscribes all progress events.
  • Removes the player model from window.Vidyard.players().
const player = api.getPlayersByUUID('pZovJVPRGJWs2scm3EZckY')[0];
api.destroyPlayer(player);

getPlayerMetadata(UUID)

  • Fetches metadata for players that have not been rendered.
  • Accepts a string UUID for the player.
  • Returns a promise containing the player metadata object, if the player UUID is not valid the promise is rejected.
import vidyardEmbed from '@vidyard/embed-code';

vidyardEmbed.api.getPlayerMetadata('UUID')
  .then((metadata) => {
    console.log(metadata);
  })
  .catch((e) => {
    console.log('error fetching player metadata');
  });

The schema of the Player Metadata object:

interface Metadata {
  chapters_attributes: Array<{
    video_attributes: {
      captions: any[];
      description: string | null;
      length_in_milliseconds: number;
      length_in_seconds: number;
      name: string;
      sd_url: string;
      status: string;
      tags: any[];
      thumbnail_urls: {
        normal: string;
        play_button: string;
        play_button_small: string;
        small: string;
      };
    };
  }>;
  custom_attributes: any[];
  description: string;
  height: number;
  length_in_seconds: number;
  name: string;
  tags: any[];
  uuid: string;
  width: number;
}

Player API

Once a player is selected with any of the Embed API methods, the player API allows for control of the player and adding handlers for player events. Full documentation of the Vidyard Player API can be found in the Vidyard Knowledge Base.

const players =  VidyardEmbed.api.getPlayersByUUID(UUID);
const firstPlayer = players[0];

firstPlayer.play();

firstPlayer.on('playerComplete', () => {
  console.log('the video was watched in full, hurray!');
});

License

The Vidyard Embed code is licensed under the MIT License.

Copyright 2021 Buildscale Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
4.3.154,213latest

Version History

VersionDownloads (Last 7 Days)Published
4.3.154,213
4.3.146,312
4.3.13316
4.3.12446
4.3.11409
4.3.10497
4.3.90
4.3.742
4.3.6280
4.3.561
4.3.48
4.3.393
4.3.212
4.3.10
4.3.00
4.2.39132
4.2.38174
4.2.3751
4.2.3642
4.2.3553
4.2.340
4.2.330
4.2.3217
4.2.31104
4.2.3038
4.2.290
4.2.280
4.2.270
4.2.260
4.2.250
4.2.240
4.2.232
4.2.220

Package Sidebar

Install

npm i @vidyard/embed-code

Weekly Downloads

13,302

Version

4.3.15

License

MIT

Unpacked Size

662 kB

Total Files

11

Last publish

Collaborators

  • esmith.vidyard
  • vymassimo
  • vyremus
  • ian.wilson
  • bpandya
  • vidyard-npm-ci
  • vyvergil
  • shubsengupta
  • alexpennells
  • mattocook
  • jbarwick
  • ahussein7
  • hanszhang
  • bluebrandon
  • ahardy