闪亮:如何在“闪亮”中更改页面/窗口标题?

时间:2020-08-04 21:32:21

标签: r shiny

关于更改其他Shiny应用程序的标题的帖子很多,例如:
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?

我的问题是相关的,但没有一个得到回答。我想使<head><title>...</title></head>标签具有反应性,或者至少可以从observeEvent中的server.R内部进行控制。

由于ui找不到theTitle,以下操作不起作用,但是我希望这种方法是可能的:

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

我尝试使用output$theTitle <- renderText({...})中的if..else逻辑制作observeEvent,然后在title = textOutput("theTitle")的{​​{1}}中设置ui ,但会生成fluidPage作为标题文本,如果我们将<div ...>传递给<span ...>,则会生成inline=True

如果这能澄清我在寻找什么,答案将等同于文字(用该字符串代替字符串变量)renderText

ui

在用户在框中输入任何文本之前;如果他们输入了“发光很棒!”放入ui <- fluidPage( title = "No title yet.", .... ) 的框中,我们将得到原义

input$pageTitle

1 个答案:

答案 0 :(得分:2)

一种方法是编写一些JavaScript来解决这一问题。例如

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)

这是在How to send messages from the browser to the server and back using Shiny guide

之后创建的