javascript - 在 Shiny 的应用程序中捕获 iframe 中的点击

标签 javascript jquery r iframe shiny

我想在 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/

相关文章:

javascript - Vue.js:导入相同的 css 文件时定义了重复的 CSS 类(CSS 组件)

jquery - 水平布局表上的分页符

r - 大稀疏矩阵的 Moore-Penrose 广义逆

Jquery 只添加不删除类

android - jquery mobile,Android 中的 Chrome 版本 50 选择菜单出错

r - 模块中使用的 observeEvent Shiny 函数不起作用

r - %||% 表达式在 R 中做什么

javascript - 如何将单词的各个字符存储在数组中以供以后使用

javascript - 如何将 JSON 数据获取到我的 ejs 模板中?

javascript - ESLint 可以帮助你防止 Unhandled-Promise-Rejections 吗?