I'm grappling with a JavaScript issue and need some help.
You can find the demo of the functioning script by the author right here.
I've implemented the same code as displayed on his demo page.
I've downloaded the worker.js file and it's safely stored in my JS folder.
The code reflects this setup:
if ('serviceWorker' in navigator) { var iceworker = navigator.serviceWorker.register('worker.js')
//In Google Chrome, I encounter this error
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
//Specifically at this line.
navigator.serviceWorker.addEventListener('message', event => {
This is the script extracted from the provided link above.
<audio preload="none" id="aud" controls src="https://toohotradio.net/metadata/icy/" type="audio/mpeg">
</audio>
<div></div>
<ul>
</ul>
<script>
if ('serviceWorker' in navigator) {
var iceworker = navigator.serviceWorker.register('metadataworker.js')
.then(function(reg) {
console.log('Icecast service worker registered');
addItem('Icecast service worker registered. Click play to start the stream.');
}).catch(function(error) {
console.warn('Error ' + error);
addItem('Error ' + error);
});
}
var delay = 8000;
navigator.serviceWorker.addEventListener('message', event => {
if(event.origin != 'https://toohotradio.net'){
return;
}
setTimeout(function(){
document.querySelector('div').innerText = event.data.msg.substring(event.data.msg.indexOf("'") + 1,event.data.msg.lastIndexOf("'"));
},delay);
console.log(event.data.msg);
addItem('Message from service worker ' + event.data.msg);
});
document.querySelector('audio').addEventListener('play', event => {
performance.mark('play');
addItem("Measuring buffering time...");
})
document.querySelector('audio').addEventListener('playing', event => {
performance.mark('playing');
performance.measure('delay','play','playing');
var measures = performance.getEntriesByName("delay");
delay = measures[0].duration;
addItem("Buffering took " + (delay/1000).toFixed(2) + " seconds");
addItem("Setting metadata update delay to " + (delay/1000).toFixed(2) + " seconds");
})
document.querySelector('audio').addEventListener('pause', event => {
navigator.serviceWorker.controller.postMessage('message');
document.querySelector('audio').src = document.querySelector('audio').src;
})
function addItem(text) {
var node = document.createElement("li");
var textnode = document.createTextNode(text);
node.appendChild(textnode);
document.querySelector('ul').appendChild(node);
}
</script>
I've carefully checked through the code and swapped out all instances referencing his domain with mine.
You can access the source code for the JavaScript function here.
Source Code for Javascript
Any assistance in getting this working would be greatly appreciated.
Thank you.
Wayne