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

如何实现点击链接时打开含自定义代码的about:blank页面

修复方案

你的代码问题出在这几个地方:

  1. 页面一加载就自动执行window.open(),导致空白页直接弹出,不是点击链接才触发
  2. a标签点击后会执行默认跳转,没机会运行自定义逻辑
  3. 代码存在语法错误:innerHTML里的<p>标签style属性没闭合,创建样式链接时变量名前后不一致(style和link)

下面是修复后的可运行代码:

<body>
  <h1>Learn the Coding Experience!</h1>
  <p>Click <a href="#" id="link" target="_blank">here</a> to see the ultimate coding experience.</p>

  <script>
    // 获取链接元素
    const link = document.getElementById('link');

    // 添加点击事件监听
    link.addEventListener('click', function(event) {
      // 阻止a标签的默认跳转行为
      event.preventDefault();

      // 打开about:blank空白页
      const newWindow = window.open();
      if (!newWindow) {
        alert('弹窗被浏览器拦截,请允许弹窗权限');
        return;
      }

      // 写入自定义HTML内容,修正语法错误
      newWindow.document.body.innerHTML = `
        <p style="color: #333; font-size: 18px;">Subscribe to NothingButTyler on YouTube!</p>
        <iframe src="https://1v1.lol" width="100%" height="600"></iframe>
      `;

      // (可选)添加自定义样式表
      const styleLink = newWindow.document.createElement('link');
      styleLink.href = '你的样式表地址';
      styleLink.rel = 'stylesheet';
      newWindow.document.head.appendChild(styleLink);
    });
  </script>
</body>

关键说明:

  • 把a标签的href设为#,配合event.preventDefault()彻底阻止默认跳转
  • 点击事件触发时才打开空白页,符合你的需求
  • 用模板字符串(`)编写HTML内容,更易读且避免引号嵌套问题
  • 添加了弹窗拦截的判断,提升用户体验
  • 修正了变量名不一致和标签未闭合的语法错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:43:12