Home Music Blog Digital Alchemy Gates

my very own last-fm scrobbler!

posted on : 6/18/2024

i wanted to make my own last-fm widget!

you can take this code! it should work if you add your api key and your user name, and have an element named 'root' on your machine!

    
        function FetchStats() {
            // Fetch XML data
            fetch('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=USERRNAME&limit=1&api_key=api_key&format=xml')
                .then(response => response.text()) // Convert the response to text (XML is text)
                .then(str => (new window.DOMParser()).parseFromString(str, "text/xml")) // Parse the text to XML Document
                .then(data => {
                    // Extracting elements using DOM methods
                    const track = data.getElementsByTagName('track')[0]; // Get the first <track> element
                    const artist = track.getElementsByTagName('artist')[0].textContent; // Get the artist name
                    const trackName = track.getElementsByTagName('name')[0].textContent; // Get the track name
                    const images = track.getElementsByTagName('image'); // Get all image elements
                    let smallImageUrl = '';

                    // Find the URL of the small image
                    Array.from(images).forEach(img => {
                        if (img.getAttribute('size') === 'large') {
                            smallImageUrl = img.textContent;
                        }
                    });

                    // Check if now playing (based on presence of <date> element within <track>)
                    const now andPlaying = track.getElementsByTagName('date').length > 0 ? "No" : "Yes";

                    // Display the result
                    const container = document.getElementById('root');
                    const root = ReactDOM.createRoot(container);
                    root.render(
                        <>
                            <h3>What am I listening to?</h3>
                            <div id="marq">
                                <p id="playing">{`${trackName} - ${artist}`}</p>
                            </div>
                            <img class="album" src={smallImageUrl} alt="Album Cover" />
                        </>
                    );
                });
        }

        // Call the function to execute
        FetchStats();