Skip to content

Instantly share code, notes, and snippets.

@muhdiboy
Last active September 24, 2026 20:23
Show Gist options
  • Select an option

  • Save muhdiboy/a293cbff355af750e3b8f45ec816d1f1 to your computer and use it in GitHub Desktop.

Select an option

Save muhdiboy/a293cbff355af750e3b8f45ec816d1f1 to your computer and use it in GitHub Desktop.
LastFM automated duplicate scrobble deletion script

Why would I need this?

Your scrobbler might have decided to scrobble every song hundreds of times, and you can't really remove those scrobbles efficiently. Or you might have accidentally installed multiple scrobbler extensions at the same time - wondering why multiple scrobbles appear for every song played at a time - and you want to clear them after finding the issue.

Using this script still doesn't necessarily make the process quick, since Last.fm only displays a limited number of scrobbles that can be removed on each page of your library, and also rate-limits how many pages you can load in quick succession. The difference from the implementation of @sk22 and its forks - which this UserScript is derived from - is that you don't run it manually on every page. You set your options once, click START, and the rest of the process is automated: the script works its way back through your library and stops automatically at the page you choose.

Installation

Prerequisites

You will need some form of UserScript interpreter/injector plugin and a compatible browser.

  • For Google Chrome and Chromium-based browsers (e.g. Vivaldi, Opera or Brave), you need the Tampermonkey plugin. Just click on the link or search for it yourself on the Chrome Web Store and add the extension.
  • Currently not officially supported: For Firefox, you also need the Tampermonkey plugin (or alternatively Greasemonkey). Just click on one of the desired links or search for it yourself on the Firefox Browser Add-Ons page. Note that Firefox has historically been less reliable with this script, sometimes stopping after a few reloads.

How to install the UserScript

Just click on the "Raw" button in the upper right-hand corner of the script file, or by clicking here. Your extension should open an installation window where you confirm the installation of the UserScript. If that is not working, try to add the script manually to your extension by copying and pasting it.

Using the script - step by step

  • Open your Last.fm library while logged in (https://www.last.fm/user/_/library). Navigate to the page from which you want to start removing duplicates, either by clicking through the pages at the bottom or by entering the page number in the URL (e.g. https://www.last.fm/user/_/library?page=123).
    • Alternatively, you can choose a specific date range instead and navigate to the last or desired page.
  • A control panel appears in the bottom-left corner of the page. Manually reload the page if it doesn't show up.
  • Choose how duplicates are compared, using the checkbox in the panel:
    • Only compare real duplicates (checked by default) removes only scrobbles that share the exact same timestamp. These are genuine duplicates - the same play counted more than once.
    • Unchecking it reveals a Tracks to compare field. This makes the script ignore timestamps and instead compare each track against the next n tracks. Useful for older messes where timestamps differ, but be careful: this can remove legitimate repeat-listens, so set the number thoughtfully.
  • Enter the page number where you want the script to stop in the panel's field, then click START. The current page is shown next to the field for reference.
    • The stop page must be lower than or equal to your current page, since the script works backwards towards page 1. For example, start on page 100 and set the stop page to 1 to clean your entire history; or set it to 50 to clean only pages 100 down to 50.
  • Now enjoy the purge :)
    • You can continue with other tasks on your PC. Just leave the window active in the background. Running the script in a separate window (not just a background tab) is recommended, as background tabs can be throttled by the browser and stall the script.
    • The panel's log shows live progress: pages cleared, how many duplicates were deleted, and any rate-limit or error waits. The running total is shown in the status line.
    • To stop early, click STOP in the panel.
  • When it reaches the page you set, the script stops automatically and shows the total number of deleted scrobbles in the panel.

A note on rate-limiting and errors

Since mid-2024, Last.fm limits how many pages you can load in a short time (roughly 20 pages per minute). When you hit this limit, you'll briefly see a "Page not available / You're requesting too many pages" message. You may also occasionally see a "405 - Method Not Allowed" page right after a block of deletions.

Both of these are normal and handled automatically. The script detects them, waits, and retries - increasing the wait time on repeated rate-limits - then continues where it left off. You'll see these events noted in the log. Because of these unavoidable pauses, larger libraries simply take longer; just leave the script running and let it work through them.

Updating the script

You can set up the script to auto-update in the settings of the UserScript. Open the plugin settings and select "LastFM automated duplicate scrobble deletion script". Then go to the script settings in the upper left-hand corner, check the "Search for updates" checkbox and save.

Alternatively, you can update it manually by following the installation instructions above, or by searching for updates in the plugin overview.

Troubleshooting

  • The panel doesn't appear. Make sure you're on a library page (not the Albums/Artists/Tracks sub-pages) and logged in. Reload the page manually. If you switched to the library from another section, Last.fm's dynamic navigation can prevent the panel from injecting - a full reload fixes this.
  • It moves through pages but deletes nothing. Confirm you actually have duplicates on those pages, and that you're logged in. If you're using the "real duplicates" mode (the default), remember it only removes scrobbles with an identical timestamp; genuine repeat-listens at different times are intentionally kept. To catch those, uncheck the box and use the "Tracks to compare" mode.
  • It keeps hitting the rate-limit / 405 page. This is expected on large libraries (see the note above). Let it run - it backs off and retries on its own. Don't rapidly start/stop it, as that can trigger the limit faster.
  • It stalls when running in a background tab. Move the script to its own separate window. Browsers throttle inactive background tabs, which interrupts the reload loop.
  • Firefox stops after a couple of reloads. Firefox behaves differently from Chromium browsers here and isn't officially supported. A Chromium-based browser (Chrome, Brave, Vivaldi, Opera, Edge) is recommended for the smoothest experience.

