Shiny: How to change the page/window title in Shiny?

自作多情 提交于 2021-01-29 22:57:41

问题


There are numerous posts regarding changing titles of other pieces of Shiny apps, e.g.:
Change the title by pressing a shiny button Shiny R
Shiny page title and image
Shiny App: How to dynamically change box title in server.R?

My question is related, but not answered by any of these. I would like to make the <head><title>...</title></head> tag reactive, or at least controllable from within an observeEvent in server.R.

The following does not work, since ui can't find theTitle, but is the kind of approach I'd hope is possible:

library(shiny)

ui <- fluidPage(
   title = theTitle(),
   textInput("pageTitle", "Enter text:")
)

server <- function(input, output, session) {
    theTitle <- reactiveVal()
    
    observeEvent( input$pageTitle, {
      if(is.null(input$pageTitle)) {
        theTitle("No title yet.")
      } else {
        theTitle(input$pageTitle)
      }
    })
}

I've tried making output$theTitle <- renderText({...}) with the if..else logic in that observeEvent, and then setting title = textOutput("theTitle") in ui's fluidPage, but that generates <div ...> as the title text, or <span ...> if we pass inline=True to renderText.

In case this clarifies what I'm looking for, the answer would make something equivalent to the literal (replacing string variables with that string) ui generated by

ui <- fluidPage(
    title = "No title yet.",
    ....
)

before the user has entered any text in the box; if they have entered "Shiny is great!" into input$pageTitle's box, then we would get the literal

ui <- fluidPage(
    title = "Shiny is great!",
    ....
)

回答1:


One way would be to write some javascript to take care of that. For example

ui <- fluidPage(
  title = "No title yet.",
  textInput("pageTitle", "Enter text:"),
  tags$script(HTML('Shiny.addCustomMessageHandler("changetitle", function(x) {document.title=x});'))
)

server <- function(input, output, session) {
  observeEvent( input$pageTitle, {
    title <- if(!is.null(input$pageTitle) && nchar(input$pageTitle)>0) {
      input$pageTitle
    } else {
      "No title yet."
    }
    session$sendCustomMessage("changetitle", title)
  })
}

shinyApp(ui, server)

This was created following the How to send messages from the browser to the server and back using Shiny guide



来源:https://stackoverflow.com/questions/63255351/shiny-how-to-change-the-page-window-title-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!