2010-02-12 70 views
3

我有一個具有「父」窗口的應用程序。在父窗口中有菜單項,如下所示(使用PHP這裏):使用Javascript的持久數據

// sample link 
echo "<li><a href=\"#\" onclick=openurl('covershift.php');>Shift Coverage</a></\ 
li>"; 

// logout link 
echo "<li><a href=\"#\" onclick=openurl('logout');>Logout</a></li>"; 

每個鏈接打開相應的頁面在不同的「孩子」窗口。父母關閉所有子窗口時必須關閉。我已經實現用javascript這個功能,這裏是功能:

var childWindow = new Array(); 
var windowCount = 0; 
function openurl(url) 
{ 
    if(url != 'logout') { 
    childWindow[windowCount]=window.open(url,'_blank','height=600,width=800,scr\ 
ollbars=1'); 
    windowCount++; 
    if (window.focus) { 
     childWindow.focus(); 
    } 
    } else { 
    var iCount; 
    for (iCount=0; iCount < windowCount; iCount++) { 
     if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) { 
     childWindow[iCount].close(); 
     } 
    } 
    window.location='logout.php'; 
    } 
} 

這裏是我的問題,當用戶重新加載父窗口,然後點擊退出,子窗口繼續開放。這是有道理的,因爲child重新加載時,childWindow數組會丟失。

如何使childWindow數組通過重新加載持久化?

謝謝!

回答

1

我不認爲你可以通過窗口加載使JavaScript對象持久化。相反,你可以創建一個關閉頁面的卸載事件處理程序嗎?

window.onunload = myCloseFunction; 
function myCloseFunction() 
{ 
    // Just copying your code... 
    var iCount; 
    for (iCount=0; iCount < windowCount; iCount++) { 
     if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) { 
     childWindow[iCount].close(); 
     } 
    } 
} 

另一種選擇可能是有父存在的子窗口調查。

在子窗口:

// Checks every 1 second for valid window.opener 
var parentChecker = setInterval(function(){ 
    if(!opener){ 
     // Is this good practice? I don't know! 
     clearInterval(parentChecker); 
     window.close(); 
    } 
}, 1000); 
+0

喬納森, 感謝您的及時答覆。兩種解決方案都有其優點。第一個很好,因爲它只需要在一個地方進行修改。我可以預見的第一個解決方案唯一的問題是,用戶可能想要保留他們的數據在子窗口上,並重新加載父窗口。由於用戶行爲,第二種解決方案可能不起作用。我的應用程序的用戶因爲單擊按鈕而臭名昭着,因此可能會意外關閉父母並用錯誤報告給我打電話:-)。如果沒有辦法使數據持續存在,我會選擇1.謝謝! – 2010-02-12 23:42:16

0

如果你想要做的就是堅持一個數組,使用http://rhaboo.org

var store = Rhaboo.persistent("My store"); 

window.onunload = function() { 
    store.write('windows', [ ... your array ...]); 
} 

function onLogout() { 
    for (var i=0; i<store.windows.length; i++) 
    closeWindowYourWay(store.windows[i]); 
}