(updated ) by

Web Components: Spotify Embed

On this site, I wanted to embed Spotify playlists. Spotify has code to allow you to embed those playlists.

<spotify-embed embedwidth=“640” embedheight=“480” playlistid=“1GLEmw6QgsqrZPYUBl8QHi”

<iframe
	src="https://open.spotify.com/embed/playlist/1GLEmw6QgsqrZPYUBl8QHi"
	width="300"
	height="380"
	frameborder="0"
	allowtransparency="true"
	allow="encrypted-media"
></iframe>

Web Components

If we want to programatically update or generate the embed we can use JavaScript. Web Components allows us to use templates to render a embed.

<spotify-embed> Component

<spotify-embed
	playlistid="1GLEmw6QgsqrZPYUBl8QHi"
	embedwidth="300"
	embedheight="380"
></spotify-embed>

Template

<template id="spotify-embed-template">
	<iframe></iframe>
</template>

HTML Element

class SpotifyEmbed extends HTMLElement {...}
window.customElements.define('spotify-embed', SpotifyEmbed);

Then you load the template in the new HTML element and inject the new attributes.

You can also create the element directly in JavaScript.

const embed = document.createElement('spotify-embed')
embed.playlistid = "1GLEmw6QgsqrZPYUBl8QHi"
embed.embedwidth = 300
embed.embedheight = 380

document.body.appendChild(embed)

There are libraries out there, as well as more being created, to deal with some of the low level language. I have been using hybrids to create my Web Components.

hybrids

import { html, define } from 'hybrids'

export const SpotifyEmbed = {
	playlistid: '',
	embedwidth: 300,
	embedheight: 380,
	render: ({ playlistid, embedwidth, embedheight }) => html`
		<iframe
			src="https://open.spotify.com/embed/playlist/${playlistid}"
			width="${embedwidth}"
			height="${embedheight}"
			frameborder="0"
			allowtransparency="true"
			allow="encrypted-media"
		></iframe>
	`
}

define('spotify-embed', SpotifyEmbed)

Result

<script type="module" src="SpotifyEmbed.js"></script>
<spotify-embed playlistid="1GLEmw6QgsqrZPYUBl8QHi"></spotify-embed>

Turns into:

<spotify-embed playlistid=“1GLEmw6QgsqrZPYUBl8QHi”

References