Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get screen resolution from JavaScript in R Shiny?

I want to get screen resolution from JavaScript, stored in the GetScreenWidth variable on Shiny Server.

I tried the reference:

  1. Receiving data from .js in server.R shiny
  2. https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/

So I have:

ui.R

shinyUI(
  bootstrapPage(

    verbatimTextOutput("results")
    ,tags$script('
        var jsWidth = screen.width;
        Shiny.onInputChange("GetScreenWidth",jsWidth);
    ')
   )
 )

server.R

 shinyServer(function(input,output){

     output$results=renderPrint({
     input$GetScreenWidth
   })

 })

It will return NULL by verbatimTextOutput.

How should I modify the code? Thanks!

like image 450
Robin Chen Avatar asked Oct 21 '15 02:10

Robin Chen


1 Answers

The problem is that you're running the JavaScript code before Shiny is initialized. You can use the new feature that tells you when shiny is ready, here's example code

jscode <-
'$(document).on("shiny:connected", function(e) {
  var jsWidth = screen.width;
  Shiny.onInputChange("GetScreenWidth",jsWidth);
});
'

library(shiny)
runApp(shinyApp(
  ui = fluidPage(
    tags$script(jscode)
  ),
  server = function(input, output, session) {
    observe({
      cat(input$GetScreenWidth)
    })
  }
))
like image 107
DeanAttali Avatar answered Nov 02 '22 09:11

DeanAttali