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

如何根据用户输入URL修改JavaScript代码动态替换URLINPUT占位符

代码修改方案

原代码的问题是把URL写死成了"URLINPUT"字符串,只需要把这部分替换成动态获取用户输入的逻辑即可,根据你的使用场景可以选两种实现:

  • 无页面控件场景:直接在函数内调用prompt弹出输入框,让用户触发函数时直接填写目标地址
  • 已有页面输入框场景:给函数增加URL形参,调用函数时把输入框拿到的用户输入传进去即可

内置输入弹窗版本(无需额外写页面元素)

function bruh() {
  // 弹出输入框获取用户输入的地址
  const url = prompt("请输入要访问的目标URL:");
  // 用户取消输入或输入为空时直接终止
  if (!url?.trim()) return;

  const win = window.open();
  win.document.body.style.margin = '0';
  win.document.body.style.height = '100vh';
  const f = win.document.createElement("iframe");
  window.focus();

  f.style.width = "100%";
  f.style.height = "100%";
  f.style.border = 'none';
  f.style.margin = '0';
  // 自动补全https协议,避免用户漏写导致地址无效
  f.src = url.startsWith('http') ? url : `https://${url}`;
  win.document.body.appendChild(f);
}

接收外部传入URL版本(适配自定义输入框场景)

// 函数增加url形参,接收外部传入的用户输入地址
function bruh(url) {
  if (!url?.trim()) return;

  const win = window.open();
  win.document.body.style.margin = '0';
  win.document.body.style.height = '100vh';
  const f = win.document.createElement("iframe");
  window.focus();

  f.style.width = "100%";
  f.style.height = "100%";
  f.style.border = 'none';
  f.style.margin = '0';
  f.src = url.startsWith('http') ? url : `https://${url}`;
  win.document.body.appendChild(f);
}

// 调用示例:绑定页面上的按钮和输入框
// const openBtn = document.querySelector('#openButton');
// const urlInput = document.querySelector('#urlInput');
// openBtn.addEventListener('click', () => {
//   bruh(urlInput.value);
// })

注意:受浏览器安全策略限制,如果目标网站配置了X-Frame-Options响应头禁止被iframe嵌入,这类站点无法通过该方式加载,属于正常的安全限制,并非代码逻辑问题。

内容的提问来源于stack exchange,提问作者Kohen Webb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:51:21