根据用户输入更改 Iframe src

Change Iframe src based on user input

我似乎找不到任何有用的东西,但我需要一些 html 来根据 url 在文本框中输入的内容制作 iframe。我使用 iframe 在我学校的 chromebook 上解锁网站,但如果我只想检查一个网站并通过创建一个全新的网站来查看它在 iframe 上的工作方式,那就很麻烦了。我只是想在 iframe 中轻松预览 URL。

为了更改 iframe 源,您需要一个侦听器来监听输入何时更改以及何时更改,通过更新 src 属性 来更改 iframe 的源。设置监听器,你可以这样做:

// Grab the element by ID
document.getElementById("example_input")
  // Add the event listener to "input" 
  .addEventListener("input", exampleFunc);
  
function exampleFunc(event){
  // Grab iframe by ID
  let iframe = document.getElementById("example");
  // Update the source
  
  // First grab the input that was typed into
  let input = event.target;
  // Next get the value of that input
  let newUrl = input.value;
  
  // Now update the "src" property of the iframe
  iframe.src = newUrl;
}
<html>

<head></head>

<body>
  <input type="url" value="https://example.com" id="example_input">
  <iframe id="example" src="https://example.com" width="1000" height="450" frameborder="0" scrolling="no"></iframe>
</body>

</html>

尽管在这种情况下,您可能不想在每次输入时更新它,而是希望在用户停止输入时更新它,这在 this 问题中有解决方案。

另请注意,由于各种原因(X-Frame-Options header、内容安全策略等),许多网站不允许 iframe 建立连接,其中包括一些不允许的网站示例在 Google 和 YouTube 上工作。