我想在 Shiny 的应用程序中捕获对 iframe 内链接的点击。我想知道点击了哪个链接。
在 Shiny 的外面这很好用。我为相关问题添加了一个完全可重现的示例:
https://stackoverflow.com/a/46093537/3502164
(它必须在(本地)服务器上运行,例如 xaamp
)。
我的尝试:
1) 要保存在Path/To/App
中的应用。
2) 在 www
文件夹中存储应该在 iframe 中显示的 html 文件。
fileWithLink.html
<html>
<body>
<a href="https://stackoverflow.com/">SOreadytohelp</a>
</body>
</html>
3) 必须使用 runApp("Path/To/App", launch.browser = TRUE)
启动应用程序
(以便启动本地服务器)。
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
htmlOutput("filecontainer")
)
server <- function(input, output, session){
session$onFlushed(once = T, function(){
runjs("
console.log('I arrive here')
$('#filecontainer').load(function(){
console.log('But not here')
var iframe = $('#filecontainer').contents();
iframe.find('#a').click(function(){
alert('I want to arrive here');
});
});
")
})
output$filecontainer <- renderUI({
tags$iframe(src = "fileWithLink.html", height = 600, width = 1200)
})
}
shinyApp(ui, server)
最佳答案
iframe 包含在具有相关 ID ($('#filecontainer iframe')
) 的 div 中。有一个调用 anchor 标记的拼写错误。我更改了目的地以避免跨脚本问题:
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
htmlOutput("filecontainer")
)
server <- function(input, output, session){
session$onFlushed(once = T, function(){
runjs("
console.log('I arrive here')
$('#filecontainer iframe').load(function(){
console.log('But not here')
var iframe = $('#filecontainer iframe').contents();
iframe.find('a').click(function(){
console.log('am i here')
alert('I want to arrive here');
});
});
")
})
output$filecontainer <- renderUI({
tags$iframe(src = "fileWithLink.html", height = 600, width = 1200)
})
}
shinyApp(ui, server)
fileWithLink.html
<html>
<body>
<a href="anotherpage.html">SOreadytohelp</a>
</body>
</html>
另一个页面.html
<html>
<body>
Another page
</body>
</html>
关于javascript - 在 Shiny 的应用程序中捕获 iframe 中的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46094396/