npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

url-embed

v1.0.2

Published

Flexible oembed module written in ES6. Supports many existing providers. Can be easily extended to support new providers. Can resolve multiple oembeds asynchronously.

Downloads

117

Readme

url-embed

A flexible ES6 class-based system that supports converting URLs into embed code.

The module provides support for many common oembed providers, as well as support for creating your own custom providers.

API Documentation Lives Here

The Basics

This module exports the following properties:

 

Example: Resolving a single embed

'use strict';

let urlEmbed = require('url-embed');
let EmbedEngine = urlEmbed.EmbedEngine;
let Embed =  urlEmbed.Embed;
let engine = new EmbedEngine({
  timeoutMs: 2000,
  referrer: 'www.example.com'
});
engine.registerDefaultProviders();

let embedOptions = {
  maxHeight: 300
}

let embed = new Embed('https://www.youtube.com/watch?v=dQw4w9WgXcQ', embedOptions);

// Get single embed
engine.getEmbed(embed, function(embed) {
  if (embed.error) {
    console.log('Something went wrong.');
    console.log(err.stack);
  }

  // Embed markup
  console.log(embed.data.html);
});

 

Example: Resolving muliple embeds in parallel

'use strict';

let urlEmbed = require('url-embed');
let EmbedEngine = urlEmbed.EmbedEngine;
let Embed = urlEmbed.Embed;

let engine = new EmbedEngine({
  timeoutMs: 2000,
  referrer: 'www.example.com'
});

engine.registerDefaultProviders();

let embedArray = [
  new Embed('https://www.instagram.com/p/BCA0qkon9B1/?taken-by=mtv'),
  new Embed('https://soundcloud.com/newyorker/listen-to-craig-raine-read-bitch'),
  new Embed('https://www.youtube.com/watch?v=2LO4QL_i8is'),
  new Embed('https://vimeo.com/156045670'),
  new Embed('http://soundcloud.com/forss/flickermood'),
  new Embed('https://www.flickr.com/photos/sas999/25092061391/in/explore-2016-02-22/'),
  new Embed('http://www.dailymotion.com/video/x3lwpy7_the-worst-car-in-the-history-of-the-world-top-gear-bbc_auto'),
  new Embed('https://www.facebook.com/facebook/videos/10153231379946729/'),
  new Embed('https://www.facebook.com/MTV/posts/10153553500401701'),
  new Embed('https://twitter.com/simpscreens/status/702025133951680512'),
  new Embed('http://imgur.com/gallery/KSMB2tI'),
  new Embed('https://play.spotify.com/track/0ivpUENLpheuPoa6VuY1ax'),
  new Embed('http://mtv.tumblr.com/post/139813756155/kanye-west-taking-a-kanye-rest-so-he-can-do-his'),
  new Embed('https://videopress.com/v/kUJmAcSf'),
  new Embed('http://www.example.com/foo')
];

// Get multiple embeds
engine.getMultipleEmbeds(embedArray, function (error, results) {
  if (error) {
    // Something horrible killed the whole process. Spooky.
  } else {
    for (let i = 0; i < results.length; i++) {
      let embed = results[i];

      console.log('\nEmbed for ' + embed.embedURL);
      if (embed.error) {
        console.log('A tragedy occurred: ' + embed.error);
      }
      console.log(embed.data.html);
    }
  }
});

Creating Your Own URL Embed Providers

You can extend URLEmbedProvider and OEmbedProvider to make your own embed providers.

Example: Creating a new oembed provider

'use strict';

let OEmbedProvider = (require('url-embed')).OEmbedProvider;

class SoundCloud extends OEmbedProvider {}

// Name of provider
SoundCloud.prototype.name = 'soundcloud';

// oembed API URL
SoundCloud.prototype.providerURL = 'http://soundcloud.com/oembed';

// List of RegExp patterns to match provider urls
SoundCloud.prototype.urlPatterns = ['^https?://(www\.)?soundcloud\.com/.*'];

// Format indicates the response type of the oembed API
SoundCloud.prototype.format = 'json';

module.exports = SoundCloud;

 

Example: Creating a custom provider

'use strict';

