Test: window.close()
検証済みのブラウザ
- Chrome 89 passed
- Firefox 86 passed
- Edge 89 passed
- Safari 14 failed
Safariでは、本来の意味でScriptで開いた場合にのみ利用できるようです。
Safariで閉じることができるスクリプトを判別する方法がわかれば、追加します。
window.close()
が使用できる状況は限られています。このページはそれをテストするためのものです。
閉じるボタンが機能するかどうかを見てみましょう。
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.
HTML Living standard: https://html.spec.whatwg.org/multipage/window-object.html#dom-window-close
実際にwindow.close()
が動作する状況は、次のいずれかの条件に合致する場合のようです。
window.opener
がnull
ではないwindow === window.top
がtrue
であり、window.history.length
が「1」である
script-closable | おそらく... |
---|---|
top level browsing context |
|
window.opener |
|
window.history.length |
|
document.referrer |
テスト用のリンクと閉じるボタン
次のリンクはすべて現在と同じページへの導線です。
注意: 「同じタブ」は、現在URLと同じ遷移先だと履歴が増えないためJavaScriptによって一意なURLクエリが与えられています。
- 同じタブで開く
- 新しいタブで開く [target=_blank]
- 新しいタブで開く [target=_blank][rel=opener]
- JavaScriptを使って新しいタブで開く(window.open)
- JavaScriptを使って新しいタブで開く(window.open - noopener)
ブラウジング・コンテキスト確認用のiframe要素
現在のブラウジングコンテキストがトップレベル(window.top === window
)の場合、このページと同じページがiframe要素として挿入されます。