rshinyshinyalert

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


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.


Solution

  • 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)
    })