javascript - 使用 iFrame 中的父文档触发和关闭窗口
问题描述
我正在练习使用showmodaldialog.js Polyfill演示。我在 demo-modal.html 中添加了一个按钮,并尝试使用子窗口上的按钮来触发 'dialog-close' 。但我用window.top.document.getElementById('dialog-close').close();
的是不行。感谢帮助。以下是我的代码。
<!-- demo-modal.html -->
<!DOCTYPE html>
<html>
<head>
<title>showModalDialog modal demo</title>
</head>
<body>
<h1>showModalDialog modal demo</h1>
<p>Dialog argments: <span id="arg"></span></p>
<textarea id="textcontent"></textarea>
<button id="btn1" onclick="myFunction()">close</button>
</form>
<script>
document.getElementById('arg').innerHTML = window.dialogArguments;
window.returnValue = "some return value";
function myFunction(){
window.top.document.getElementById('dialog-close').close(); //it not work
//how to use it to close window?
}
</script>
</body>
</html>
<!-- demo.html -->
<!DOCTYPE html>
<html>
<head>
<title>showModalDialog polyfill demo</title>
</head>
<body>
<h1>showModalDialog polyfill demo</h1>
<form action="">
<p>
<input id="button1" type="button" value="Show Modal Dialog using yield"> <span id="result1"></span>
</p>
<p>
<input id="button2" type="button" value="Show Modal Dialog using async/await"> <span id="result2"></span>
</p>
<p>
<input id="button3" type="button" value="Show Modal Dialog using eval"> <span id="result3"></span>
</p>
</form>
<iframe src="https://ghbtns.com/github-btn.html?user=niutech&repo=showModalDialog&type=watch&count=true" height="30" width="118" frameborder="0" allowTransparency="true"></iframe>
<script src="showModalDialog.js"></script>
<script>
//using eval
document.getElementById('button3').addEventListener('click', function() {
var ret = window.showModalDialog("demo-modal.html", "some argument", "dialogWidth:500px;dialogHeight:200px");
document.getElementById('result3').innerText = "Returned from modal: " + ret;
});
</script>
</body>
</html>
解决方案
我自己解决了这个问题!
我改变
window.top.document.getElementById('dialog-close').close();
至
window.top.document.getElementById('dialog-close').click();
它有效!