Thank-yous

Based on https://gist.github.com/sk22/39cc280840f9d82df574c15d6eda6629#gistcomment-3046698. Thanks to previous contributors @CennoxX, @mattsson, @gms8994, @huw and @sk22. Thanks to new contributions from @Eiron, and to @RudeySH for the rate-limiting analysis.

Feel free to post any problems, fixes, improvements and feedback. I will try to help in any form. To anyone having more experience in JavaScript or OpenUserJS/UserScript: your help is welcome to keep improving the script.

// ==UserScript==
// @name LastFM automated duplicate scrobble deletion script
// @namespace https://gist.github.com/muhdiboy
// @version 2.0.0
// @downloadURL https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js
// @updateURL https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js
// @description Based on https://gist.github.com/sk22/39cc280840f9d82df574c15d6eda6629#gistcomment-3046698, thanks to previous contributors (@CennoxX, @mattsson, @gms8994, @huw and @sk22) and new contributors (@Eiron).
// @author muhdiboy
// @match https://www.last.fm/*user/*
// @icon https://www.last.fm/static/images/favicon.ico
// @grant none
// ==/UserScript==
(function() {
let runScript = localStorage.getItem('runScript') === 'true';
let rmOnlyRealDup = localStorage.getItem('rmOnlyRealDup') !== 'false'; // checkbox defaults to checked
let numTracks = localStorage.getItem('numTracks') || "5";
let stopAtPage = localStorage.getItem('stopAtPage') || "0";
// Always read the page number fresh from the current URL. A cached value
// goes stale when the user clicks through Last.fm's own pagination (the
// click handler fires before the URL updates), and it also misreads the
// /library/delete (405) page as "page 1" because that URL has no page param.
function getCurrentPage() {
return extractQueryParam('page', window.location.href) || 1;
}
// Add/remove the panel as the URL changes, and keep the current-page label live.
setInterval(function () {
if (this.lastPathStr !== location.pathname || this.lastQueryStr !== location.search) {
this.lastPathStr = location.pathname;
this.lastQueryStr = location.search;
if (shouldMatchPage()) buildPanel(); else removePanel();
}
const pageLbl = document.getElementById('lfm-stop-page-lbl');
if (pageLbl) pageLbl.textContent = 'Stop at which page? (current: ' + getCurrentPage() + ')';
}, 125);
function replaceQueryParam(param, newval, search) {
const regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
const query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
function extractQueryParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
const regexS = "[\\?&]" + name + "=([^&#]*)";
const regex = new RegExp(regexS);
const results = regex.exec(url);
return results == null ? null : results[1];
}
function shouldMatchPage() {
const url = window.location.href;
const excludeUrlRegex = /^https:\/\/www\.last\.fm\/.*user\/.*\/library\/(albums|artists|tracks|music).*/;
const matchUrlRegex = /^https:\/\/www\.last\.fm\/.*user\/.*\/library.*/;
return matchUrlRegex.test(url) && !excludeUrlRegex.test(url);
}
// ---- Logging ----------------------------------------------------------
// The page reloads constantly while running, so the log is persisted in
// localStorage and re-rendered each time the panel is built.
function loadLog() {
try { return JSON.parse(localStorage.getItem('lfmLog')) || []; }
catch (e) { return []; }
}
function log(msg, level) {
const entries = loadLog();
const now = new Date();
const ts = String(now.getHours()).padStart(2, '0') + ':' +
String(now.getMinutes()).padStart(2, '0') + ':' +
String(now.getSeconds()).padStart(2, '0');
entries.unshift({ ts: ts, msg: msg, level: level || 'info' });
while (entries.length > 60) entries.pop();
localStorage.setItem('lfmLog', JSON.stringify(entries));
renderLog();
}
function renderLog() {
const logEl = document.getElementById('lfm-log');
if (!logEl) return;
logEl.textContent = '';
loadLog().forEach(function (e) {
const line = document.createElement('div');
line.className = 'log-' + e.level;
line.textContent = '[' + e.ts + '] ' + e.msg;
logEl.appendChild(line);
});
}
function setStatus(text, running) {
const statusEl = document.getElementById('lfm-status');
if (!statusEl) return;
statusEl.innerHTML = '';
if (running) {
const spin = document.createElement('span');
spin.className = 'lfm-spin';
statusEl.appendChild(spin);
}
statusEl.appendChild(document.createTextNode(text));
}
function removePanel() {
const panel = document.getElementById('lfm-panel');
if (panel) panel.remove();
}
// ---- Actions ----------------------------------------------------------
function startScript() {
const pageInput = document.getElementById('lfm-stop-page');
const tracksInput = document.getElementById('lfm-num-tracks');
const inputStopAtPage = (pageInput.value || '').trim();
if (!/^\d+$/.test(inputStopAtPage)) {
log('\u2715 Invalid stop page. Enter a valid number.', 'err');
return;
}
const curPage = getCurrentPage();
if (parseInt(inputStopAtPage) > curPage && !(curPage === 0 && parseInt(inputStopAtPage) === 1)) {
log('\u2715 Stop page must be \u2264 current page (' + curPage + ').', 'err');
return;
}
localStorage.setItem('stopAtPage', inputStopAtPage);
if (!rmOnlyRealDup) {
const inputNumTracks = (tracksInput.value || '').trim();
if (!/^\d+$/.test(inputNumTracks) || inputNumTracks < 2 || inputNumTracks > 50) {
log('\u2715 Tracks to compare must be a number between 2 and 50.', 'err');
return;
}
localStorage.setItem('numTracks', inputNumTracks);
}
localStorage.setItem('runScript', 'true');
localStorage.setItem('totalDeleted', '0');
localStorage.removeItem('lfmDone');
log('\u25B6 Started. Stopping at page ' + inputStopAtPage + '.', 'life');
location.reload();
}
function stopScript() {
localStorage.setItem('runScript', 'false');
localStorage.removeItem('savedUrl');
localStorage.removeItem('refreshTimeout');
localStorage.removeItem('totalDeleted');
log('\u25A0 Stopped by user.', 'life');
location.reload();
}
// ---- Panel ------------------------------------------------------------
function buildPanel() {
if (document.getElementById('lfm-panel')) return;
const style = document.createElement('style');
style.textContent = `
#lfm-panel {
position:fixed;left:18px;bottom:90px;z-index:2147483647;
width:300px;background:#111;color:#eee;
border:1px solid #333;border-radius:10px;
font:12px/1.4 "Inter","Segoe UI",sans-serif;
box-shadow:0 8px 40px rgba(0,0,0,.85);
display:flex;flex-direction:column;overflow:hidden;
}
#lfm-panel * { box-sizing:border-box; }
#lfm-header {
display:flex;align-items:center;justify-content:space-between;
padding:10px 14px;background:#1a1a1a;border-bottom:1px solid #2a2a2a;
cursor:pointer;user-select:none;
}
.lfm-h-title{font-weight:700;color:#e11d48;font-size:13px;}
.lfm-h-hint{color:#444;font-size:11px;}
#lfm-body{display:flex;flex-direction:column;gap:9px;padding:12px;}
.lfm-lbl{font-size:10px;color:#888;margin-bottom:-4px;}
.lfm-input{
width:100%;padding:6px 8px;background:#1e1e1e;
border:1px solid #333;border-radius:6px;color:#eee;
font-size:12px;font-family:inherit;
}
.lfm-input::placeholder{color:#555;}
.lfm-row{display:flex;gap:8px;}
.lfm-check{display:flex;align-items:center;gap:7px;cursor:pointer;user-select:none;color:#ccc;}
.lfm-check input{accent-color:#e11d48;width:14px;height:14px;cursor:pointer;}
.lfm-btn{flex:1;padding:7px 0;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;}
.lfm-btn:hover{opacity:.85;}
.lfm-btn-primary{background:#e11d48;color:#fff;}
.lfm-btn-secondary{background:#2a2a2a;color:#ccc;border:1px solid #3a3a3a;}
#lfm-status{font-size:11px;color:#bbb;padding:5px 0;border-top:1px solid #1c1c1c;min-height:20px;}
#lfm-log{
height:120px;overflow-y:auto;background:#050505;
border:1px solid #1a1a1a;border-radius:6px;
padding:5px 7px;font-family:monospace;font-size:10px;
display:flex;flex-direction:column;gap:1px;
}
.log-ok{color:#4ade80;}.log-warn{color:#fbbf24;}.log-err{color:#f87171;}.log-info{color:#888;}.log-life{color:#22d3ee;}
@keyframes lfm-spin{to{transform:rotate(360deg);}}
.lfm-spin{
display:inline-block;width:10px;height:10px;
border:2px solid #e11d48;border-top-color:transparent;
border-radius:50%;animation:lfm-spin .7s linear infinite;
vertical-align:middle;margin-right:6px;
}
`;
document.head.appendChild(style);
const panel = document.createElement('div'); panel.id = 'lfm-panel';
const hdr = document.createElement('div'); hdr.id = 'lfm-header';
const ht = document.createElement('span'); ht.className = 'lfm-h-title'; ht.textContent = 'LastFM Duplicate Remover';
const hh = document.createElement('span'); hh.className = 'lfm-h-hint'; hh.textContent = '\u25BC collapse';
hdr.append(ht, hh);
let collapsed = localStorage.getItem('lfmCollapsed') === 'true';
hdr.addEventListener('click', () => {
collapsed = !collapsed;
body.style.display = collapsed ? 'none' : '';
hh.textContent = collapsed ? '\u25B6 expand' : '\u25BC collapse';
localStorage.setItem('lfmCollapsed', collapsed);
});
panel.appendChild(hdr);
const body = document.createElement('div'); body.id = 'lfm-body';
const lblPage = document.createElement('div'); lblPage.className = 'lfm-lbl';
lblPage.id = 'lfm-stop-page-lbl';
lblPage.textContent = 'Stop at which page? (current: ' + getCurrentPage() + ')';
const pageInput = document.createElement('input');
pageInput.id = 'lfm-stop-page'; pageInput.className = 'lfm-input';
pageInput.type = 'text'; pageInput.value = stopAtPage; pageInput.placeholder = '0';
const checkWrap = document.createElement('label'); checkWrap.className = 'lfm-check';
const check = document.createElement('input'); check.type = 'checkbox';
check.id = 'lfm-real-dup'; check.checked = rmOnlyRealDup;
const checkTxt = document.createElement('span'); checkTxt.textContent = 'Only compare real duplicates';
checkWrap.append(check, checkTxt);
const lblTracks = document.createElement('div'); lblTracks.className = 'lfm-lbl';
lblTracks.textContent = 'Tracks to compare (2\u201350):';
const tracksInput = document.createElement('input');
tracksInput.id = 'lfm-num-tracks'; tracksInput.className = 'lfm-input';
tracksInput.type = 'text'; tracksInput.value = numTracks; tracksInput.placeholder = '5';
// The num-tracks field is only relevant when "real duplicates" is off.
function syncTracksVisibility() {
const show = !check.checked;
lblTracks.style.display = show ? '' : 'none';
tracksInput.style.display = show ? '' : 'none';
}
check.addEventListener('change', function () {
rmOnlyRealDup = check.checked;
localStorage.setItem('rmOnlyRealDup', check.checked);
syncTracksVisibility();
});
const row = document.createElement('div'); row.className = 'lfm-row';
const startBtn = document.createElement('button');
startBtn.className = 'lfm-btn lfm-btn-primary'; startBtn.textContent = '\u25B6 START';
startBtn.onclick = startScript;
const stopBtn = document.createElement('button');
stopBtn.className = 'lfm-btn lfm-btn-secondary'; stopBtn.textContent = '\u25A0 STOP';
stopBtn.onclick = stopScript;
row.append(startBtn, stopBtn);
const statusEl = document.createElement('div'); statusEl.id = 'lfm-status';
const lblLog = document.createElement('div'); lblLog.className = 'lfm-lbl'; lblLog.textContent = 'Log (newest first):';
const logEl = document.createElement('div'); logEl.id = 'lfm-log';
body.append(lblPage, pageInput, checkWrap, lblTracks, tracksInput, row, statusEl, lblLog, logEl);
panel.appendChild(body);
document.body.appendChild(panel);
if (collapsed) { body.style.display = 'none'; hh.textContent = '\u25B6 expand'; }
syncTracksVisibility();
// Lock inputs while a run is in progress.
if (runScript) {
startBtn.disabled = true; startBtn.style.opacity = '.4'; startBtn.style.cursor = 'default';
pageInput.disabled = true; tracksInput.disabled = true; check.disabled = true;
}
renderLog();
// Status line: running spinner, last completion message, or idle.
const done = localStorage.getItem('lfmDone');
if (runScript) {
setStatus('Running\u2026 ' + (parseInt(localStorage.getItem('totalDeleted')) || 0) + ' deleted so far.', true);
} else if (done) {
setStatus(done, false);
} else {
setStatus('Idle', false);
}
}
// ---- Deletion + navigation engine -------------------------------------
if (shouldMatchPage()) {
window.addEventListener('load', function () {
if (!runScript) return;
let found = 0;
const initialRefreshTimeout = 5000;
let refreshTimeout = parseInt(localStorage.getItem('refreshTimeout')) || initialRefreshTimeout;
const sections = Array.from(document.getElementsByTagName("tbody"));
const savedUrl = localStorage.getItem('savedUrl') || window.location.href;
// Page number for this load. If the live URL has no page param (e.g. a
// transient bounce), fall back to savedUrl so the log/stop check don't
// spuriously report "page 1".
let pageNow = extractQueryParam('page', window.location.href);
if (pageNow == null) pageNow = extractQueryParam('page', savedUrl);
if (pageNow == null) pageNow = 1;
pageNow = parseInt(pageNow);
// A "delete" URL is the 405 (Method Not Allowed) page after a delete
// click. Bounce back to the last good page. The return is required so we
// don't fall through into deletion on a page that's mid-navigation.
if (window.location.toString().includes("delete")) {
log('\u26A0 Hit 405 page, returning to last good page.', 'warn');
window.location.href = savedUrl;
return;
}
// No track list means the rate-limit page ("requesting too many pages").
// Detecting via the .chartlist table rather than page text keeps this
// language-independent. Wait the current backoff, retry, and escalate so
// repeated rate-limits wait progressively longer.
if (!document.querySelector('.chartlist')) {
log('\u26A0 Rate-limited. Waiting ' + (refreshTimeout / 1000) + 's then retrying.', 'warn');
setTimeout(function() {
window.location.href = savedUrl;
}, refreshTimeout);
localStorage.setItem('refreshTimeout', refreshTimeout + 5000);
return;
} else {
refreshTimeout = initialRefreshTimeout;
localStorage.setItem('refreshTimeout', initialRefreshTimeout);
localStorage.setItem('savedUrl', window.location.href);
}
sections.forEach(function (section) {
const els = Array.from(section.rows);
const names = els.map(function (el) {
const nmEl = el.querySelector('.chartlist-name');
const artEl = el.querySelector('.chartlist-artist');
if (rmOnlyRealDup) {
const tstEl = el.querySelector('.chartlist-timestamp');
return nmEl && artEl && tstEl && nmEl.textContent.replace(/\s+/g, ' ').trim() + ':' + artEl.textContent.replace(/\s+/g, ' ').trim() + ':' + tstEl.textContent.replace(/\s+/g, ' ').trim();
} else {
return nmEl && artEl && nmEl.textContent.replace(/\s+/g, ' ').trim() + ':' + artEl.textContent.replace(/\s+/g, ' ').trim();
}
});
names.forEach(function (name, i) {
if (!name) return;
// Real-duplicate mode: duplicates share an identical timestamp but
// can be far apart or span page boundaries, so compare against the
// whole remaining list. "n tracks" mode: limited look-ahead window.
const rest = rmOnlyRealDup
? names.slice(i + 1)
: names.slice(i + 1, i + 1 + parseInt(numTracks));
if (!rest.includes(name)) return;
const delBtn = els[i].querySelector('[data-ajax-form-sets-state="deleted"]');
if (delBtn) { delBtn.click(); found++; }
});
});
if (found > 0) {
const totalDeleted = (parseInt(localStorage.getItem('totalDeleted')) || 0) + found;
localStorage.setItem('totalDeleted', totalDeleted);
log('\u2713 Page ' + pageNow + ': deleted ' + found + ' (total ' + totalDeleted + ').', 'ok');
setTimeout(function() {
location.reload();
}, refreshTimeout);
return;
}
if (pageNow <= stopAtPage) {
const totalDeleted = parseInt(localStorage.getItem('totalDeleted')) || 0;
const msg = 'Complete. ' + totalDeleted + ' duplicate scrobble' + (totalDeleted === 1 ? '' : 's') + ' deleted.';
localStorage.setItem('runScript', 'false');
localStorage.removeItem('savedUrl');
localStorage.removeItem('refreshTimeout');
localStorage.removeItem('totalDeleted');
localStorage.setItem('lfmDone', msg);
log('\u25A0 ' + msg, 'life');
location.reload();
return;
}
// Otherwise go up one page.
window.location.href = window.location.pathname + replaceQueryParam('page', extractQueryParam('page', window.location.href) - 1, window.location.search);
});
}
})();
@leahrr

