模態框/頁面 跨域通信,如何用模態框iframe裏的按鈕關閉模態框?

通過主頁面 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' }, "*");
                })
            });

效果圖:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章