我在 R 中创建了一个简单的 Shiny 应用程序,它采用 URL 和一些 UTM 参数并连接所有内容。
现在我想添加一个按钮来直接将输出复制到剪贴板。
我尝试调整
rclipButton()
包中的 rclipboard
函数,但我的代码复制了其他内容而不是生成的字符串。
library(shiny)
library(rclipboard)
shinyApp(
ui = fluidPage(
# URL input
textInput("url", label = "Paste your URL", value = "https://google.com"),
textInput("utm_source", label = "UTM source", value = "newsletter"),
# URL + UTM output
verbatimTextOutput("url_with_utm"),
# Clipboard button
uiOutput("clip"),
textInput("clip_test", label = "Paste copied text")
),
server = function(input, output) {
# Define reactive value to store URL + UTM parameter
url_with_utm <- reactiveValues(text = "")
# Update URL + UTM parameters reactively
observeEvent({
input$url
input$utm_source
}, {
url_with_utm$text <- paste0(input$url, "?", "utm_source=", input$utm_source)
})
# URL output for UI
output$url_with_utm <- renderText({
url_with_utm$text
})
# Clipboard button
output$clip <- renderUI({
rclipButton(
inputId = "clipbtn",
label = "Copy",
clipText = url_with_utm$text, # IS THIS CORRECT??
icon = icon("clipboard"),
options = list(delay = list(show = 800, hide = 100), trigger = "hover")
)
})
}
)
navigator.clipboard
API 和 Shiny to JavaScript API 编写不依赖 R 的文本。
在您的
ui
中添加一个闪亮的自定义消息处理程序。在本例中,该函数获取一些文本并将其复制到剪贴板。这意味着您的用户界面将如下所示:
ui = fluidPage(
tags$script("
Shiny.addCustomMessageHandler('txt', function (txt) {
navigator.clipboard.writeText(txt);
});
"), # this is new
actionButton("copy_link", "Copy to clipboard"),
# URL input
textInput("url", label = "Paste your URL", value = "https://google.com"),
textInput("utm_source", label = "UTM source", value = "newsletter"),
textInput("paste_here", label = "Check copy/paste worked here"), # added for testing
# URL + UTM output
verbatimTextOutput("url_with_utm")
)
在您的服务器逻辑中,将
session$sendCustomMessage("txt", text)
添加到观察事件。您的整个服务器逻辑可以是:
server = function(input, output, session) {
observeEvent(input$copy_link, {
text <- paste0(input$url, "?", "utm_source=", input$utm_source)
session$sendCustomMessage("txt", text)
})
}
请注意,我们需要将
session
传递给服务器,因为自定义消息处理程序使用此参数。无需加载 rclipboard()
库。
根据您的 IDE,这可能无法在预览窗格中工作,因为可能不支持
navigator.clipboard
API。它应该可以在任何现代浏览器中工作。 navigator.clipboard.writeText()
自 2018 年起在 Chrome、Firefox 和 Opera 中受支持,自 2020 年起在 Safari 和 Edge 中受支持。请参阅此处了解更多浏览器兼容性详细信息。