leahrr commented Mar 7, 2022

Copy link
Copy Markdown

I leave mine on for a bit and I have years and years of scrobbles to delete and I come back and it didn't actually delete anything, its moving from page to page without doing anything

@muhdiboy

muhdiboy commented Mar 8, 2022

Copy link
Copy Markdown
Author

Hi @leahrr,

thank you for your feedback. I will look into this tomorrow. Until then please make sure that you really have duplicates and are using the latest version of the script. Also please tell me your Browser with version number.

@leahrr

leahrr commented Mar 8, 2022

Copy link
Copy Markdown

I have visible duplicates
I am using Chrome version 99.0.4844.51

@muhdiboy

muhdiboy commented Mar 11, 2022 •

Copy link
Copy Markdown
Author

@leahrr I couldn't reproduce it. Maybe you are not logged in? I'm sorry though. Maybe try out a different browser without the possibility of conflicting add-ons.

@hash-khat

hash-khat commented Apr 2, 2022 •

Copy link
Copy Markdown

Thanks for bringing this to the level it's at, muhdiboy. I'm sure there are untold many out there who appreciate it.

I used a manual version last year that worked fine. Using this on my usual browser (Edge) did nothing: moved quickly through the pages but deleted nothing (99.0.1150.55 (Official build) (64-bit)).

