DSLC Slack: Changing Window Titles in Shiny
·1 min
dslc-slack
q-a
shiny
r
I greatly enjoy the DSLC Slack Community (
dslc.io/join),
and spend a fair bit of time answering questions! This post is part of a series
where I curate some interesting questions and/or answers that I’ve come across there.
Dhiraj
asks:
#
I have a shiny application which uses the navbarPage() layout. The app has multiple tabPanels with their own titles. Is it possible to have the windowTitle of the navbarPage dynamic to show the titles of the tabPanels ?
Answer #
Here’s a minimal example of the Shiny and JS code you’ll need:
library(shiny)
library(tidyverse)
custom_js <- 'Shiny.addCustomMessageHandler("handler_windowtitle", switch_window_title );
function switch_window_title(message){
document.title = message;
}'
ui <- navbarPage(
title = 'navbarpage',
id = 'displayed_tab',
tags$head(tags$script(custom_js)),
tabPanel(title = "StrangePlanet"),
tabPanel(title = "DarthVader")
)
server <- function(input, output, session) {
observeEvent(
input$displayed_tab,
session$sendCustomMessage("handler_windowtitle",input$displayed_tab)
)
}
shinyApp(ui, server)
If you give navbarPage an ID, it’ll create an input
variable that can be accessed as input${id}
, returning the value argument of the tabPanel. In this case, tabPanel returns the title
argument as the default value - you can specify something else if you prefer.
In a production app, I’d also move the JS into a separate JS file (stored in www) and use includeJS()
instead of using the tags$script
method.
Related
DSLC Slack: Explaining Shiny to Your IT Team
·6 mins
dslc-slack
q-a
shiny
r
Helping present the business architecture for Shiny in production to a relatively technical (but not R-based) crowd
DSLC Slack: Debugging Netlify Deploys
·2 mins
dslc-slack
q-a
r-in-production
r
A quick example of reading through automated deploy logs, finding the relevant errors, and triaging a fix - transcribed from the DSLC Slack Community help channels
DSLC Slack: Things I Learned From Advanced R Book Club
·3 mins
dslc-slack
r
A non-exhaustive list of things I learned from each of the sections of Advanced R while participating in R4DS Slack’s Advanced R Book Club.