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

使用TypeScript打开新标签页但不直接导航的实现方法求助

实现打开新标签页但不自动聚焦的方案

浏览器默认会让window.open(url, '_blank')打开的新标签页自动获得焦点,要实现打开后不跳转聚焦,可以通过以下步骤调整:

  1. 先打开一个空白的新标签页:
    const newWindow = window.open('', '_blank');
    
  2. 为这个新标签页设置目标URL:
    if (newWindow) {
      newWindow.location.href = '你的目标URL';
    }
    
  3. 让新标签页失焦,同时将焦点切回当前窗口:
    if (newWindow) {
      newWindow.blur();
      window.focus();
    }
    

注意事项

  • 部分现代浏览器出于用户体验或安全限制,可能会忽略blur()和focus()的调用,这种情况下无法强制实现不聚焦的效果。
  • 确保代码是由用户主动触发的(比如点击事件回调),否则window.open可能会被浏览器的弹出窗口拦截器阻止。

完整示例代码:

function openTabWithoutFocus(url: string) {
  const newWindow = window.open('', '_blank');
  if (!newWindow) return; // 处理弹出被拦截的情况
  
  newWindow.location.href = url;
  newWindow.blur();
  window.focus();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:23:09