R Shiny - Trigger a shinyalert popup directly from the UI using javascript

1.1k Views Asked by At

With the following piece of code I'm able to trigger a pure javascript alert by clicking on the question-mark of the fileInput:

enter image description here

            fileInput('peptides', 
                      span("Peptides file  ",
                           id="peptidesSpan",
                           tags$a(
                             tags$i(class='fa fa-question-circle'),
                             href = "#",
                             onclick = "alert('Oops!'); return false;")
                      ),
                      multiple=FALSE,
                      accept = c('text/csv','text/comma-separated-values',
                      )
            )

I was wondering if I could trigger a shinyalert popup (https://github.com/daattali/shinyalert/) instead of a simple javascript alert directly form the UI without any observer in the server side.

Something like:

shinyalert("Oops!", "Something went wrong.", type = "error")

If there is not a workaround to do that, any other suggestion with an observer would be welcome as well.

2

There are 2 best solutions below

0
On BEST ANSWER

I think using an observer is not at all inconvenient.

Instead of alert(), invoke Shiny.setInputValue(id, value);, and then on your server side you can observeEvent(input[id], { shinyalert() }).

Read this article for details: https://shiny.rstudio.com/articles/communicating-with-js.html

You only need to use one observe code block to achieve this.

An example

Define a customized function in your UI Javascript code and call it in your onclick. You can put this function say in helper.js in the 'www' folder in your project folder, that will be www/helper.js. Include this file in your Shiny UI code by tags$head(tags$script(src = "helper.js"))

function showAlert(message, type = "info") {
  Shiny.setInputValue(
    'alertMessage',
    {
      message: message,
      type: type
    },
    { priority: 'event' }
  );
}

Then on the Shiny server side define the observer once

observeEvent(input$alertMessage, {
  alertData <- input$alertMessage
  req(alertData)

  shinyalert("title", alertData$message, type = alertData$type)
})

1
On

It's one of the few times that I answer my own post, but after searching a bit more on stack-overflow I found a workaround inspired by this post.

  1. I downloaded the sweetAlert.js file of the Sweet Alert library directly from here
  2. I create a www folder in the root of my Shiny application
  3. I added the sweetAlert.js file in the www directory and in the dashboardBody() of the ui.R I added the following line:

    tags$head(tags$script(src="sweetAlert.js"))

Now I'm able to call directly the Swal.fire function with any argument as I would normally do in any other framework which runs javascript.