Javascript works multiple times locally but only once in the server

I use JavaScript for updating tabs. Although it works as expected locally, in the server it only works once as I click the button take triggers the JavaScript command (it should work any time I click the button). Any ideia how to fix this?

Here is the code with the example


library(shiny)
library(shinymaterial)

js <- "
$(document).on('shiny:connected', function() {
  Shiny.addCustomMessageHandler('selectTab', function(tab) {
    var tabs = document.querySelector('ul.tabs');
    var instance = M.Tabs.getInstance(tabs);
    instance.select(tab);
  });
});
"

ui <- material_page(
  
  tags$head(tags$script(HTML(js))),

  title = NULL,
  
  # Define tabs
  material_tabs(
    tabs = c(
      "First Tab" = "first_tab",
      "Second Tab" = "second_tab",
      "Third Tab" = "third_tab"
    )
  ),
  # Define tab content
  material_tab_content(
    tab_id = "first_tab",
    tags$h1("First Tab Content"),
    material_button("btn1", "Go to tab 2")
  ),
  material_tab_content(
    tab_id = "second_tab",
    tags$h1("Second Tab Content"),
    material_button("btn2", "Go to tab 3")
  ),
  material_tab_content(
    tab_id = "third_tab",
    tags$h1("Third Tab Content"),
    material_button("btn3", "Go to tab 1")
  )
)

server <- function(input, output, session) {
  
  observeEvent(input$btn1, {
    session$sendCustomMessage("selectTab", "second_tab")
  })  
  
  observeEvent(input[["btn2"]], {
    session$sendCustomMessage("selectTab", "third_tab")
  }, ignoreInit = TRUE)  
  
  observeEvent(input[["btn3"]], {
    session$sendCustomMessage("selectTab", "first_tab")
  }, ignoreInit = TRUE)  
  
}

shinyApp(ui = ui, server = server)