5

My question is rather simple. I am building a Shiny application where the user can switch between predefined languages with a button. However I would like to start each session with the user's language already displayed in the text, so is there a way to retrieve the language defined in the browser or operating system of the user, like as a function that returns a character variable?

I saw that there were many questions about this subject already on this site, but there are for other computing languages than R/Shiny and I have no idea how to adapt them to R. Thanks

agenis
  • 8,069
  • 5
  • 53
  • 102
  • For the multilingual part of my app I'm using parts of the code of Chrisphe Ladroue here https://github.com/chrislad/multilingualShinyApp – agenis Dec 11 '17 at 10:01

1 Answers1

7

This answer is based on the content from an SO answer and a blog link. Code flow:

A plain javascript code to get Browser language is run using runjs of shinyjs package (instead this could be run with tags$script too). Also note that the browser language value is stored in a javascript variable language which is then passed back to R and displayed as a text.

jscode <- "var language =  window.navigator.userLanguage || window.navigator.language;
Shiny.onInputChange('mydata', language);
console.log(language);"
library(shiny); library(shinyjs)
shinyApp(
  ui = fluidPage(
    useShinyjs(),

    "This is your browser language",
    textOutput('your_lang')

  ),
  server = function(input, output,session) {
    runjs(jscode)
 output$your_lang <- renderPrint(input$mydata)
  }
)

Screenshot:

enter image description here

amrrs
  • 6,215
  • 2
  • 18
  • 27
  • thanks a lot, it works well. Can you explain how this piece of javascript works? It generates a new input variable? – agenis Dec 11 '17 at 11:24
  • 1
    @agenis I've added some description please check and also please mark right if it works. Thanks. – amrrs Dec 11 '17 at 11:27