Embed via JavaScript

Iframely hosts the embed.js JavaScript library that works together with hosted iFrames for third-party rich media and Iframely interactives.

We include the embed.js by default as <script> to the HTML code of API responses when required if you get your data via our oEmbed or Iframely API.

This document describes the library’s events, methods and callbacks that you can use.

You may also use the library to unfurl URLs on your page without making API requests first. Instead of content-specific HTML codes from APIs, you could create an HTML template yourself. The HTML code will be less optimized for layout shift but will work well otherwise.

Unfurl URLs without API calls

Add embed.js to your page

Add the embed.js script anywhere in your page’s <head> or <body>. It unfurls the links in your page’s HTML once the page has loaded. Call iframely.load() only for links you add later (see “Adding links dynamically” below).

<script async src="https://iframely.net/embed.js?key={MD5_KEY}"></script>

To load the embed.js script conditionally, only when rich media is on your page, please copy-paste this example gist.

  • src should have your API key in its query-string. Use the key’s MD5 hash as the key parameter rather than api_key: the src is visible in your page source.
  • Securing API by managing allowed origins is recommended for production use.
  • You may add any of the other supported query-string parameters.
  • If you use a custom CDN, source the embed.js script from your domain name.

You may also self-host the embed.js script. It is available on GitHub and npm. To read settings from its src, a self-hosted copy must be named embed.js (or iframely.js) and loaded from a full URL. Serve it from a folder rather than the root of your domain, or it will take your domain for its CDN, and request your HTML codes with omit_script=1. See the README for details. To bundle it into your app instead, see Use embed.js from npm.

HTML templates for your URLs

Iframely’s embed.js will search for the following links on your page with data-iframely-url attribute:

<div class="iframely-embed">
	<div class="iframely-responsive">
		<a data-iframely-url href="{URL_TO_EMBED_HERE}"></a>
	</div>
</div>

During its load cycle, embed.js replaces all such URLs with Iframely iFrame corresponding to the href link.

If all links are already in the DOM before you load the embed.js script, you’d get all links unfurled. If you load the embed.js before adding HTML template elements to your page, please see “Adding links dynamically” below.

You may add iframely-embed and iframely-responsive styles to your page yourself, as described in our omit-CSS document. It helps with layout shift until after embed.js is loaded.

Still, if cumulative layout shift is critical, you’d be better off using APIs instead.

If you add links dynamically, say, in a chat application or after the embed.js script is loaded, there’s an extra step for you. Please call embed.js loader explicitly:

iframely.load();

It will fetch all the missing links and unfurl them. To unfurl one link only, pass its <a> element:

iframely.load(linkElement);
// linkElement - is an <a> with 'href' attribute to replace

To unfurl only the links inside one element, such as a chat message or a shadow root, pass that element:

iframely.load(containerElement);

Alternatively, you may skip the HTML template altogether and specify container element and a URL to put there directly:

iframely.load(containerElement, 'https://{YOUR_URL_HERE}');

Removing embeds

When your app replaces part of the page, such as a chat view or a route in a single-page app, remove its embeds first, so their observers and timers are released:

iframely.unload(containerElement); // the embeds inside one element
iframely.unload(); // every embed on the page

unload() doesn’t put the original <a data-iframely-url> links back: render your markup again before you call iframely.load() on it. It doesn’t cover embeds in Shadow DOM, and it doesn’t remove your event listeners (see Events).

Act when unfurling fails

Perhaps an original link or its rich media are no longer available. For example, it was removed from YouTube, became private on Facebook, or you changed your API settings so that media type is no longer allowed.

Embed.js removes such failed rich media. By default, if the original link had text, a plain link with that text stays in its place; a link without text leaves nothing behind. To hide a container as well, or to change what stays behind, there are a few ways to do it.

  • You may source embed.js with optional &parent=… parameter containing the class name of the parent container. Iframely will find the first parent element with such class name and hide it, leaving the rest of your page tidy.
<script async src="https://iframely.net/embed.js?key={MD5_KEY}&parent={CLASS_NAME}"></script>
  • Alternatively, you can listen for the cancel event and handle it as your app requires:
