Sweet Alert 2 Open in Parent Frame

2019-05-23 09:02发布

问题:

I have an iframe with a source that is a php file. What I'm trying to do is get Sweet Alert 2 to open in the parent frame rather than inside of the iframe. I have tried changing the target and have not had any success.

None of the following target options have worked:

swal({
    target: 'window'
    target: 'document'
    target: 'parent'
});

This is the result that I get when 'body' is the target:

Edit:

SweetAlert 2 code

swal({
    type: 'error',
    text: 'You did not select any files.',
    target: 'top'
});

iFrame code

<div id="viewWindow" class="col-xs-10 content">
    <iframe id="waiverList" src="php/edit_archive.php"></iframe>
</div>

回答1:

Hi what you can do is have your sweetalert2 code in your parent window. Then use JavaScript's parent property inside your iframe to call the function. To avoid getting a same origin policy error you can use window post messages.

like this:

Parent Html

<!DOCTYPE html>
<html>
<body>
<script> 
    function openAlert() {
        swal(
            'Good job!',
            'You clicked the button!',
            'success'
        )
    }
    window.addEventListener("message", function(event) {
        if(event.data == "openAlert");{
            openAlert();
        }
    });

</script>
    <iframe src="iframe.html">

    </iframe>
</body>
</html>

Iframe HTML

<!DOCTYPE html>
<html>
<body>
     <button onclick="foo();">Click Me</button>
     <script>
     function foo(){
         parent.postMessage("openAlert", "*");
     }
     </script>
</body>
</html>