【问题标题】:Window.open with 'noopener' opens a new window instead of a new tabWindow.open with 'noopener' 打开一个新窗口而不是一个新选项卡
【发布时间】:2018-03-14 11:26:20
【问题描述】:

我使用window.open('')'_blank' 作为第二个参数在新选项卡中打开我的链接例如。 window.open('http://google.com', '_blank')

但是,最近我添加了第三个参数'noopener',以便window.opener 在新选项卡中变为空,并且新选项卡无法访问父选项卡/窗口。即window.openernull

window.open('http://google.com', '_blank', 'noopener')

所以上面的代码解决了安全问题,但不是打开一个新选项卡,而是一个新窗口开始打开,这不是我所期望的。我的浏览器设置相同,没有对其进行任何更改。

我可以做些什么来让这段代码打开新标签而不是新窗口?我不想删除 noopener 作为第三个参数

【问题讨论】:

  • 我不认为这是重复的,@Stender 发布的链接是关于没有让“noopener”工作,而不是它改变了选项卡/窗口行为。这在所有浏览器中都发生吗?可能是浏览器错误/不一致。
  • 是的,它在 Chrome、Firefox 和 IE 中对我来说都是一样的
  • 我想正确的语法应该是noopener=1/true/yes。看起来所有其他窗口功能都会以某种方式连接到带有 chrome 的窗口,而 noopener 是唯一一个实际上在选项卡中也有用的功能。也许在浏览器实现中已经忘记了这一点,当存在 windowFeature 参数时,窗口将自动打开到新窗口而不是选项卡。我用FF做了一个小测试,如果存在windowFeatures参数,它会打开一个新窗口,参数的值无关紧要,甚至可以是乱码......

标签: javascript window.open window.opener


【解决方案1】:

另一种在一行中解决此问题的方法是直接访问 opener 属性并将其设置为 null 以利用 window.open() 返回 Window 对象这一事实。这将适用于所有浏览器,以打开一个带有空 window.opener 的新选项卡。

window.open(url, '_blank').opener = null;

【讨论】:

  • 看起来有点老套,但这是我发现的唯一解决方案,它在所有现代浏览器中都能可靠运行。
【解决方案2】:

老实说,我认为您的代码很好,但您可以尝试不同的实现:

var yourWindow = window.open();
yourWindow.opener = null;
yourWindow.location = "http://someurl.here";
yourWindow.target = "_blank";

【讨论】:

  • 请注意,截至 2020 年 3 月 31 日,使用 yourWindow.target = "_self" 在 Safari 中似乎无法正常工作。使用,var yourWindow = window.open("someurl.here", "_self"); yourWindow.opener = null;
【解决方案3】:

https://mathiasbynens.github.io/rel-noopener/

const anchor = document.createElement('a');

Object.assign(anchor, {
  target: '_blank',
  href: 'http://google.com',
  rel: 'noopener noreferrer'
})
.click()

这是感觉更干净的方法。它创建一个锚标记并单击它,我们必须将此解决方法用作用户偏好。

【讨论】:

    【解决方案4】:

    这对我来说是唯一适用于跨浏览器(IE11、Chrome 66、FF 60、Safari 11.1)的东西

    function openURL(url) {
      var link = document.createElement('a');
      link.target = "_blank";
      link.href = url;
      link.rel = "noopener noreferrer";
      document.body.appendChild(link); // you need to add it to the DOM to get FF working
      link.click();
      link.parentNode.removeChild(link); // link.remove(); doesn't work on IE11
    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2015-04-21
      • 1970-01-01
      • 2011-10-03
      • 2013-11-29
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多