【问题标题】:Using rel="noopener" in window.open()在 window.open() 中使用 rel="noopener"
【发布时间】:2017-09-11 03:54:44
【问题描述】:

所以我知道在使用target="_blank" 时我可以在a 标记中应用rel="noopener。但我试图将它作为参数传递给window.open(),即:

window.open('http://cats.com', '_blank', 'rel=noopener')

但是它似乎没有按我预期的方式工作,因为在用户单击链接后,opener 对象仍然存在于窗口中。

我有什么遗漏吗?还是不能按照我的意图完成?

我找到了一些很棒的文章,但据我所知,它们并没有完全解决我的用例。

https://developer.mozilla.org/en-US/docs/Web/API/Window/open https://mathiasbynens.github.io/rel-noopener/

非常感谢。

【问题讨论】:

  • window.open() 中使用的窗口功能标志字符串只是noopener 而不是rel=noopener。不过,suggested here 解决方案具有最佳的向后和跨浏览器兼容性。

标签: javascript hyperlink target window.opener


【解决方案1】:

doc 中没有直接的例子,但它可以像这样使用并且对我有用。

window.open('http://cats.com', '_blank', 'noopener,resizable,scrollbars')

【讨论】:

【解决方案2】:

覆盖你所有的基地

最安全的重定向方法是添加noopenernoreferrerwindow.opener = null

const openInNewTab = (url) => {
    const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
    if (newWindow) newWindow.opener = null
}

然后调用你的新函数

openInNewTab('https://stackoverflow.com')

第三个参数也可以取these optional values,根据你的需要。

【讨论】:

  • noreferrer 暗示 noopener,因此只需要 noreferrer 即可让它们都处于活动状态。 “8. 如果 noreferrer 为真,则将 noopener 设置为真。”来自html.spec.whatwg.org/multipage/…
【解决方案3】:

这对我有用:

const a = document.createElement("a")
a.href = args.url
a.target = "_blank"
a.rel = "noopener"
a.click()

【讨论】:

  • 如此简单。谢谢!
  • 这不能回答发帖者的问题,也不是一种好的编码风格,因为它创建了一个假元素而不是使用内置函数。这应该是公认的答案:stackoverflow.com/a/49918599/7905854
【解决方案4】:

据我所知,window.open() 参数无法实现这一点。但是,有一种方法可以获取该行为:

var newWindow = window.open();
newWindow.opener = null;
newWindow.location = 'http://some.url';

【讨论】:

  • 无法在最新的 chrome 版本 88.0.4324.190(官方版本)(64 位)中工作。 rel = 'noreferrer' 为我工作
猜你喜欢
  • 2020-02-28
  • 2018-12-14
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 2018-11-15
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多