How to pass data to parent window from popup window?

后端 未结 2 434
無奈伤痛
無奈伤痛 2021-02-07 03:02

How can I pass some data or call a function on the parent window from a popup window?

The user will click a link which will open a popup on the same website, once he is

相关标签:
2条回答
  • 2021-02-07 03:52

    The window.opener object is what you're looking for, used it from within your popup like so to call the a function of the parent window:

    window.opener.yourFunc() 
    
    0 讨论(0)
  • 2021-02-07 04:01

    Here is a fun and easy demo that is heavily inspired by this answer to a similar question (but modified for my own purposes to help investigate the most difficult bug of my career).

    Create 2 files (in the same directory) as follows:

    parent.html

    <button type="button" onclick="popup('popup.html', '', 800, 200);">Add My Card</button>
    =&gt;
    <span id="retrievedData">No data yet.</span>    
    <script>
        function popup(url, title, width, height) {
            var left = (screen.width / 2) - (width / 2);
            var top = (screen.height / 2) - (height / 2);
            var options = '';    
            options += ',width=' + width;
            options += ',height=' + height;
            options += ',top=' + top;
            options += ',left=' + left;    
            return window.open(url, title, options);
        }
    
        function setData(data) {
            console.log(data);
            var strData = JSON.stringify(data);
            document.getElementById('retrievedData').innerHTML = strData;
            var requestBinUrl = 'http://requestb.in/18u87g81';
            window.location.href = requestBinUrl + '?data=' + strData;
        }
    </script>
    

    popup.html

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <form id="popupForm" name="f">    
        <select id="urlField" name="url">
            <option>
                http://date.jsontest.com/
            </option>
            <option>
                http://time.jsontest.com/
            </option>
            <option>
                http://md5.jsontest.com/?text=HereIsSomeStuff
            </option>    
        </select>
        <div><input type="submit" /></div>    
    </form>
    <script>
        $('#popupForm').submit(function(e) {
            e.preventDefault();
            var url = $('#urlField').val();
            console.log(url);
            $.ajax({
                url: url
            }).then(function(data) {
                console.log(JSON.stringify(data));
                window.opener.setData(data);
                window.close();
            });
        });    
    </script>
    
    0 讨论(0)
提交回复
热议问题