0

I'm new to JavaScript and I feel like I've hit a brick wall. I can do simple functions but I've run into a more complex issue and have no idea how to solve this.

Basically I have a HTML document called publish-an-ad.html

Inside this HTML page, I have the following iframe:

<iframe src="checkout-1.html" width="900" height ="500" id="myFrame"> </iframe>

And inside this iframe I have a button with a class, <button class="myBtn"> Proceed to checkout </button>

I want to create an alert in the parent page (publish-an-ad.html) that triggers when this button inside my iframe is clicked. I don't know how to do this because the parent and the iframe clearly don't seem to communicate, they act like two different entities.

Are there any simple solutions to this? Thank you.

Drakaria
  • 9
  • 1

1 Answers1

0

Parent

<body style="display: flex; flex-direction: column;">
    <h1>
        This is parentElement
    </h1>
    <iframe id="frame" src="./iframe.html" frameborder="2"></iframe>
</body>

<script>
    window.onmessage = function (event) {
        switch (event.data.init) { // getting data from frame
            case 'alert':
                alert(event.data.message);

            case 'confirm': // USECASE 1: getting data from frame, process it and send it back
                var confirmed = confirm(event.data.message);
                document.getElementById("frame").contentWindow.postMessage({ confirmed }, '*');
        }
    };

</script>

Iframe

<body>
    This is an iframe.
    <button id="alert"> Click to pass alert</button>
    <button id="confirm"> Click to confirm</button>

    <p id="message"></p>
</body>

<script>
    document.getElementById("alert").addEventListener("click", function () {
        window.top.postMessage({
            init: "alert",
            message: "Hello from iframe"
        }, "*");
    })

    document.getElementById("confirm").addEventListener("click", function () { // USECASE 1: it passing a state to parent and receiving result from parent
        window.top.postMessage({
            init: "confirm",
            message: "Are you sure ?"
        }, "*");
    })

    window.onmessage = function (e) { // USECASE 1: handle previous state result from parent
        if (e.data.confirmed === true) {
            document.getElementById("message").innerHTML = "He Confirmed";
        } else if (e.data.confirmed === false) {
            document.getElementById("message").innerHTML = "He Canceled";
        } else { }
    };


</script>
  • Thanks for the effort but I really don't understand this :( Is there an easier way to do it? I'm really, really bad at Js and I can't seem to get this to work. – Drakaria Sep 04 '21 at 11:29