簡體   English   中英

Shiny:如何更改 Shiny 中的頁面/窗口標題?

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

有很多關於更改其他 Shiny 應用程序標題的帖子,例如:
按 shiny 按鈕更改標題 Shiny R
Shiny 頁面標題和圖片
Shiny 應用程序:如何在 server.R 中動態更改框標題?

我的問題是相關的,但其中任何一個都沒有回答。 我想讓<head><title>...</title></head>標記具有反應性,或者至少可以從 server.R 中的observeEventserver.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)
      }
    })
}

我嘗試使用該observeEvent中的if..else邏輯制作output$theTitle <- renderText({...}) ,然后在uifluidPage中設置title = textOutput("theTitle") ,但這會生成<div...>作為標題文本,或者<span...>如果我們將inline=True傳遞給renderText

如果這澄清了我正在尋找的東西,答案將使一些東西等同於由生成的文字(用該字符串替換字符串變量) ui

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

在用戶在框中輸入任何文本之前; 如果他們輸入了“Shiny is great!” 進入input$pageTitle的盒子,然后我們會得到文字

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

一種方法是編寫一些 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)

這是根據如何使用 Shiny 指南將消息從瀏覽器發送到服務器並返回

As of June 2021, there is an R package called shinytitle that can update the window title from within Shiny's reactive context: https://cran.r-project.org/package=shinytitle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM