VJS
VJS

Reputation: 2951

javascript: pop up close when page refresh

Below is my javascript code.

pop up is getting opened but my page is refresh. Now I have to close the popup. I am trying to save popupWindow in localStorage. But when i am getting through localStorage.getItem("someVarName"). I am not getting original dom, looks like its changed. As my page is getting refresh, i have to save dom.

Please suggest how to do it.

<script language="javascript" type="text/javascript">
  function openPopup(URL) {
    popupWindow = window.open(URL, 'popupWindow', 'height=300,width=450');
    localStorage.setItem("someVarName", popupWindow);
  }

  function closePopup() {
    var popupWindow = localStorage.getItem("someVarName");
    popupWindow.close();
  }
</script>

Upvotes: 1

Views: 64

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

Web storage stores strings. You can't store a window reference in it.

You can, though, store the name you used and reuse that with window.open:

function openPopup(URL) {
    window.open(URL, 'popupWindow', 'height=300,width=450');
    localStorage.setItem("someVarName", "popupWindow");
}

function closePopup() {
    var name = localStorage.getItem("someVarName");
    if (name) {
        var wnd = window.open("", name);
        wnd.close();
        localStorage.removeItem("someVarName");
    }
}

Calling window.open with the name of an existing window that your page has access to gives you a reference to that existing window, instead of opening a new one.

Note how I'm clearing the name from storage when the window isn't open, so we don't try to close it (which would, paradoxically, open it).

My answer to this other question has a complete example.

Upvotes: 1

Related Questions