Tried on a fresh install of Chrome and the same behaviour: moves quick but deletes nothing (Version 100.0.4896.60 (Official Build) (64-bit)).

Hope this isn't too difficult to figure out because it's well beyond me to understand (I am a manual labourer). Even if you don't, thanks for the effort thus far!

@eiron

eiron commented Apr 6, 2022 •

Copy link
Copy Markdown

I made a couple of tweaks below.

One is to include an EventListener for the page load (lines 76 & 108).

The other is to also include the '.chartlist-timestamp' (lines 82-83).

In theory, this should wait for the page to load completely before checking for things to delete, and not remove those single-track binge sessions where you genuinely have repeated a song. It should catch, then, only those identical scrobbles with the same timestamp.

Code
// ==UserScript==
// @name         LastFM automated duplicate scrobble deletion script
// @namespace    https://gist.github.com/muhdiboy
// @version      1.1-u5
// @downloadURL  https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js
// @updateURL    https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js
// @description  Based on https://gist.github.com/sk22/39cc280840f9d82df574c15d6eda6629#gistcomment-3046698, thanks to previous contributors: @CennoxX, @mattsson, @gms8994, @huw and @sk22
// @author       muhdiboy
// @include      /^https:\/\/www\.last\.fm\/user\/.*\/library.*$/
// @exclude      /^https:\/\/www\.last\.fm\/user\/.*\/library\/(albums|artists|tracks).*$/
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(function() {
    var found = 0;
    var num = 5;
    var sections = Array.from(document.getElementsByTagName("tbody"));

    function exit( status ) {
        // source: https://web.archive.org/web/20091002005151/http://kevin.vanzonneveld.net:80/techblog/article/javascript_equivalent_for_phps_exit
        // http://kevin.vanzonneveld.net
        // +   original by: Brett Zamir (http://brettz9.blogspot.com)
        // +      input by: Paul
        // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
        // +   improved by: Philip Peterson
        // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)

        var i;

        if (typeof status === 'string') {
            alert(status);
        }

        window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

        var handlers = [
            'copy', 'cut', 'paste',
            'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
            'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
            'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
        ];

        function stopPropagation (e) {
            e.stopPropagation();
            // e.preventDefault(); // Stop for the form controls, etc., too?
        }
        for (i=0; i < handlers.length; i++) {
            window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
        }

        if (window.stop) {
            window.stop();
        }

        throw '';
    }

    function replaceQueryParam(param, newval, search) {
        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
        var query = search.replace(regex, "$1").replace(/&$/, '');
        return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
    }

    function gup( name, url ) {
        if (!url) url = location.href;
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( url );
        return results == null ? null : results[1];
    }



    window.addEventListener('load', function () {
        sections.forEach(function (section) {
            var els = Array.from(section.rows);
            var names = els.map(function (el) {
                var nmEl = el.querySelector('.chartlist-name');
                var artEl = el.querySelector('.chartlist-artist');
                var tstEl = el.querySelector('.chartlist-timestamp');
                return nmEl && artEl && tstEl && nmEl.textContent.replace(/\s+/g, ' ').trim()+':'+artEl.textContent.replace(/\s+/g, ' ').trim()+':'+tstEl.textContent.replace(/\s+/g, ' ').trim();
            });

            names.forEach(function (name, i, names) {
                if (!names.slice(i + 1, i + 1 + num).includes(name)) return;
                var delBtn = els[i].querySelector('[data-ajax-form-sets-state="deleted"]');
                if (delBtn) { delBtn.click(); found++; };
            });
        });


        if (window.location.toString().includes("delete")) {
            history.go(-1);
            exit();
        }

        if (found > 0) {
            setInterval(function() {
                location.reload();
            }, 5000);
        }

        if (window.location.toString().includes("page=-")) alert("LastFM duplicate deletion complete. Disable the UserScript!");

        else window.location.href = window.location.pathname + replaceQueryParam('page', gup('page', window.location.href) - 1, window.location.search);
    });

})();

@muhdiboy

muhdiboy commented Apr 7, 2022

Copy link
Copy Markdown
Author

Hello @eiron ,

thank you very much for your input! It makes the script much more stable.
I released a new version with your additions and also added a variable to enable or disable removing only true duplicates. The reason for my addition is because I have a bug with my wireless earbuds that seem to play the last track on loop while they are not being used. The option is there for people who want to change the (now) default behaviour.

@alxjms92, also thank you for your feedback. I'm still not sure why that happens, as I've tested the script on fresh Firefox and Chrome installations. Maybe this new addition will be helpful. Test it out and report your experience please. Thank you!

@eiron

eiron commented Apr 7, 2022 •

Copy link
Copy Markdown

@muhdiboy: I had the same experience as @leahrr and @alxjms92. It is what prompted me to make the adjustments above. Hopefully, this new version will work for them!

Edit: Should also add that I really appreciate this tool. Removed over 1000 duplicates from over the years in a matter of minutes - it would have been an impossible task else.

@alexandroheredia

Copy link
Copy Markdown

April 30th, 2022... this worked like a charm! Thank you for making this!!!

@muhdiboy

muhdiboy commented Jun 7, 2022

Copy link
Copy Markdown
Author

I used it again today and noticed a warning from Tampermonkey about Chromium moving to Manifest V3 next year. So I changed the include parameter to match. Also some small changes to the comments and arrangement in the script.

