url-embed

    1.0.2 • Public • Published

    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>
    */
     

    Install

    npm i url-embed

    DownloadsWeekly Downloads

    16

    Version

    1.0.2

    License

    MIT

    Last publish

    Collaborators

    • mkopit