通過主頁面 windows.addEventListener()監聽消息的方式,實現用iframe內部的按鈕關閉模態框。
本案例中使用的layui的彈出層,layui彈出層關閉的方法之一爲:
layer.close(layer.index);
使用其他的模態框請替換模態框關閉方法的代碼。
喚醒模態框的頁面代碼:
window.addEventListener("message",(e)=>{
// console.log(e);
if(e.data.type == 'close') {
layer.close(layer.index);
}
if(e.data.type == 'sucess') {
layer.close(layer.index);
window.location.reload();
}
});
模態框內頁面的js代碼
$(function () {
$('.close-btn').click(function () {
window.parent.postMessage({ type: "close" }, "*");
});
$('.submit-btn').click(function () {
window.parent.postMessage({ type: 'sucess' }, "*");
})
});
效果圖: