You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

shinyCaptcha自定义按钮:如何替换默认按钮并修改标签与位置?

自定义shinyCAPTCHA的按钮样式与行为

默认的recaptchaUI封装了Google reCAPTCHA的原生组件,无法直接修改按钮样式。要实现自定义按钮(修改标签、位置、样式),需要手动集成reCAPTCHA API,绕过默认的recaptchaUI组件,具体实现如下:

核心思路

  1. 手动加载Google reCAPTCHA的前端脚本,指定验证成功后的回调函数
  2. 创建自定义按钮,点击时触发reCAPTCHA验证流程
  3. 在Shiny后端接收验证结果,完成后续逻辑判断

完整示例代码

library(shiny)
library(shinyCAPTCHA)

ui <- fluidPage(
  # 加载Google reCAPTCHA API脚本,替换为你的sitekey
  tags$script(src = "https://www.google.com/recaptcha/api.js?render=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"),
  tags$script(HTML("
    // 定义验证成功后的回调函数
    function recaptchaCallback(response) {
      // 将验证结果发送到Shiny的input对象
      Shiny.setInputValue('custom_recaptcha_response', response);
    }
  ")),
  
  # 自定义按钮:修改label、样式、位置都在这里调整
  actionButton(
    inputId = "trigger_recaptcha",
    label = "点击验证身份",  # 自定义按钮标签
    class = "btn btn-primary",  # 自定义样式类
    style = "margin: 20px;"  # 自定义位置/样式
  ),
  
  uiOutput("body")
)

server <- function(input, output, session) {
  # 处理reCAPTCHA验证逻辑
  result <- reactive({
    req(input$custom_recaptcha_response)
    # 调用shinyCAPTCHA的验证函数,替换为你的secret
    recaptcha_verify(
      secret = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe",
      response = input$custom_recaptcha_response
    )
  })
  
  output$body <- renderUI({
    fluidPage(
      uiOutput("humansOnly")
    )
  })  
  
  output$humansOnly <- renderUI({
    req(result()$success)
    tags$h1("仅对人类可见!")
  })
  
  # 点击自定义按钮时触发reCAPTCHA验证
  observeEvent(input$trigger_recaptcha, {
    session$sendCustomMessage("trigger_recaptcha", list())
    tags$script(HTML("grecaptcha.execute('6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI', {action: 'submit'}).then(recaptchaCallback);"))
  })
}

shinyApp(ui, server)

自定义按钮的调整方式

  • 修改标签:直接修改actionButton的label参数,比如改成"验证我是人类"
  • 调整位置:将actionButton放在UI的任意容器中(比如sidebarPanel、fluidRow),配合style参数设置margin、padding等
  • 修改样式:通过class参数使用Bootstrap样式类,或者style参数直接写CSS样式(比如修改背景色、字体大小)
  • 绑定其他行为:可以在observeEvent中添加额外逻辑,比如点击按钮前的提示

内容的提问来源于stack exchange,提问作者Lev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 14:28:37