Background of the issue

Recently, we were working on a feature where we wanted to autoplay the audio.

So like a normal developer we did the following:

<audio autoplay data-audio-target="audioElement">
  <source src="https://www.xyz/...">
</audio>

Since this is a rails project and we have turbolinks on, we came across an interesting issue.

Whenever we were navigating from the page with the audio element to any other page the audio from the previous page used to play.

We tried to search the same and came across few issue in the turbolinks repository.

We found few solutions but since we were using stimulus js we solved it with the following approach

The solution

We removed the autoplay from the <audio> element.

<audio data-audio-target="audioElement">
  <source src="https://www.xyz/...">
</audio>

We added this on connect() in our stimulus controller. So whenever the controller is connected we play the audio.

import { Controller } from "stimulus";

export default class extends Controller {
  //...

  connect() {
    this.audioElementTarget.play();
  }

  //...
}

This resolved our issue and gave us more control over the audio element.