0

hello, i have a simple button

<a onclick="window.location.href=window.location.href" class="btn"> Stop </a>

and i have an audio source

<audio id="myAudio"> <source src="https://myweb.com/files/tuntun.mp3" type="audio/mpeg"> </audio>

and this is javascript

<script> 
var x = document.getElementById("myAudio");
function playAudio() { 
x.play();
} 
</script>

i want the audio play before refreshing the page when i click the button, i tried but my audio stops while refresh. Bye the way i need it for ANDIOID Browser

I hope you can understand what I need because I'm bad at English

King Moaz
  • 25
  • 3
  • Does this answer your question? [Run JavaScript code on window close or page refresh?](https://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close-or-page-refresh) – Justinas Mar 13 '22 at 18:54
  • @Justinas: That anser is from 2012. `beforeUnload` now does not allow to run any script. It only throws an non-custumizable prompt to the user to confirm leaving the page. – Louys Patrice Bessette Mar 13 '22 at 18:56

1 Answers1

1

You will have to run a function on click... That will play the audio and then will refresh the page.

<a onclick="playAudio()" class="btn"> Stop </a>

<audio id="myAudio"> <source src="https://myweb.com/files/tuntun.mp3" type="audio/mpeg"> </audio>

<script>
let stopFlag = false
let x = document.getElementById("myAudio");

function playAudio() {
  // Set a flag to know if the "stop" link was clicked
  stopFlag = true
  x.play();
}

// An event listener to reload the page after the video has ended if the "Stop" link was cliked
x.addEventListener('ended', () => {
  if(stopFlag){ 
    window.location.reload()
  }
})
</script>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64