Audio Player: How to download tracks directly

Want to download tracks straightaway without redirecting to another tab? We’ve got a solution :tada:

The only thing you should do is to add this code to the Custom JS field on the Style tab of your widget’s settings:

const downloadButtonSelector = "a[download][href][class*='Button__StyledButton-sc']";

function getFileName(url) {
	const urlParts = url.split('/');

	if (urlParts.length === 0) {
		return '';
	}

	return urlParts[urlParts.length - 1];
}

document.addEventListener("click", (e) => {
	const link = e.target.closest(downloadButtonSelector);

	if (!link) {
		return;
	}

	e.preventDefault();
	e.stopImmediatePropagation();

	const fileURL = link.getAttribute('href');

	fetch(fileURL)
		.then(resp => resp.blob())
		.then(blob => {
			const url = window.URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = getFileName(fileURL);
			a.click();
			window.URL.revokeObjectURL(url);
		});
});

Keep in mind, that the changes won’t be visible within the editor. To check how it works, you need to test this feature on your website.

Now, when pressing the “Download” button, the process of downloading a track should start immediately without redirecting you to another tab.


Got question or faced difficulties? Drop us a line in the comments and we’ll be happy to help :slightly_smiling_face: