(Note that in the gif, it is run in a browser console, but after reading this post you’ll know how to implement the same action in the Shiny app.)
Here the great help comes with the shinyjs package by Dean Attali. All you need to do is wrap the pure JS code given as a string into shinyjs::runjs() and use it as a replacement for your standard R solution (please do remember to initialize the package in your ui file with useShinyjs() – check package description for details). The main advantage of this method is how easy it is to incorporate the R objects that you’re familiar with: put them inside the string passed as JS code (we encourage using something like sprintf or glue to do this, not a series of paste). Here is an example of the usage for the gif:
Implementing it into your Shiny app requires the following steps:
1. Create a JS file named shinyjs.functionName.js (functionName to be replaced with your functionality) in the dedicated folder in your app (usually shiny/www/js)
2. Define the content of the file as follows – some boilerplate code is needed at the beginning. (of course the names, number and default values of the parameters are up to you):
3. Add the JS extension to your ui file, in your dashboardBody/semanticPage/mainPanel, namely:
(note: there can be more than a single function defined per file, but to organize the code better we recommend keeping them separated and naming file the same as functions)
4. Now you can use the function! Wherever you wish in the code (e.g. in observe or observeEvent) just call js$functionName() and set (in this test case) the two defined parameters, param_1, param_2.
As you can see, this method requires a little more effort when defining in comparison to inline JS code, but it hides your JS code in the function, thus making the code clearer and allows you to use the same function in many places, thus making your code more DRY.
– the result should be the same as using R code to generate notifications.
Thanks for reading! Follow me on Twitter @dubelmarcin. You can also check out the first post in the series, Super Solutions for Shiny Architecture 1 of 5: Using Session Data. And don’t forget to sign up for our newsletter!