I'm developing a Chrome extension and I have a button. When this button is clicked, it gets a random URL from JSON. I don't want the last URL to be the same as the random URL currently received. How can I get random URL until the data is different?
Javascript
var music;
var lastMusic; // Suppose I got this data.
window.addEventListener("load",function() {
fetch('***data.json', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
try {
if(json.last_version !== chrome.runtime.getManifest().version) {
$id("new-update").style.display = "block";
}
music = json.musics[Math.floor(Math.random()*(json.musics.length + 1))].url;
} catch (error) {}
});
},false);
UPDATE
I solved problem but Chrome throws an error Uncaught TypeError: Cannot read properties of undefined (reading 'url')
var music;
var lastMusic;
window.addEventListener("load",function() {
fetch('https://kortopal.github.io/data/11a/data.json', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
try {
var musicInterval;
if(json.last_version !== chrome.runtime.getManifest().version) {
$id("new-update").style.display = "block";
}
musicInterval = setInterval(function() {
music = json.musics[Math.floor(Math.random()*(json.musics.length + 1))].url; // Error Line
if(music !== lastMusic){
clearInterval(musicInterval);
lastMusic = music;
setStorage();
loadStorage();
}
}, 100);
} catch (error) {}
});
},false);