0

How can I pass data between two windows using javascript. I tried using global variable. But when the child window close, the variable value become undefined.

Here is parent js.

var allVariables;
function popupEmpSelect(id, code, name, display) {
    var w = 800;
    var h = 600;
    var l = Number((window.screen.width - w) / 2);
    var t = Number((window.screen.height - h) / 3);
    var url = createUrl();

    allVariables = window.open(url + '/dialog/empSelect/?displaySwitch='
            + display, 'empSelect',
            'menubar=no, toolbar=no, location=no, width=' + w + ', height=' + h
                    + ', top=' + t + ', left=' + l);   

    $(allVariables).on('unload', function () {
        setTimeout(function () {

            console.log(localStorage.getItem('data'));//The result become null here

            console.log(allVariables);
            console.log(allVariables.jsonObject);//**allVariables.jsonObject is always undefined here**

            if ( !allVariables.closed ) return;
            if ( typeof allVariables.jsonObject === 'undefined' ) return;

            var val = JSON.parse(allVariables.jsonObject)[0];
            console.log(allVariables.jsonObject);
            if (!isElementEmpty(id)) $('#' + id).val(val.id);
            if (!isElementEmpty(code)) $('#' + code).val(val.code);
            if (!isElementEmpty(name)) $('#' + name).val(val.name);

            if(display == 'true'){
                collbackEmpSelect();
            }

        },10);
    });

}

Here is child js.

var jsonObject;
    $('button[name="btn_select"]').on('click', function(){
        var json = new Array();
        if ($('input[name="checked"]:checked').length == 0) {
            setTimeout(function() {
                $('#select1').focus();
            }, 1);
            return false;
        }

        let emp_No = '';
        let emp_Name = '';
        $('input[name="checked"]:checked').each(function() {
            var s =$(this).val().split(",");
            var $row = $(this).closest('tr');
            var tmpEmpNo=$row.find(".empNo").text();
            var tmpEmpName=$row.find(".empName").text();

            emp_No += (emp_No != '' ? "," : "") + tmpEmpNo;
            emp_Name += (emp_Name != '' ? "," : "") + tmpEmpName;
        });
        var checjed = {
                "empNo":emp_No,
                "empName":emp_Name
        }
        json.push(checjed);

        jsonObject = JSON.stringify( json );

        **localStorage.setItem('data', jsonObject);**

        window.close();
    });

The problem is jsonObject is always undefined when accessing from parent.js
What should I do to access jsonObject from parent.js

ZanZan
  • 47
  • 4
  • If you don't care about IE, window.opener is a way to send data to the parent window (set a global var, call a function, whatever). EDIT: also, why is your parent waiting to call the unload handler (via setTimeout), rather than directly calling it at event time? – josh.trow May 15 '20 at 04:11
  • I used unload handler because I want to do the process after closing child window. Is there another better way? I am new to Javascript and there are many things I don't know. – ZanZan May 15 '20 at 04:16
  • Can you just try to increase the setTimeout to 100 ? Maybe that works – Raj Kumar May 15 '20 at 04:55
  • I will try increasing setTimeout too.Thanks. – ZanZan May 15 '20 at 05:05

2 Answers2

1

You can store data directly in window object like this, window.jsonObject.

This object can be accessible from your parent window. But it will only work in the case of parent and child windows. Otherwise you've to use the localStorage.

Checkout this question once, Storing a variable in the JavaScript 'window' object is a proper way to use that object?

Dhairya
  • 33
  • 5
0

I don't think it is possible to share data between two windows. What I would suggest you is to use localstorage.

Then you can save data like localStorage.setItem('data', json) and access it using localStorage.getItem('data').

Once you are done you can call localStorage.clear()

Hope this helps

Raj Kumar
  • 1,547
  • 14
  • 19
  • Two windows from the same domain _can_ share data. – Michael Geary May 15 '20 at 04:22
  • When I tried to access using localStorage.getItem('data') from parent window.The result become null. – ZanZan May 15 '20 at 04:31
  • Can you show me the code that you wrote? I've used this multiple times in the past – Raj Kumar May 15 '20 at 04:33
  • @MichaelGeary sorry, wasn't aware about that – Raj Kumar May 15 '20 at 04:33
  • @ZanZan Also The localStorage.setItem() is a asynchronous task. Can you try - setTimeout(function() { let data = localStorage.getItem('data'); console.log(data); }, 50); Maybe you are trying to access data before the asynchronous processing completes – Raj Kumar May 15 '20 at 04:39
  • @RajKumar -setTimeout(function() { let data = localStorage.getItem('data'); console.log(data); }, 50); is fine only after refreshing the page. For the first time, the result become null. – ZanZan May 15 '20 at 05:16
  • `localStorage.setItem()` [is synchronous](https://www.google.com/search?q=localstorage+setitem+asynchronous). – Michael Geary May 15 '20 at 06:36
  • 1
    Also, if `localStorage.setItem()` (or any other function) _was_ asynchronous, a 50 millisecond timeout would never be the way to handle that. Any asynchronous function must provide a way to notify you of completion. Otherwise, how would you know if you should wait 10 milliseconds, or 50, or 90? – Michael Geary May 15 '20 at 06:44
  • Well, I guess I need to study more of such things. Thanks for pointing out the holes in the answer – Raj Kumar May 15 '20 at 08:29
  • @MichaelGeary can you tell me what should I do so that I can access **jsonObject** when the child window is closed? – ZanZan May 17 '20 at 02:30
  • @MichaelGeary According to this documentation https://developer.mozilla.org/en-US/docs/Web/API/Window it doesn't seem that window objects can be shared among different tabs. ```In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo() and innerHeight.``` – Raj Kumar May 17 '20 at 05:22