Frontend Javascript

How can I request user permission for audio on Chrome?

Simply make your own alert modal. You can feature detect if it is required or not by trying to play your audio while muted

const audio = new Audio( 'https://dl.dropboxusercontent.com/s/h8pvqqol3ovyle8/tom.mp3' );
audio.muted = true;

const alert_elem = document.querySelector( '.alert' );

audio.play().then( () => {
  // already allowed
  alert_elem.remove();
  resetAudio();
} )
.catch( () => {
  // need user interaction
  alert_elem.addEventListener( 'click', ({ target }) => {
    if( target.matches('button') ) {
      const allowed = target.value === "1";
      if( allowed ) {
        audio.play()
          .then( resetAudio );
      }
      alert_elem.remove();
    }
  } );
} );

document.getElementById( 'btn' ).addEventListener( 'click', (e) => {
  if( audio.muted ) {
    console.log( 'silent notification' );
  }
  else {
    audio.play();
  }
} );

function resetAudio() {
  audio.pause();
  audio.currentTime = 0;
  audio.muted = false;
}
.alert {
  font: 14px Arial, sans-serif;
  position: fixed;
  top: 0;
  left: 0;
  background: white;
  border: 1px solid lightgray;
  box-shadow: 3px 3px 12px lightgray;
}
p { margin: 12px; }
.alert .buttons {
  float: right
}
<div class="alert">
  <p>This webpage would like to play sounds</p>
  <p class="buttons">
    <button value="0">Block</button>
    <button value="1">Allow</button>
  </p>
</div>
<button id="btn">trigger notification</button>

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *