1

I added references to css and javascript files as follows:

  tags$link(rel="stylesheet", type="text/css", href="rtp.css"),
  tags$script(type="text/javascript", src = "rtp.js"),

How do I make a call to a javascript function defined in "rtp.js"? I have tried

tags$script(type="text/javascript", src = "myfunction()")

(which does not work).

AlexRos
  • 13
  • 1
  • 5

2 Answers2

2

You can use the JS() function from htmlwidgets package (I think it comes by default with shiny)

To add a custom function executing at the start of the application:

tags$script(JS('alert("initialized!")'))

tags$script(JS('myfunction()'))

If myfunction() resides in an external file, first import it and the execute:

tags$script(type="text/javascript", src = "rtp.js"),
tags$script(JS('myfunction())'))
polkas
  • 3,797
  • 1
  • 12
  • 25
GGamba
  • 13,140
  • 3
  • 38
  • 47
  • Thanks @GGamba, sorry I'm a complete JS newbie. I added JS('myfunction()') to my code, but shiny prints the expression rather than calling the function. What am I doing wrong? – AlexRos Feb 24 '17 at 08:50
  • You have to add a bit of context, what are you trying to accomplish with the js function()? – GGamba Feb 24 '17 at 09:41
  • Thank you, that it is clearer now. Though still not working even with tags$script(JS('myfunction()')). I'm not sure what lines 2-5 on your code do. It seems that you are defining a function. I am trying to use myfunction(), which is defined within rtp.js. It adds a widget on mobile devices to add to [home screen](http://cubiq.org/add-to-home-screen). @GGamba – AlexRos Feb 24 '17 at 10:17
1

The src="foo" argument means to get the source for your script from a file named foo. If you have inline code instead, then provide an unnamed argument to tags$script:

tags$script(type="text/javascript", "myfunction()")

# <script type="text/javascript">myfunction()</script>
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187