2015-09-07 43 views
1

假設我們有一個應用程序,它在window1(父窗口)中運行。然後,我們打開一個子窗口(window2),但其執行代碼位於window1(DOM事件監聽器等)中。如何處理髮生在子窗口中的父窗口中的JavaScript錯誤?

舉一個例子,我們有窗口2內的按鈕,但的onclick事件的事件處理程序是在窗口1

的問題是,當我們有一個處理器內一定的誤差,會一起出現錯誤窗口2的內側error.stack和返回Error.message,但在窗口1,我們將看到什麼。

當然,我們可以在try ... catch語句中包裝該處理程序的整個代碼,但是我們不會收到errors.stack,並且只有一個參數作爲字符串,其中包含error.message。

至於我在嘗試包裹每處理器... catch語句有一些劣勢:

  1. 額外的代碼
  2. 沒有堆棧錯誤
  3. 有時候,我們可以忘記添加try ... catch語句
  4. 更糟糕的代碼的可讀性

所以也許有更好的方法來處理這樣的錯誤?

回答

0

我說你可以聲明在子窗口的onerror處理程序,並用它來執行重定向到父窗口的一些功能。

子窗口:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>error-child</title> 
    </head> 
    <body onerror="window.opener.myErrorHandler(event)"> 
     <h1>error-child</h1> 
     <button onclick="invalidReference.method()">produce error</button> 
     <button onclick="alert('OK')">do something</button> 
    </body> 
</html> 

父窗口:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>error-parent</title> 
     <script type="text/javascript"> 
      function myErrorHandler(event) 
      { 
       alert("Parent window has received an error from the child window: "+event); 
      } 
     </script> 
    </head> 
    <body> 
     <h1>error-parent</h1> 
     <button onclick="window.open('error-child.html')">open child window</button> 
    </body> 
</html> 
相關問題