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

如何在R Shiny内部嵌入网页?解决脚本的两类问题

Hey there! Let's fix up your Shiny app to display the webpage inside the app instead of opening an external window, and stop that annoying folder popup. Here's the revised code, followed by a breakdown of what changed:

library(shiny)
library(shinyWidgets)

if (interactive()) {
  ui <- fluidPage(
    tags$h1("URL Viewer"),
    br(),
    searchInput(
      inputId = "search",
      label = "Enter a URL (start with http/https)",
      placeholder = "https://example.com",
      btnSearch = icon("search"),
      btnReset = icon("remove"),
      width = "450px"
    ),
    br(),
    # Container for the embedded webpage
    uiOutput("webpage_container")
  )
  
  server <- function(input, output, session) {
    # Render the iframe only when a valid URL is entered
    output$webpage_container <- renderUI({
      req(input$search)
      # Check if URL starts with http/https to avoid invalid sources
      if (grepl("^https?://", input$search)) {
        tags$iframe(
          src = input$search,
          width = "100%",
          height = "600px",
          frameborder = 0,
          scrolling = "auto"
        )
      } else {
        tags$div(
          class = "alert alert-warning",
          "Please enter a valid URL starting with http:// or https://"
        )
      }
    })
  }
  
  shinyApp(ui = ui, server = server)
}

Key Changes Explained:

  • Removed shell.exec(): This was the exact reason the external browser or folder window kept popping up. Ditching this call keeps all interaction inside the Shiny app.
  • Added dynamic webpage container: The uiOutput("webpage_container") creates a flexible spot in the UI to render the embedded page only when a valid URL is provided.
  • Valid URL check: We use a regex to ensure the input starts with http:// or https://—this prevents broken iframes and unnecessary error states. If the URL is invalid, we show a friendly warning instead.
  • Optimized iframe settings: The iframe is configured to fill most of the app's width, has a fixed height, no border, and allows scrolling for a clean, integrated look.

Note on Iframe Limitations:

Some websites block themselves from being embedded in iframes using security headers like X-Frame-Options (a measure to prevent clickjacking). This is a deliberate choice by the site owner, and there's no way to bypass it from the Shiny app side. If you hit this issue, the site will either fail to load or display an error message.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:31:52