Search code examples
javascriptasp-classicdom-events

Programmatically determine whether a window is standalone or orphaned


I have a need to figure out whether a window was opened as a standalone vs. whether it was orphaned. Let me illustrate what I mean.

Let's say I have two ASP pages that I'll call PARENT.asp and CHILD.asp. Additionally, there is a redirect page that I'll call CHILD-REDIRECT.asp.

When a certain button on CHILD.asp is clicked, it redirects to CHILD-REDIRECT.asp, which includes client-side Javascript code that needs to run a certain way, depending on whether or not it has a parent (based on window.opener == null). For sake of illustration, I'll say the Javascript code is a Boolean variable that I'll call IsOrphan.

So, I open a new browser window and I navigate to CHILD.asp. I then click the button that redirects to CHILD-REDIRECT.asp and kicks off the Javascript. Because I opened it as a standalone page, IsOrphan = FALSE.

Now, I open a new browser and navigate to PARENT.asp. This page includes a window.open call that opens CHILD.asp in a new window. While CHILD.asp is open, I close PARENT.asp so that CHILD.asp is now in an orphaned window. So now when I click the button and the page redirects to CHILD-REDIRECT.asp, I need IsOrphan = TRUE.

Any thoughts as to how to do this? I'm looking into setting a variable for the parent via window.opener on the CHILD.asp onload event; however, because of the complexity of these pages, this isn't as easy as it sounds. As it stands now, the Javascript checks window.opener to kick off the code, but of course, it doesn't know the difference between a standalone page and an orphaned page. I'm hoping that someone out there knows of a good/better way to do this.


Solution

  • I got this to work.

    In my CHILD.asp page, I set up the following at the top of the page:

    <script>
       var isChild;
       if (window.opener == null) { isChild = false } else { isChild = true }
    </script>
    

    This instantiates the isChild client-side variable when the page loads.

    My server-side classic ASP code contains something that looks like this:

    response.write("javascript: if (1=1) { window.location.href='CHILD-REDIRECT.asp?ID=" & someID & "';")
    

    I have to admit that one of my hangups was how to send this to the server-side code. However, I then realized that this would be a moot point, because the client-side value should be there when it rendered.

    So, I rewrote it like this:

    response.write("javascript: if (1=1) { window.location.href='CHILD-REDIRECT.asp?ID=" & someID & "&isChild=' + isChild;")
    

    In the CHILD-REDIRECT.asp, I added:

    var boolChild = <%request.QueryString("isChild")%>
    

    So now, I have a flag that indicates whether or not the page was generated by a parent. Later in the code, I have this:

    if (window.opener == null && boolChild) { 
       // do something 
    }
    

    Sure enough, it's doing what I need it to do.