The error message "Uncaught (in promise) DOMException: play() could not be executed as there was no prior user interaction with the document" indicates

var buttonColours = ["red", "blue", "green", "yellow"];

var gamePattern = [];

function nextSequence() {

  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColour = buttonColours[randomNumber];
  gamePattern.push(randomChosenColour);

  $("#"+randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);

  var audio = new Audio("sounds/"+randomChosenColour+".mp3");
  audio.play().catch(function(error) {
    console.log("Error occurred: " + error.message);
    // Add a play button for user interaction with the document
  });
}

nextSequence();

The play() function is not working and it is giving the error "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first."

Suggest some fix.

Answer №1

This feature is incorporated in modern browsers to prevent malicious or spam activities carried out by website developers. Essentially, web pages are restricted from automatically playing videos or audios unless the user interacts with the website first (such as clicking, hovering, pointing, etc.).

Therefore, in your situation, the nextSequence() function should be triggered when the user clicks on something, for instance.

document.getElementById("playbutton").addEventListener("click", nextSequence);

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

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...

What is the best way to receive several responses from a PHP file using AJAX?

My PHP file is handling 2 operations: 1. Submitting data from a form into a database table, and 2. Sending an email. I am looking to display status messages through ajax. For instance, showing "First operation done, please wait for the second" and then di ...

What is the correct way to display the date in a React application?

I am working on a project that involves integrating solidity contracts into a web portal. In one of the contracts, I have stored dates as uint values like this: 1539491531. However, when I display these dates on the web page, they appear different from wh ...

Encoding and decoding a two-way stream in NodeJS

I am looking to encapsulate a socket within another object that has the following features: - transforms output, such as converting strings into Base64 format - transforms input, such as converting Base64 back into strings (Please note: while my specif ...

What is a unique method for creating a wireframe that replicates the structure of a square grid without using interconnected nodes

Currently, I am in the process of designing the wire frame styles for human body OBJs and my goal is to achieve a wire frame similar to the image below. In the following lines, you will find the code snippets that illustrate how I create the wire frame alo ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

Error encountered while using the getJSON code syntax

Is there an issue with this code snippet? I am receiving a syntax error on line 1: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="http:/ ...

Using the Coinbase.com API with HMAC authentication in a Node.js environment

I recently delved into some node.js documentation, specifically crypto and https, in an attempt to utilize the coinbase.com API within my coin.js file to retrieve the bitcoin balance of my account. However, I am encountering errors. Upon running the code w ...

Adjust color in real-time with JavaScript

I am using a json file to store data for generating a diagram, and I want to change the color of the diagram conditionally based on an attribute in the json. If the attribute is false, the color should be red, and if true, it should be green. Here is a sni ...

Retrieving the selected value from a dropdown using jQuery's `$('#id').val()` may not always provide the desired result

I am having trouble retrieving the selected value from a dropdown menu as it keeps returning either an empty string or undefined results. My HTML code is structured like this: <div class="input-group" style="padding-bottom: 10px;"> <span id= ...

When the page is scrolled, trigger a click event on the next button in

Currently, I have a listing page that features pagination at the bottom. However, my goal is to transform this into an infinite loading page. The issue I am facing is that when the click event triggers after scrolling to the bottom, it makes calls for pag ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResul ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Within the Django framework, where should I place the Python script that needs to be called by a JavaScript function?

When it comes to Django and file locations, I often find myself getting confused a lot, especially since I am using Django 1.10. Currently, in my static/(django-proj-name)/js/ folder, I have my main.js file where I need to call a Python script along with t ...

Display multiple selection using JavaScript based on the element ID

I have a task to display the selected id using JavaScript, but currently, only the first select id is shown. Here is my HTML and JavaScript code: <tr> <td> <select name="jens_id[]" id="jens_id" required="" > <option ></op ...

What is the best way to add a radial pattern to a ring using three.js r67?

I am facing a challenge in applying a texture to a ringGeometry using three.js r67. The issue lies in orienting the texture correctly. My goal is to apply a specific texture to a ringGeometry mesh in a radial manner, where the blue end of the texture align ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...