iframely.on('cancel', function (url, parentNode, text, nextSibling) {
	// url - the original URL to rich media
	// parentNode - container of the deleted rich media
	// text - the original link's text, if it had any
	// nextSibling - the node that followed the deleted rich media
	//   e.g.: send a notification to your CMS to remove URL,
	//   or insert your own fallback before nextSibling
	//   (unless cancel_link is false, embed.js may already have put a link back)
});
  • To choose what a failed embed leaves behind, set cancel_link in the src (for example, &cancel_link=url) or in your configuration:
cancel_linkA failed embed leaves
text (default)A link with the original text; nothing when the link had none.
urlA link in any case, with the URL as its text when the link had none.
falseNothing. Render your own fallback from a cancel listener.

&cancel=0, the earlier way to get url, keeps working.

Configure embed.js

Besides the query-string of the script’s src, there are two ways to configure embed.js:

  • Before the script loads, pre-set the configuration. iframely doesn’t exist until the script has run, so this is the way to go with async scripts:
<script>
	window.iframely = { config: { theme: 'auto', cancel_link: 'url' } };
</script>
<script async src="https://iframely.net/embed.js?key={MD5_KEY}"></script>
  • After the script has run, call iframely.configure():
iframely.configure({ cancel_link: 'url' });

Parameters in the script’s src win over the pre-set configuration. iframely.extendOptions() still works as a deprecated name of configure().

To see which version of embed.js a page runs, type iframely.LIB_VERSION in the browser console.

Use embed.js from npm

For apps that bundle their JavaScript, embed.js is also an ES module:

npm install @iframely/embed.js
import { iframely } from '@iframely/embed.js';

iframely.configure({ key: '{MD5_KEY}' });
iframely.load();

Unlike the script tag, the module doesn’t scan the page on its own. Call iframely.load() when your markup is in the DOM, and iframely.unload() before it goes away (see Removing embeds). To scan the page on load like the script tag does, add autorun: true to configure() right after the import.

The module is safe to import with server-side rendering (SvelteKit, Next.js and others): on the server it does nothing, so keep load() and unload() in client-side code. TypeScript types are included, and @iframely/embed.js/options adds the URL options form. Recipes for Svelte, React and the options form are in USAGE.md.

Request your HTML codes with omit_script=1, so that the page runs a single copy of embed.js.

Events

Subscribe to events with iframely.on(). It returns a function that removes the subscription, and iframely.off(event, callback) removes every subscription of that callback. Remove your listeners when a component unmounts: unload() doesn’t.

var stop = iframely.on('height-changed', function (iframe, oldHeight, newHeight) {
	// adjust your layout
});

// later
stop();
EventArgumentsFired when
iframe‐readyiframeAn embed iframe has been created or revealed.
iframe‐sizediframe, mediaAn embed reported its size and it was applied, even when the height stays the same. The moment to drop a placeholder or a reserved height.
height‐changediframe, oldHeight, newHeightAn embed changed its height. heightChanged, its earlier name, still fires too.
cancelurl, parentNode, text, nextSiblingNo embed for the URL. See Act when unfurling fails.
clickhrefA user clicked in a summary card. See Card events.
optionswidget, optionsAn iFrame declared its URL options. See URL options events.
options‐changedid, container, queryA user changed a value in an options form.
set‐themethemeiframely.setTheme() applied a theme.
unloadcontaineriframely.unload() finished.

Card events

embed.js raises a click event if you need to run any analytics when your user clicks in a summary card:

iframely.on('click', function (href) {
	// For example, send a Google Analytics 4 event
	gtag('event', 'iframely_card_click', { link_url: href });
});

All clicks in cards open the URL in a new tab, except for links to your own site (the same origin as your page). Those open in the same window to allow for seamless navigation.

To change that, override iframely.openHref function:

iframely.openHref = function (href) {
	// You're in full control now
};

URL options events

iFrames that are sourced with content IDs will declare per-use options for a URL they represent.

For Iframely in a text editor, use those options to build a unique customization form for that URL.

iframely.on('options', function (widget, options) {
	// Use our options.js to build the options form for your text editor
});

Shadow DOM

When you place Iframely card and other rich media embed codes into Shadow DOM, there may be issues.

Please see the guide about how to use Iframely embeds with Web Components.