Use window.open but block using window.opener
A back I met an interesting security hole
<a href="http://someurl.here" target="_blank">Link</a> It looks quite harmless, but there is a hole, because by default the page you open allows the open page to call her back through window.opener . There are some restrictions that are cross-domain, but there are still some insults that can be made
window.opener.location = 'http://gotcha.badstuff'; HTML now has a workaround
<a href="http://someurl.here" target="_blank" rel="noopener noreferrer">Link</a> This prevents the transfer of a new window to window.opener . This is good and good for HTML, but what if you use window.open ?
<button type="button" onclick="window.open('http://someurl.here', '_blank');"> Click Me </button> How can you block the use of window.opener here?
using
var yourWindow = window.open(); yourWindow.opener = null; yourWindow.location = "http://someurl.here"; The loan goes to Matthias Binens: https://mathiasbynens.imtqy.com/rel-noopener/
The call to window.open() now supports the "noopener" function.
Therefore, calling window.open('https://www.your.url','_blank','noopener') should open a new window / tab with zero window.opener .
I'm having trouble finding a reliable list of supported browsers (and versions) - here MDN states that
This is supported in modern browsers, including Chrome and Firefox 52+.
From my experiments, I see that this works for:
- Chrome 61
- Firefox 56
- Safari 11.1 (thanks to Ji Hu for this)
But does not work for:
- IE 11.608
- Edge 40
(All tests on a PC running Windows 10 ...)
For backward compatibility, it might be better to combine this with t3__rry's answer .
This worked for me:
const a = document.createElement("a") a.href = args.url a.target = "_blank" a.rel = "noopener" a.click() According to the documentation ( https://developer.mozilla.org/en/docs/Web/API/Window/open ), in the following code
window.open('https://www.your.url','_blank','noopener') The third argument contains "WindowFeatures" (see https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features ), so it makes sense to open the target in a new window.
After browsers add support for the CSP disown-opener directive, you can simply use this:
<meta http-equiv="Content-Security-Policy" content="disown-opener"> Or as an HTTP header:
Content-Security-Policy: disown-opener In any case, the effect is to set window.opener to null for any new windows that are created from a document that includes this CSP directive.
But disown-opener is a recent addition to CSP, and as far as I know, browsers do not yet support it.