Also I noticed that the script didn't run well and stopped after a few reloads when the tab ran in background. This didn't happen before and might be because of other running websites (Youtube, Twitch). Moving the tab to a seperate window solved the issue. So just a suggestion if people have the same difficulty to move the script running tab to a seperate window.

@muhdiboy

Copy link
Copy Markdown
Author

Hi everyone,

I've added many improvements to the script and updated the Readme. A button to start the script along with prompts to customize the script has been added.
Be sure to test it out. 😁

@bloodclot

Copy link
Copy Markdown

This does not work for me on a clean install of Chrome and FFX. This is what happens on chrome when any number of pages are entered in https://imgur.com/a/MzeToEo

On FFX, the button never appears

@muhdiboy

muhdiboy commented Jun 23, 2023 •

Copy link
Copy Markdown
Author

Thank you for providing feedback and putting in the effort to setup a new environment.

If I didn't see wrong you've put in page 5 to stop the script at while being on page 2. That won't work, because the script will stop when hitting that page number or when it has already passed it.

So a working example would be starting at page 5, enter a number lower than the current page, for example 3, and the script will go until it will be at page 3.

I‘ll look into why the button doesn't appear on Firefox, however it did on my testing before publishing.

@muhdiboy

Copy link
Copy Markdown
Author

I've updated the Gist to version 1.4 with many changes and a complete overhaul including a new checkbox, a Cancel button, prompts catching wrong input and many more things working in the background to make it more stable, reliable and easier to use.
It is no longer necessary to modify the script, everything is done via the buttons/checkbox.

However, I can confirm, that Firefox isn't behaving the same as Chromium browsers. It often stops after one or two reloads. Manual refresh can help it go further, but that is not efficient.
The Readme has also been updated accordingly.

Feel free to test it out and post your feedback.

@muhdiboy

Copy link
Copy Markdown
Author

Just a small info: Because of Last.fm's dynamic page design the buttons may appear in the wrong pages. This occurs sometimes when changing e.g. from "Library" to "Artists". Pressing them won't do anything because the script will always check before doing something. Also reloading the page will always remove them, if they shouldn't be there.

@bmrs

bmrs commented Jul 31, 2023 •

Copy link
Copy Markdown

Hi,

Thank you for this very enjoyable script. The process is not very smooth on my library with 160,000+ scrobbles on 3267 pages: it stops after a dozen of pages each time. It is running in a separate window from the last page to the page #1. Help appreciated!

@muhdiboy

