R Shiny如何解决定时点击自定义HTML元素失效问题
问题原因
你的代码无法正常生效,核心是两个问题:
- 脚本执行时机不对:JS在页面初始化阶段就运行了,Airbnb嵌入组件是异步加载渲染的,此时目标“Next”按钮还没生成,
document.querySelector拿到的是null,后续调用.click()会直接抛出空值错误,逻辑完全中断。 - 元素选择器兼容性差:你用的
[class='_1rftspj9']是精确匹配class属性的完整字符串,只要Airbnb给按钮追加其他样式类、调整类名顺序,就会匹配失败。
修复方案
- 增加元素存在性轮询:等Airbnb组件把按钮渲染到页面后,再启动定时点击逻辑,避免空值报错
- 改用标准类选择器:用
._1rftspj9的写法匹配目标按钮,不受追加类名、类名顺序影响 - 调整执行时机:等页面DOM加载完成后再启动检测逻辑,避免不必要的性能消耗
修复后的完整可运行代码如下:
library(shiny) ui <- fluidPage( tags$script(" document.addEventListener('DOMContentLoaded', function() { const clickGap = 3000; // 自动点击间隔,单位毫秒 // 每500毫秒检测一次目标按钮是否加载完成 const checkTimer = setInterval(function() { const nextBtn = document.querySelector('._1rftspj9'); if (nextBtn) { clearInterval(checkTimer); // 找到按钮后停止检测 // 启动固定间隔自动点击 setInterval(function() { nextBtn.click(); }, clickGap); } }, 500); }); "), sidebarLayout( sidebarPanel(), mainPanel( shiny::htmlOutput(outputId = "airbnbListing") ) ) ) server <- function(input, output) { output$airbnbListing <- renderUI({ HTML( '<div class="airbnb-embed-frame" data-id="48429200" data-view="home" style="width:1800px;height:1200px;margin:auto"><a href="https://www.airbnb.com/rooms/48429200?check_in=2022-11-28&check_out=2022-12-05&guests=1&adults=1&s=66&source=embed_widget">View On Airbnb</a><a href="https://www.airbnb.com/rooms/48429200?check_in=2022-11-28&check_out=2022-12-05&guests=1&adults=1&s=66&source=embed_widget" rel="nofollow">Beautifully Decorated, Comfortable, Beachfront 3 Bedroom House on Gulf Beach</a><script async="" src="https://www.airbnb.com/embeddable/airbnb_jssdk"></script></div>' ) }) } shinyApp(ui = ui, server = server)
提示:如果后续Airbnb更新组件修改了按钮类名,只需要把代码中选择器里的
_1rftspj9替换为新的目标类名即可。
内容的提问来源于stack exchange,提问作者Joe Robert
相关产品推荐
相关产品推荐

