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

如何让新创建的浏览器窗口调用创建它的JavaScript脚本?

解决方案:让新窗口复用弹窗脚本实现指数级增长

你的核心问题在于原代码打开的是跨域外部页面(YouTube),浏览器的同源安全策略会阻止你向外部页面注入或执行自定义脚本。要实现每个新窗口都能继续创建更多窗口,你需要创建空白窗口并向其中注入完整的弹窗逻辑代码。

修改后的代码实现

// 封装要注入到所有新窗口的弹窗逻辑
const windowLogic = `
  function spawnNewWindow() {
    // 生成随机位置和尺寸(限制为父窗口的一半大小,避免窗口过大)
    const x = Math.floor(Math.random() * window.innerWidth);
    const y = Math.floor(Math.random() * window.innerHeight);
    const width = Math.floor(Math.random() * window.innerWidth * 0.5);
    const height = Math.floor(Math.random() * window.innerHeight * 0.5);

    // 创建空白新窗口
    const newWindow = window.open("", "_blank", \`width=\${width},height=\${height},left=\${x},top=\${y}\`);
    
    // 向新窗口注入完整的逻辑代码
    newWindow.document.write(\`
      <!DOCTYPE html>
      <html>
      <body>
        <script>\${windowLogic}</script>
      </body>
      </html>
    \`);
    newWindow.document.close(); // 完成文档写入
  }

  // 启动定时器:每秒创建一个新窗口
  setInterval(spawnNewWindow, 1000);
`;

// 初始窗口的弹窗函数
function spawnNewWindow() {
  const x = Math.floor(Math.random() * window.innerWidth);
  const y = Math.floor(Math.random() * window.innerHeight);
  const width = Math.floor(Math.random() * window.innerWidth * 0.5);
  const height = Math.floor(Math.random() * window.innerHeight * 0.5);

  const newWindow = window.open("", "_blank", `width=${width},height=${height},left=${x},top=${y}`);
  
  newWindow.document.write(`
    <!DOCTYPE html>
    <html>
    <body>
      <script>${windowLogic}</script>
    </body>
    </html>
  `);
  newWindow.document.close();
}

// 初始启动:第一个窗口每秒创建新窗口
setInterval(spawnNewWindow, 1000);

关键说明

  1. 同源策略限制:你无法向YouTube这类外部跨域页面注入脚本,浏览器会直接阻止这类操作,因此必须使用空白窗口来承载自定义逻辑。
  2. 脚本复用:将弹窗逻辑封装成字符串windowLogic,每个新窗口都会注入这段代码,从而拥有和父窗口完全相同的弹窗能力。
  3. 弹窗拦截注意:浏览器会自动拦截频繁触发的弹窗,你需要在浏览器设置中允许当前页面的弹窗权限(比如本地HTML文件或你部署的页面),否则脚本无法正常工作。
  4. 尺寸优化:给新窗口尺寸乘以0.5的系数,避免窗口过大覆盖整个屏幕,提升体验。

如果你坚持要打开YouTube页面同时执行弹窗逻辑,这在浏览器安全机制下是无法实现的——跨域页面不允许外部脚本干预其运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:45:40