Reputation: 1117
I was using window.open('')
with '_blank'
as second parameter to open my link in new tab For eg. window.open('http://google.com', '_blank')
But, recently I added the third parameter 'noopener'
so that window.opener
becomes null in the new tab and the new tab does not have access to the parent tab/window. i.e. window.opener
is null
window.open('http://google.com', '_blank', 'noopener')
So the above code solved the security problem, but instead of opening a new tab, a new window started opening which is not what I expected. My browser settings were same and no changes were made to it.
Is there anything I can do to make this code open new tab instead of new window ? I do not want to remove noopener
as third parameter
Upvotes: 17
Views: 11921
Reputation: 3452
const anchor = document.createElement('a');
Object.assign(anchor, {
target: '_blank',
href: 'http://google.com',
rel: 'noopener noreferrer'
})
.click()
This is the method which feels a bit cleaner. It creates an anchor tag and clicks it, we have to use this workaround as its a user preference.
Upvotes: 5
Reputation: 139
Another approach that will solve this in one line is to access the opener property directly and set it to null to make use of the fact that window.open()
returns a Window
object. This will work across all browsers to open a new tab with a null window.opener
.
window.open(url, '_blank').opener = null;
Upvotes: 12
Reputation: 165
This is the only thing that works cross-browser (IE11, Chrome 66, FF 60, Safari 11.1) for me
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
};
Upvotes: 5
Reputation: 729
Honestly i think your code is fine but you can try a different implementation:
var yourWindow = window.open();
yourWindow.opener = null;
yourWindow.location = "http://someurl.here";
yourWindow.target = "_blank";
Upvotes: 8