簡體   English   中英

帶有'noopener'的Window.open打開一個新窗口而不是一個新選項卡

[英]Window.open with 'noopener' opens a new window instead of a new tab

我使用window.open('')'_blank'作為第二個參數在新標簽中打開我的鏈接例如。 window.open('http://google.com', '_blank')

但是,最近我添加了第三個參數'noopener'以便window.opener在新選項卡中變為null,並且新選項卡無法訪問父選項卡/窗口。 window.openernull

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

所以上面的代碼解決了安全問題,但是沒有打開一個新的選項卡,而是一個新的窗口開始打開,這不是我的預期。 我的瀏覽器設置相同,未對其進行任何更改。

我可以做些什么來使這個代碼打開新標簽而不是新窗口? 我不想刪除noopener作為第三個參數

在一行中解決這個問題的另一種方法是直接訪問opener屬性並將其設置為null以利用window.open()返回Window對象的事實。 這將適用於所有瀏覽器,以打開一個帶有null window.opener的新選項卡。

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

老實說,我認為你的代碼很好,但你可以嘗試不同的實現:

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

對於我來說,這是跨瀏覽器(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 }; 

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

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

這是一種感覺有點清潔的方法。 它創建一個錨標記並單擊它,我們必須使用此變通方法作為其用戶首選項。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM