The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

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

Answer №1

Problem solved!
Switching the URL to HTTPS or localhost did the trick.
After making that change, everything began functioning properly.

All issues resolved successfully.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch between two tabs with the convenient toggle button

I have implemented 2 tabs using Bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">CLient</a></li> <li role="presentatio ...

Perform a replacement with jQuery.replaceWith() on an input field and refocus in Microsoft Internet Explorer

There exists a script http://gist.github.com/457324 which establishes default text (extracted from the element's title attribute) for empty input[type=text] as well as input[type=password] elements. However, setting default text for password elemen ...

While attempting to run the project I downloaded from GitHub using the command npm run serve, I encountered the following error: "Syntax Error: Error: No ESLint configuration found in

After receiving a Vue.js project from GitHub, I attempted to download and run it. However, when I tried the command npm run serve, I encountered an error message: Syntax Error: Error: No ESLint configuration found in C:\Users\User\Desktop&bs ...

I am attempting to load the ajax content into separate divs simultaneously

When I attempt to load the ajax into two separate divs, I notice that despite calling for data to be placed in two different divs within the ajax code, it all ends up in one div. <script>$(document).ready(function(){ $.ajax({ url: "http: ...

I'm curious if there is an eslint rule specifically designed to identify and flag any unnecessary spaces between a block comment and the function or

Can anyone help me find a solution to prevent the following issue: /** * This is a comment */ function foo() { ... } I need it to be corrected and formatted like this: /** * This is a comment */ function foo() { ... } ...

Best practices for handling errors beyond network problems when using the fetch() function

I am facing a situation where the route of my fetch() call can result in two different responses, each requiring a different action. However, I have noticed that the catch() method only handles network errors as far as I know. Currently, my code looks lik ...

Innovative Audio Editing Tool using Javascript

Currently, I am in the process of creating a JavaScript-based audio editor that will allow users to record, play, and edit audio files. It is crucial for the tool to be able to visualize both real-time recorded audio and selected/uploaded audio files. Whil ...

Issue with Tweening in Three.js: Initial value does not change

Having trouble with tweening my camera position. I've set up a Codepen with minimal code to showcase the issue, complete with annotations and plenty of console.log() statements for debugging purposes. Check out the Codepen The starting point of my c ...

What is the best way to eliminate the appended content within the tbody?

The code snippet below is functioning correctly. I am trying to retrieve the ID or Class of the appended data from the checkbox. However, when I use the following code $('.chk').click(function(){ console.log(cc);}), it does not work as expected. ...

Uninterrupted movement within a picture carousel

Seeking a way to create a smooth transition in an image slider with sliding dividers using continuous switching when clicking previous/next buttons. Currently, the dividers replace each other from far positions. Any ideas on achieving a seamless single mov ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

Click the button to dynamically add a Bootstrap select element

I need assistance creating a select element with a Bootstrap class using a button click event. The element is successfully inserted into the body, but it does not appear on the page. https://i.sstatic.net/ppHfL.png <html> <head> <link re ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

Tips for properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

Having trouble running the d3js example on Ionic 2

I am having trouble running the example provided in this link: https://github.com/abritopach/ionic2-d3js-example Even after installing the latest Ionic 2 version and npm, I encounter an error when trying to run the app, as shown in the browser console. p ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

What is the best way to transfer Kendo Grid row data to a Kendo popup window within a partial view using jQuery?

I am currently facing a challenge in passing the row data from the Kendo Grid to a partial view that is displayed through a Kendo popup window. Within the partial view, users have the option to upload an image file related to the specific row record. This ...