Close Bootstrap modal from inside iframe

2019-03-11 01:08发布

Page which opens Twitter Bootstrap Modal with iframe inside:

<div id="iframeModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="btn btn-danger pull-right" data-dismiss="modal" aria-hidden="true">Close</button>
        <div class="clearfix"></div>
    </div>
    <div class="modal-body">
        <iframe src="iframe-modal.html"></iframe> 
    </div>
    <div class="modal-footer">
    </div>
</div>

And I am looking for a way to close this modal from inside the iframe. Ex. clicking a link inside the iframe-modal.html to close the modal. What I have tried, but non successful:

$('#iframeModal', window.parent.document).modal('hide');
$('#iframeModal', top.document).modal('hide');
$('#iframeModal').modal('hide');

4条回答
放荡不羁爱自由
2楼-- · 2019-03-11 01:13

You can also trigger the click the close button:

$('#iframeModal button.mce-close', parent.document).trigger('click');
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-11 01:14

The issue is that jQuery events are being registered with the individual page's instance of jQuery. So, $('#iframeModal', window.parent.document).modal('hide'); is actually going to trigger the hide event in the iframe, not the parent document.

This should work: parent.$('#iframeModal').modal('hide');

This will use the parent's instance of jQuery to find the item (so no context is needed), and it will then fire the event correctly in the parent.

查看更多
SAY GOODBYE
4楼-- · 2019-03-11 01:19

You can always create a globally accessible function which closes the Bootstrap modal window.

eg.

window.closeModal = function(){
    $('#iframeModal').modal('hide');
};

Then from the iframe, call it using:

window.parent.closeModal();
查看更多
男人必须洒脱
5楼-- · 2019-03-11 01:20

One more solution in case you don't know id of modal which use iframe :

Add function CloseModal

function CloseModal(frameElement) {
     if (frameElement) {
        var dialog = $(frameElement).closest(".modal");
        if (dialog.length > 0) {
            dialog.modal("hide");
        }
     }
}

where frameElement is reference to iframe element container.

And this parameter can be passed from iframe like so:

window.parent.CloseModal(window.frameElement);

More about window.frameElement you can find here

查看更多
登录 后发表回答