let urlEmbed = require('url-embed');
let URLEmbedProvider = urlEmbed.URLEmbedProvider;
let UnexpectedStatusError = urlEmbed.errorClasses.UnexpectedStatusError;

class CustomProvider extends URLEmbedProvider {

  /*
  * @override
  */
  getEmbed (embed, callback) {
    try {
      embed.data.html = '<iframe src="http://www.example.com/embed/video/12345" width="512" height="288" frameborder="0"></iframe>';
      this.filterData(embed.data);
      callback(embed);
    } catch (error) {
      embed.data.html = this.errorMarkup(embed);
      embed.error = error;
      callback(embed);
    }
  }

  /*
  * Optional custom override of function that generates error markup.
  * Will deliver back customized messaging for missing items and API errors
  * @override
  */
  errorMarkup (embed) {
    if (embed.error instanceof UnexpectedStatusError) {
      if (embed.error.status == 404) {
        return 'Embed not found for: ' + embed.embedURL;
      } else {
        return 'Server returned an error for: ' + error.status + ' when resolving: ' + embed.embedURL;
      }
    }

    return 'Oops. Something went wrong for: <a href="' + embed.embedURL + '">' + embed.embedURL + '</a>';
  }
}

CustomProvider.prototype.name = 'custom';
CustomProvider.prototype.urlPatterns = ['^https?://www\.example\.com/video/.*'];

module.exports = CustomProvider;

 

Example: registering a provider with the EmbedEngine

'use strict'

let CustomProvider = require('./custom_provider');

let engine = new require('url-embed').EmbedEngine({
  timeoutMs: 2000,
  referrer: 'www.example.com'
});

engine.registerProvider(new CustomProvider());

Other tips, tricks and feats of strength

Example: Modifying an existing provider by extending its class

'use strict';

let urlEmbed = require('url-embed');
let Embed = urlEmbed.Embed;
let EmbedEngine = urlEmbed.EmbedEngine;
let engine = new EmbedEngine();

let defaultProviderClasses = urlEmbed.defaultProviderClasses;
let Youtube = defaultProviderClasses.Youtube;

// Class level override of filterData
class BetterYoutubeProvider extends Youtube {
  filterData(data) {
    data.html = 'YOLO!!!! ' + data.html
  }
}

// Test it out
engine.registerProvider(new BetterYoutubeProvider());

engine.getEmbed(new Embed('https://www.youtube.com/watch?v=dQw4w9WgXcQ'), function(embed) {
  console.log(embed.data.html);
});

/**
* Outputs:
* YOLO!!!! <iframe width="459" height="344" src="https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed" frameborder="0" allowfullscreen></iframe>
*/

Example:

  • Modifying the embed code for an instance of an existing provider
  • Modifying the embed code for all providers
'use strict';

let urlEmbed = require('url-embed');
let Embed = urlEmbed.Embed;
let EmbedEngine = urlEmbed.EmbedEngine;
let engine = new EmbedEngine();

let defaultProviderClasses = urlEmbed.defaultProviderClasses;
let Youtube = defaultProviderClasses.Youtube;
let provider = new Youtube();

// Instance-level override of Youtube.filterData.
provider.filterData = function (data) {
  data.html = 'YOLO!!!! ' + data.html
}

engine.registerDefaultProviders();

// Instance level override of EmbedEngine.filterData
engine.filterData = function(data) {
  data.html = '<hug>' + data.html + '</hug>';
}

engine.registerProvider(provider);

engine.getEmbed(new Embed('https://www.youtube.com/watch?v=dQw4w9WgXcQ'), function(embed) {
  console.log(embed.data.html);
});

engine.getEmbed(new Embed('https://play.spotify.com/track/0ivpUENLpheuPoa6VuY1ax'), function(embed) {
  console.log(embed.data.html);
});

/*
* Outputs:
* <hug>YOLO!!!! <iframe width="459" height="344" src="https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed" frameborder="0" allowfullscreen></iframe></hug>
* <hug><iframe src="https://embed.spotify.com/?uri=spotify:track:0ivpUENLpheuPoa6VuY1ax" width="300" height="380" frameborder="0" allowtransparency="true"></iframe></hug>
*/