Controlling an embedded YouTube video when observing another event in R Shiny

376 views Asked by At

I have an R Shiny app. The UI has an embedded YouTube video, as well as a simple image. I would like to be able to pause the embedded video and play it again by clicking on my image and not on the video, or when clicking on an action button specifically added for this purpose. I have seen that it's possible to do this using JavaScript. Unfortunately, I haven't gotten very far.

My current reproducible code so far, below:

library(shiny)
library(shinyjs)
library(shinydashboard)

ui <- 
  dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      useShinyjs(),
      fluidPage(uiOutput("video")),
      img(id = 'image', src = 'http://www.zorro.com/wp-content/uploads/2014/04/005.jpg'),
      
    )
  )

server <- function(input, output, session){
  
  onclick(id = 'image', function(x) {
    tags$script('function () {
                player.playVideo();}')})
  
  output$video <- renderUI({
    HTML('<iframe width = "100%" height = "250" src = "https://www.youtube.com/embed/oW2c4KBLIeE" frameborder="0" allow = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>') 
  })
}
shinyApp(ui, server)

EDIT: This webpage does what I would like to do with R Shiny (play/pause part)

1

There are 1 answers

0
FOREXCTF1 On BEST ANSWER

I found the answer to my own question if anyone needs it: The javascript code was to be included in the server part only. I included the onclick event in the UI:

library(shiny)
library(shinyjs)
library(shinydashboard)

ui <- 
  dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      useShinyjs(),
      fluidPage(uiOutput("video")),
      img(id = 'image', src = 'http://www.zorro.com/wp-content/uploads/2014/04/005.jpg', onclick = 'myFunction()'),
      
    )
  )
output$video <- renderUI({
HTML('<div id="player"></div>
           
       <script>
       
       var tag = document.createElement("script");
       
       tag.src = "https://www.youtube.com/iframe_api";
       var firstScriptTag = document.getElementsByTagName("script")[0];
       firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
       
       var player;
       function onYouTubeIframeAPIReady() {
       player = new YT.Player("player", {
       height: "390",
       width: "640",
       videoId: "', input$modal_youtube_link, '" 
       playerVars: { "autoplay": 1, "modestbranding": 1 },
       events: {}
       });
       }
       var myFunction = function(){
       player.playVideo();
       
       </script>')})

shinyApp(ui, server)