使用postMessage API

时间:2019-07-11 09:15:14

标签: javascript jquery postmessage

我正在为我的产品开发一项功能,即用户输入网址并获得用户点击。

我尝试使用postMessage进行操作,其中用户输入url并打开新窗口并获取元素数据,但由于我滞后某处,问题仍然无法解决。

父窗口HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Admin Dashboard</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous">
        </script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
        integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
</head>

<body>
    <div class="container">
        <form class="form-inline">
            <div class="form-group mb-2">
                <label for="urllabel" class="sr-only">Enter the URL</label>
                <input type="text" readonly class="form-control" id="urllabel" value="Enter the URL">
            </div>
            <div class="form-group mx-sm-3 mb-2">
                <label for="urlinput" class="sr-only">URL</label>
                <input type="text" class="form-control" id="urlinput" placeholder="https://example.com">
            </div>
            <button type="submit" class="btn btn-primary mb-2" id="message_button">Open page</button>
        </form>
        <p>Got Message:</p>
        <div id="results"></div>
        <br />
    </div>



    <script>
        // addEventListener support for IE8
        function bindEvent(element, eventName, eventHandler) {
            if (element.addEventListener) {
                element.addEventListener(eventName, eventHandler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + eventName, eventHandler);
            }
        }
        console.log('click')
        // $("#message_button").click(function () {


        var messageButton = document.getElementById('message_button'),
            results = document.getElementById('results');


        // Send a message to the child iframe
        var sendMessage = function (msg) {
            // Make sure you are sending a string, and to stringify JSON
            console.log('msg',msg)
            newWin.postMessage(msg, '*');
        };




        // Send random messge data on every button click
        bindEvent(messageButton, 'click', function (e) {
            console.log('click',e);
            var url = $("#urlinput").val();
            var newWin = window.open(url, '', 'location=no,toolbar=0',false);
            var random = Math.random();
            console.log('adsf2')
            sendMessage('' + random);
            return false;
        });


        // })
        // Listen to message from child window
        bindEvent(window, 'message', function (e) {
                console.log(e.data)
                results.innerHTML = e.data;
            });

    </script>
</body>

</html>

新窗口HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>iframe Window</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
        integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <style>
        * {
            box-sizing: border-box;
        }

        .border {
            background: rgba(0, 0, 0, 0.5);
        }
    </style>
</head>

<body>

    <h1>Hello there, i'm an iframe</h1>
    <p id="send_message">Send Message: <button id="message_button">Hi parent</button></p>
    <p id="got_message">Got Message:</p>
    <div id="results"></div>


    <script>
        // addEventListener support for IE8
        function bindEvent(element, eventName, eventHandler) {
            if (element.addEventListener) {
                element.addEventListener(eventName, eventHandler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + eventName, eventHandler);
            }
        }

        // Send a message to the parent
        var sendMessage = function (msg) {
            // Make sure you are sending a string, and to stringify JSON
            window.parent.postMessage(msg, '*');
        };

        var results = document.getElementById('results'),
            messageButton = document.getElementById('message_button');




        function activate() {
            $(document).mouseover(function (e) {
                if (!$(e.target).is('html') && !$(e.target).is('body')) {
                    $(e.target).addClass('border');
                }
            })
            $(document).mouseout(function (e) {
                if (!$(e.target).is('html') && !$(e.target).is('body')) {
                    $(e.target).removeClass('border');
                }
            })

            //Send random message data on every button click
            $(document).click(function (e) {
                e.preventDefault()
                if (!$(e.target).is('html') && !$(e.target).is('body')) {
                    $(e.target).css('border', '3px solid black');
                    window.addEventListener("message", function (event) {
                        console.log(event)
                        event.source.postMessage('' + `${e.target.parentElement.tagName}, ${e.target.tagName}, ${e.target.id}, ${e.target.className}, ${e.target.textContent}`, "*");
                    })
                    // window.close()
                }
            });
        }

        // Listen to messages from parent window
        bindEvent(window, 'message', function (e) {
            console.log('event',e)
            activate()
        });
        // bindEvent(messageButton, 'click', function (e) {
        //     var random = Math.random();
        //     // sendMessage('' + random);
        //     window.addEventListener("message", function (event) {
        //         console.log(event)
        //         event.source.postMessage("" + random, "*");
        //     })
        // });  
    </script>
</body>

</html>

问题是打开新窗口时没有发送消息

0 个答案:

没有答案