I want to display a Plotly plot with HTML without using a render function I have looked into htmltools
and htmlwidgets
but have not found a solution. I am able to render a Plotly plot without a render function with the insertUI
function like this:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
#shiny::singleton(
# tags$head(tags$script(src = "custom_message_handler.js"))
#),
div(
id = "placeholder"
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
shiny::insertUI(
"#placeholder",
"beforeBegin",
ui = shiny::tagList(plotly::plot_ly(x = rnorm(100), y = rnorm(100)))
)
#shiny::observe({
# panel_plot(
# item = shiny::tagList(plotly::plot_ly(x = rnorm(100), y = rnorm(100)))
#)
#})
}
# Run the application
shinyApp(ui = ui, server = server)
However, when I have my own custom message handler, then the Plotly plot will not render. I want to send the Plotly plot to Javascript where I want to insert the Plotly plot after the placeholder id. How can I send the output of the Plotly plot to JavaScript and then display it like the insertUI
function does?
This is how I got so far regarding my own custom message handler
panel_plot <- function(item, session = shiny::getDefaultReactiveDomain()) {
session$sendCustomMessage(
type = 'plots',
message = list(panel = as.character(item))
)
}
# Javascript/jQuery
$(function() {
Shiny.addCustomMessageHandler('plots', function(message) {
var panel_plot = $.parseHTML(message.panel);
$(panel_plot).insertAfter($('#placeholder'));
});
});
shiny::observe({
panel_plot(
item = shiny::tagList(plotly::plot_ly(x = rnorm(100), y = rnorm(100)))
)
})