Chapter 3 JS in Shiny
3.1 Add JS to Shiny
How to add JavaScript to {shiny}
?
3.1.1 With {golem}
golem::add_js_file()
Simple JS file
golem::add_js_handler()
Shiny Handlers
3.1.2 Link in your app
3.1.2.2 With htmlDependency()
- Create an
htmlDependency
object:
dep_binding <- function() {
htmlDependency(
"dep","0.1.0",
src = system.file("app/www", package = "expl"),
stylesheet = c(
"css/uikit.css",
"css/custom.css"
),
script = c(
"input-fleche.js",
"input-nav.js",
"input-progress.js",
"input-rangeSlider.js",
"input-select.js",
"input-onoff.js",
"input-sqonOff.js",
"input-radioButton.js",
"input-checkbox.js",
"input-increment.js",
"panel.js"
),
meta = list(
lang="fr"
),
head = HTML(
'<meta http-equiv="X-UA-Compatible" content=="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Raleway:400,600,700|Roboto+Slab:300,400,700" rel="stylesheet"> '
)
)
}
Then in R/app_ui.R
golem_add_external_resources <- function(){
#...
dr_binding()
}
3.2 The JavaScript Shiny Object
In the browser, there is a Shiny
JavaScript object.
3.2.1 Set the value of an input from JavaScript
- From your browser, you can set the value of a Shiny input:
Shiny.setInputValue(id, value, options)
With
{priority : 'event'}
, the value is sent even if the value hasn’t changed (not the default behavior)
Shiny.setInputValue("pouet", 12, {priority : 'event'})
pouet
will appear asinput$pouet
observeEvent( input$pouet , {
})
3.3 Shiny JS Handlers
- Pass data from R to JS (from server to browser)
Shiny.addCustomMessageHandler('alert', function(arg) {
alert(arg.val);
alert(arg.size);
});
Send with
session$sendCustomMessage()
To pass multiple value, pass a list, then access with
.name
session$sendCustomMessage("alert", list(
val = 2,
size = 11
))