fetching data from the last FM API to build a last fm status

one of the most common things i see within the neocities community is the want to have a last fm status to allow page visitors to see the song you're currently listening to.

fortunately, it is extremely simple with Javascript!!

the steps

the most obvious first thing you're going to need is a last fm account. if you don't have one, create one here.

for people who don't want to read through and just want the code:



    document.addEventListener("DOMContentLoaded", function() {
        var LASTFMUSER = "sep7ic"  
        var url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + LASTFMUSER + "&api_key=afc213709a996ae561e307f596c9952b&format=json";
      
          fetch(url)
              .then(response => response.json())
              .then(data => {
                  var artist = data.recenttracks.track[0].artist["#text"];
                  var song = data.recenttracks.track[0]["name"];
                  var artwork = data.recenttracks.track[0].image[3]["#text"];
                  var link = data.recenttracks.track[0]["url"];
      
                  document.getElementById("artwork").src = artwork;
                  document.getElementById("track").innerHTML = "" + song + "
" + artist; document.getElementById("artworklink").href = link; if (typeof data.recenttracks.track[0]["@attr"] !== "undefined") { document.getElementById("listen").innerHTML = 'listening to:'; console.log("true"); document.getElementById("status").innerHTML = 'online'; } else { document.getElementById("listen").innerHTML = "last listened to:"; console.log("false"); } }) .catch(error => { console.error("Error fetching data:", error); }); });

page still a wip lol