rclipboardquarto

Add copy to clipboard button in Quarto dashboard


I would like to add a button which copies the input or output of a user in a Quarto dashboard. I found the shiny2clipboard which seems a good option. Unfortunately, the code I'm trying to run doesn't copy the text to the clipboard inside a Quarto dashboard. When you run the example code from the blog in the link it does work but not in a Quarto dashboard. Here is some reproducible code:

---
title: "Test"
format: dashboard
server: shiny
---

## Test

```{r}
library(shiny)
library(shinyCopy2clipboard)
```

```{r}
#| title: "Text that needs to copy to clipboard"

# Setup
  use_copy()

  # Text Input 1
  textInput("text", "Enter Your Text")

  # Copy Button 1
shinyCopy2clipboard::CopyButton(
    "copybtn",
    label = "Copy to clipboard",
    icon = icon("copy"),
    text = "No Text Found"
  )
```


```{r}
#| context: server
observe({

    req(input$copybtn)
  shinyCopy2clipboard::CopyButtonUpdate(session,
                     id = "copybtn",
                     label = "Copy to clipboard",
                     icon = icon("copy"),
                     text = input$text
    )

  })
```

Output:

enter image description here

As you can see in the output I try to copy the text from the input field to my clipboard. This doesn't work. So I was wondering if anyone knows how to add a button to copy text to your clipboard inside a Quarto dashboard?


Solution

  • You can define an actionButton which has an onclick event. There, we read the current text from the textInput (using txt = document.getElementById('text').value;) and then pass this to the clipboard with navigator.clipboard.writeText(txt);:

    ---
    title: "Test"
    format: dashboard
    server: shiny
    ---
    
    ## Test
    
    ```{r}
    library(shiny)
    ```
    
    ```{r}
    #| title: "Text that needs to copy to clipboard"
    
    # Text Input 1
    textInput("text", "Enter Your Text")
    
    actionButton(
      "copy_link", 
      "Copy to clipboard", 
      onclick = "
        txt = document.getElementById('text').value;
        navigator.clipboard.writeText(txt);"
    )
    ```
    
    ```{r}
    #| context: server
    ```
    

    enter image description here