Add clips from Spotify in Anki

I’m trying to get each flashcard to automatically play the Spotify preview clip of a song. This is a custom basic card, with fields Front, Back, and Url (the Spotify song ID). Here’s what I have so far:

<div id="embed-iframe"></div>

{{Front}}

<script>
function loadSpotifyClip() {
   	const script = document.createElement('script');
  	script.setAttribute('src', 'https://open.spotify.com/embed/iframe-api/v1');
 	document.body.appendChild(script);

	window.onSpotifyIframeApiReady = (IFrameAPI) => {
          const element = document.getElementById('embed-iframe');
          const options = {
     	    width: 200,
            height: 200,
            uri: 'spotify:track:{{Url}}',
          };
          const callback = (EmbedController) => {
		EmbedController.play();
	  };
          IFrameAPI.createController(element, options, callback);
       };
}
loadSpotifyClip();
</script>

The current issue is that only the first card’s song appears, any subsequent cards don’t.

I am getting The Spotify Iframe API has already been initialized error. From my understanding, onSpotifyIframeApiReady is only called if the API script loads successfully, so this is why subsequent cards aren’t showing their songs. But this also means I can’t just use a global variable to call the API script once, since subsequent cards’ onSpotifyIframeApiReady functions require a successful API script load.

From Spotify documentation it seems that I could use the controller to switch the song when a new embed-frame div is in view? However I’m not sure how to code that.

I’m still new to this so thanks for any help.

Janky solution, I solved by setting window.SpotifyIframeConfig.loading = 0

1 Like