はじめに
JavaScriptでモーダルウインドウを表示するためのメソッドwindow.showModalDialogが、最新のブラウザたちでどのように動作するかを検証してみました。
用意したブラウザ
OSはWindows XP SP3
- Firefox4 beta7
- Opera11.00 1111
- Google Chrome 8.0.552.210 beta
- Safari5.0.3
- IE8*1
検証結果
ブラウザ | 動作 | 備考 |
Firefox4 beta7 | ○ | |
Opera11.00 1111 | × | ダイアログが開きません。 |
Google Chrome 8.0.552.210 beta | × | ダイアログがモーダルになりません。 |
Safari5.0.3 | ○ | |
IE8 | ○ |
ちなみにGoogle Chromeでは、window.returnValueで親ウインドウに値を返すことができませんでした。Google ChromeでreturnValueが無視されるよという問題について、英語ですがここに書かれています。
サンプルコード
モーダルダイアログを表示し、ダイアログ側から親ウインドウに対して値を返すコードです。
親ウインドウ側
<html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>モーダルダイアログを開くサンプル</title> <script type="text/javascript" charset="UTF-8"> window.onload = function() { var btn = document.getElementById("btnOpen"); btn.onclick = function() { var url = "ModalDialog.html"; var winWidth = "400px"; var winHeight = "300px"; var options = "dialogWidth=" + winWidth + ";dialogHeight=\ " + winHeight + ";center=1;status=1;scroll=1;resizable=1;\ minimize=0;maximize=0;"; // ボタンをグレーアウトする btn.disabled = true; window.returnValue = showModalDialog(url, window, options); // 戻り値をアラート alert(window.returnValue); } } </script> </head> <body> <h1>モーダルダイアログを開くサンプル</h1> <input type="button" id="btnOpen" value="モーダルダイアログを開く"> </body> </html>
モーダルウインドウ側
<html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>モーダルダイアログ</title> <script type="text/javascript" charset="UTF-8"> window.onload = function() { // 自分自身のウインドウを閉じる document.getElementById("btnClose").onclick = CloseDialog; window.onunload = CloseDialog; function CloseDialog() { // 親ウインドウを取得する(IE用) if(!window.opener) { window.opener = dialogArguments; } // 親ウインドウのボタンのグレーアウトを解除する window.opener.document.getElementById("btnOpen").disabled = false; window.returnValue = "hoge"; window.close(); } } </script> </head> <body> <h1>モーダルダイアログ</h1> <input type="button" id="btnClose" value="自分自身のウインドウを閉じる"> </body> </html>
以下のエントリもあわせてどうぞ
*1:IE9betaがリリースされていますが、WindowsXPしか手元にないので検証できませんでした。