Copy link
Copy Markdown
Author
Details I can confirm, that the script sometimes has issues to load the next page. I think the issue might be because the event listener (`window.addEventListener('load', function ()`, [line 178](https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1#file-lastfm-automated-remove-duplicates-user-js-L178)) is currently getting loaded after a few checks and inside a function, which might add a miniscule amount of delay.

To test this I added a timeout of 3-5 seconds to the listener, which would result in no reloads. After lowering it to 250 ms the issue could be reproduced more frequently and would almost disappear when reducing it to 25 ms.

I also checked how long it needs to reach the listener and measured ~200 ms. After that it is waiting for the page to load and that takes ~50-100 ms. That means that the script only has ~50 ms of time to reach that point, otherwise it will not run because the listener won't trigger as the website has already been loaded. So I have to minimize that 200 ms time window.

Fixed it by untying the run function from the URL checker function, et voilà, the script is reaching that spot instantly and only has to wait for the webpage to load which triggers the event listener.


Hi @bmrs, thank you for noticing and giving feedback. Please try again with the new version (1.4.3). Enjoy!

@bmrs

bmrs commented Sep 25, 2023

Copy link
Copy Markdown

Hi @bmrs, thank you for noticing and giving feedback. Please try again with the new version (1.4.3). Enjoy!

Yes, it works well now, and way faster… Thank you!

@machineonamission

Copy link
Copy Markdown

Found a bug. On line 201, you add "num", but num is a string and needs to be cast to an int, or else it's concatenated, not added.

@pleebus

pleebus commented Nov 28, 2023 •

Copy link
Copy Markdown

hey dude, loving this script, is helping to do something I thought I was going to have to do semi-manually...

however, I'm hitting the "405 - Method Not Allowed" error every few pages. is this just because my last.fm history is so huge (4,000+ pages going back almost 20 years) with a ridiculous amount of duplicates? I had some bug a few years ago that caused some tracks to be scrobbled literally 50+ times for a single play and have only recently decided to do something about that. Thought this could be the solution, and it's working, but it's also not so stable and crashes after maximum 60 seconds each time I run it. am I doing something wrong, or is it just the size of the task I'm asking it to do?!

EDIT: If it helps to add some more context, it does seem that the redirect to /library/delete happens whenever it hits a block of duplicate songs. I'm using a fresh install of Brave that I downloaded just to run this script. But it's also happening in a fresh Chrome install.

@Jeboose

Jeboose commented Dec 27, 2023

Copy link
Copy Markdown

hey dude, loving this script, is helping to do something I thought I was going to have to do semi-manually...

however, I'm hitting the "405 - Method Not Allowed" error every few pages. is this just because my last.fm history is so huge (4,000+ pages going back almost 20 years) with a ridiculous amount of duplicates? I had some bug a few years ago that caused some tracks to be scrobbled literally 50+ times for a single play and have only recently decided to do something about that. Thought this could be the solution, and it's working, but it's also not so stable and crashes after maximum 60 seconds each time I run it. am I doing something wrong, or is it just the size of the task I'm asking it to do?!

EDIT: If it helps to add some more context, it does seem that the redirect to /library/delete happens whenever it hits a block of duplicate songs. I'm using a fresh install of Brave that I downloaded just to run this script. But it's also happening in a fresh Chrome install.

You're using tampermonkey with lastfm pro? I'm having trouble getting this script to do much of anything it seems to just endlessly scroll through my scrobbles without actually removing any. Tried firefox, chrome, and brave with no results.

@muhdiboy

muhdiboy commented Jan 9, 2024 •

Copy link
Copy Markdown
Author

@reticivis-net

Found a bug. On line 201, you add "num", but num is a string and needs to be cast to an int, or else it's concatenated, not added.

Thank you, I updated it to parse it to int. Version 1.4.4 onwards includes this change.


@pleebus

am I doing something wrong, or is it just the size of the task I'm asking it to do?!
I'm using a fresh install of Brave that I downloaded just to run this script. But it's also happening in a fresh Chrome install.

Sorry, that the script didn't work for you as expected. I've tried on multiple installations (fresh/old + Windows/Ubuntu(Flatpak, DEB)) and couldn't seem to reproduce the mentioned errors.

EDIT: If it helps to add some more context, it does seem that the redirect to /library/delete happens whenever it hits a block of duplicate songs.

Yes, after some retesting, that was what I've experienced too. And it was just that the line "if (window.location.toString().includes("delete")) history.go(-1);" was not in the right place.
Now it should go back in history and retry, if it hits the "405 - Methos Not Allowed" Page. Tested again after this change and it ran flawlessly again.

Change is included in version 1.4.5

@muhdiboy

muhdiboy commented Jan 9, 2024

Copy link
Copy Markdown
Author

@Jeboose
Can you retest with the newest version? If you have a different issue, please retest on a single page where you are sure multiple duplicates exist and report your findings. I will try to help as possible.

Just to be sure, if you didn't know the feature: the script is differentiating duplicates, ones that are scrobbled at exactly the same time (to the minute) and ones where you can choose the amount to be checked. First one is the true duplicate, enabled by the checkmark. Second one is active when the checkmark is unchecked. When unchecked, another input box will appear after hitting the "Remove duplicates" button. There you can input the number of scrobbles to compare to.
This is described in the doc above: Using the script - step by step

@RudeySH

RudeySH commented Sep 4, 2024

Copy link
Copy Markdown

Since June 2024, Last.fm has added rate-limiting. From my own testing I concluded that you can request about 20 pages per minute. Eventually you'll run into this:

image

Page not available
You’re requesting too many pages
You're requesting a lot of pages which may slow down the site for other users. Why not take a break and enjoy a cup of tea?

This messes up the automated script, because it triggers the rate-limiting very fast, and then the script will continuously skip pages until you cancel it.

@muhdiboy

muhdiboy commented Sep 9, 2024

Copy link
Copy Markdown
Author

Hey @RudeySH, thanks for your findings!

I can confirm the script's misbehavior. This issue only started occurring recently.
Unless you plan to monitor the entire process manually and stop/restart the script (which temporarily resets the problem), we need a fix to handle this.

Potential solutions:

  1. Increase Delay Before Reloading:

    • A longer delay between requests could prevent triggering the rate/request limit.
    • This might reduce the chance of encountering the rate-limit page, but may not fully solve the issue.
  2. Detect Text on the Page:

    • The current script relies on URL-based detection, which is not working in this case. It detects the rate-limit page as a normal library page.
    • I should implement a method to search for specific text on each reload and stop the script when it finds the rate-limit text (or something similar).

Also, I couldn’t find any clear documentation on LastFM’s rate-limiting rules, which makes this trickier.
If we had more information, it could help refine the script and avoid hitting the limit.


Something different I wanted to write down:
I've noticed an issue when deleting duplicates: sometimes the "405 - Method Not Allowed" page appears.
Currently, the method used to handle this is by navigating back to the previous page in the browser history.
However, this only works if the "405" page doesn't reappear consecutively, as it may cause the history to point to an incorrect page (e.g., a wrong library page).

To improve this, the method should be updated to store the active page's URL (or at least the page number) and return to this stored page whenever a "405" page is detected.
This would ensure that the script can always return to the last functioning page and continue its operation smoothly.

I'll work on fixing these issues over the following days and will update you via a comment to keep you informed.
Any further suggestions or ideas are welcome and greatly appreciated.

@RudeySH

RudeySH commented Sep 9, 2024

Copy link
Copy Markdown

I'm also maintaining a Last.fm script and have dealt with this issue myself.

I think the best course of action is to make the script detect the rate-limiting page, and automatically pauses for 10/20/30/etc. seconds before automatically trying again.

I advice against detecting the text on the page. The text might differ based on the user language. Instead, I would simply test if the page contains a <table> (or if you want to be really specific, a table with the chartlist CSS class).

A Last.fm script I wrote stores the amount of seconds to wait in a variable. The variable starts at 10 seconds. So, my Last.fm script only waits 10 seconds the first time it gets rate-limited. If it can successfully resume (without immediately getting rate-limited again) after 10 seconds, my script will continue loading pages. The next time it gets rate limited, it will still only wait 10 seconds. However, as soon as it detects rate-limiting immediately after waiting 10 seconds, it increases the variable by 10 seconds. From that moment onwards, the script will wait 20 seconds every time it gets rate-limited. When the script detects rate-limiting immediately after waiting 20 seconds, the variable is increased to 30 seconds. It goes on like that until the variable reaches 60 seconds. This approach might sound convoluted but it allows my script to load pages relatively fast without knowing the exact details of Last.fm's undocumented rate-limiting.

@muhdiboy

muhdiboy commented Oct 1, 2024 •

Copy link
Copy Markdown
Author

Hi @RudeySH,

thank you so much for giving tips. I've decided to go with a 5 second delay and increase it by another 5 seconds with each consecutive rate-limit.


New Release: Version 1.5.0!
Changes:

  • Syntax Adjustments: Improvements made for better readability and performance.
  • Type Fixes: Many variables now have corrected types for better functionality.
  • Functional Changes: Fixed the page reload function and removed clutter during execution.
  • Error Handling Improvement: Enhanced the script to correctly navigate back in case of errors.
  • Rate-Limiting Fix: The awaited solution for rate-limiting issues is now implemented.

If you encounter any issues or have suggestions for further improvements, just let me know!

@dreman6

dreman6 commented Mar 30, 2025 •

Copy link
Copy Markdown

Any reason why it might work for a bit on my end and then stop within a minute or so? It'll get through a page or 2 successfully and then just randomly stop continuing on. It usually happens after It brings me to a 405 error page on lastfm and then back to my library, but after that it stops the deletion process.

@muhdiboy

Copy link
Copy Markdown
Author

Hi @dreman6,

thank you for providing feedback!
I think I've got that issue too. There seems to be another bug, where the script will only delete 1 track and then skip to the next page, which is of course not intended.

I haven't been able to implement a proposed fix for those, because I'm really busy for the last 6 months. Hope everyone can understand.
I will follow in the next month with an update.

Take care!

@muhdiboy

Copy link
Copy Markdown
Author

Hello everyone,

I finally got back to fix this and use it again for myself. There is also a major overhaul, which benefited from my other project -> YTM Block Artist


New Release: Version 2.0.0!
Changes:

  • Replaced the on-page button, checkbox and prompt dialogs with a single floating control panel (bottom-left).
  • Options are now set directly in the panel - no more browser prompt/alert pop-ups.
  • Added a live, color-coded log and a running deletion counter; the final total is shown on completion.
  • Fixed real-duplicate mode comparing only a short window of rows, which caused it to delete one duplicate and skip ahead.
  • Fixed the script stopping after returning from a 405 page.
  • More robust page-number tracking so the log and stop condition stay accurate through rate-limit and 405 bounces.

I hope it was worth the wait! Please keep me posted if there any bugs.
Maybe I will create an addon from this, who knows 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment