简体   繁体   中英

How to show a (modal) popup only once per user in R/Shiny?

I like to show a popup in an R/Shiny application, but only once per user (sort of like a GDPR cookie banner). shinyalert looks great, but it does not seem to support setting a cookie to show the popup only once. How can I do this easily? Is there any implementation that does not require writing extra JavaScript functions?

Here is how you can do it. This demo uses a js library called " js-cookie ", an easy API to get and set cookies. No need to use additional R packages.

library(shiny)

ui <- fluidPage(
  HTML('<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>'),
  tags$script(HTML(
    '
    $(document).on("shiny:connected", function(){
      var newUser = Cookies.get("new_user");
      if(newUser === "false") return;
      Shiny.setInputValue("new_user", true);
      Cookies.set("new_user", false);
    });
    '
  ))
)

server <- function(input, output, session) {
  observeEvent(input$new_user, {
    req(input$new_user)
    showModal(modalDialog(
      easyClose = TRUE, footer = NULL,
      h1("Welcome new user!")
    ))
  })
  
}

shinyApp(ui, server)

If the CDN is not working, use the link to js-cookie github download and replace the script with your local copy.

The trick here is you store the info in browser's cookie. Every time users visit, get the cookie first then decide if you show the modal.

This method will only show the modal to each user only once and even if they refresh the browser , it will not appear again.

You need to open cookie settings to clear current cookies in order to see the modal again. Here I use Chrome as an example.

在此处输入图片说明 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM