Search code examples
javascriptjqueryhtmlparent

Disable link after child window is open, restore once child window is closed


My client has a link on their website which opens a customer service chat window in a popup. They are seeing users clicking the chat link multiple times, which opens multiple chat sessions, and it is throwing off their stats. I need to disable the link when the chat window is opened, and restore it when the chat window has been closed. I can't modify/access child window.

The original link looks like this:

<a class="initChat" onclick="window.open('https://chatlinkhere.com','chatwindow','width=612,height=380,scrollbars=0'); return false;">

I figured the best thing to do would be to store the window.open() as a variable in a function:

function openChat() {
    child = window.open('http://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0,menubar=0');
}

and change the link HTML to

<a class="initChat" onclick="openChat();">

Note: Ideally, I'd like to detect the original onclick's value, and store it in a variable. Something like:

  jQuery('.initChat').find().attr('onclick');

But I'm not sure how to store it and then call it later.

Next I need to run a check to see if the chat window is open or not:

timer = setInterval(checkChild, 500);

function checkChild() {
    if (child.open) {
        alert("opened");
        jQuery(".initChat").removeAttr("onclick");
        jQuery(".initChat").css("opacity", ".5");
        clearInterval(timer);
    }

    if (child.closed) {
        alert("closed");
        jQuery(".initChat").attr('onclick', 'openChat(); checkChild();');
        jQuery(".initChat").css("opacity", "1.0");
        clearInterval(timer);
    }
}

Note: the alerts are just there for testing.

And add the new function to the link

<a class="initChat" onclick="openChat(); checkChild();">

And once the chat window is closed, I need to restore the onclick attribute to the link (is there an easier way to do this?)

Fiddle demo is here -> http://jsfiddle.net/JkthJ/

When I check Chrome Console I'm getting error Uncaught TypeError: Cannot read property 'open' of undefined

UPDATE Whoever left me the answer in http://jsfiddle.net/JkthJ/2/ thank you very much it works! :)


Solution

  • This is what I got to finally work:

        <a class="initChat" onclick="checkWin()"></a>
    
    
        <script>
        var myWindow;
    
        function openWin() {
            myWindow = window.open('https://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0');
        }
    
        function checkWin() {
            if (!myWindow) {
                openWin();
            } else {
                if (myWindow.closed) {
                    openWin();
                } else {
                    alert('Chat is already opened.');
                    myWindow.focus();
                }
            }
        }
        </script>