tags:

views:

69

answers:

1

If I open a window with JavaScript (e.g., with window.open()), is there a way, using the handle on the window I opened, to be notified when the URL of the window I opened changes? For example, I'd like to be able to do something like this, generally:

<script type="text/javascript">

    function openNewWindowAndNavigateTo(url)
    {
     var w = window.open(url, "myWindow");
     w.addEventListener("locationChange", handleLocationChange);  
    }

    function handleLocationChange(e)
    {
     alert(e.sourceWindow.newLocation); 
    }

</script>

<a onclick="openNewWindowAndNavigateTo('SomeDocumentIAuthored.html')">Go</a>

Even if it's browser-specific (this is just for demonstrative purposes), is this even possible? If so, how? Assuming both documents live on the same domain, etc. Can it be done?

+1  A: 

If both documents live on the same domain and are under your control, you will need to have the newly loaded document emit script which notifies the parent window it has just been loaded:

<script type="text/javascript">
    window.opener.notifyOpened(window.location.href + ' just loaded');
</script>

Otherwise, no. The act of navigating in the browser is outside the scope of the JavaScript sandbox. Obviously there are much more elegant, robust ways of doing what I demonstrated above, but that gets the general relationship across.

Rex M
Yeah, that does make total sense -- though it's the answer I was afraid of. ;) Thanks for the prompt response!
Christian Nunciato