Include a button in a Shiny app to Tweet the URL to the app

I'm looking to include a button in a Shiny app to Tweet the URL to the app. My goal is to make it easy for users of the app to share it on Twitter. Does anyone have any examples of this?

I'm providing two ways to do what you're asking.

1. Using Twitter's share button

library(shiny)
# Create an url using twitter's Tweet Web Intent parameters
# https://dev.twitter.com/web/tweet-button/web-intent
url <- "https://twitter.com/intent/tweet?text=Hello%20world&url=https://shiny.rstudio.com/gallery/widget-gallery.html/"

ui <- fluidPage(

    # Application title
    titlePanel("Twitter share"),

    # Sidebar with an twitter share link
    sidebarLayout(
        sidebarPanel(
            # Create url with the 'twitter-share-button' class
            tags$a(href=url, "Tweet", class="twitter-share-button"),
            # Copy the script from https://dev.twitter.com/web/javascript/loading into your app
            # You can source it from the URL below. It must go after you've created your link
            includeScript("http://platform.twitter.com/widgets.js")
        ),
        mainPanel(
        )
    )
)

server <- function(input, output) {
}

# Run the application
shinyApp(ui = ui, server = server)

2. Creating your own button

library(shiny)

# Create an url using twitter's Tweet Web Intent parameters 
# https://dev.twitter.com/web/tweet-button/web-intent
url <- "https://twitter.com/intent/tweet?text=Hello%20world&url=https://shiny.rstudio.com/gallery/widget-gallery.html/"

ui <- fluidPage(

    # Application title
    titlePanel("Twitter share"),

    # Sidebar with an actionButton with the onclick parameter
    sidebarLayout(
        sidebarPanel(
            actionButton("twitter_share",
                         label = "Share",
                         icon = icon("twitter"),
                         onclick = sprintf("window.open('%s')", url)) # Combine text with url variable
# Use the onclick parameter to open a new window to the twitter url
        ),
        mainPanel(
        )
    )
)

server <- function(input, output) {
}

# Run the application
shinyApp(ui = ui, server = server)
4 Likes

Thank you, this (the first of the two options was the one I used) work great.

1 Like

Thanks for this - I've used the second option, but some users reported that it only works with certain browsers. I'm trying to find more details at the moment.