You can find out the uri
of the context of what is playing in the Player using:
require([
'$api/models',
], function(models) {
'use strict';
// find out initial status of the player
models.player.load(['context']).done(function(player) {
// player.context.uri will contain the uri of the context
});
// subscribe to changes
models.player.addEventListener('change', function(m) {
// m.data.context.uri will contain the uri of the context
});
});
You can use that uri
to fetch properties, such as the name
. In the following example we retrieve the name of the playlist if the current track's context is a playlist:
require([
'$api/models',
], function(models) {
'use strict';
/**
* Returns whether the uri belongs to a playlist.
* @param {string} uri The Spotify URI.
* @return {boolean} True if the uri belongs to a playlist, false otherwise.
*/
function isPlaylist(uri) {
return models.fromURI(uri) instanceof models.Playlist;
}
/**
* Returns the name of the playlist.
* @param {string} playlistUri The Spotify URI of the playlist.
* @param {function(string)} callback The callback function.
*/
function getPlaylistName(playlistUri, callback) {
models.Playlist.fromURI(models.player.context.uri)
.load('name')
.done(function(playlist){
callback(playlist.name);
});
}
// find out initial status of the player
models.player.load(['context']).done(function(player) {
var uri = player.context.uri;
if (isPlaylist(uri)) {
getPlaylistName(player.context.uri, function(name) {
// do something with 'name'
});
}
});
// subscribe to changes
models.player.addEventListener('change', function(m) {
var uri = m.data.context.uri;
if (isPlaylist(uri)) {
getPlaylistName(m.data.context.uri, function(name) {
// do something with 'name'
});
}
});
});