3

How can I catch an exception thrown inside my iframe?

Here is my code:

Parent:

        iframe = document.createElement("iframe");
        iframe.src = "../a.aspx";
        iframe.style.display = "none";
        document.body.appendChild(iframe);

and the code inside a.aspx:

    protected void Page_Load(object sender, EventArgs e)
    {
            GenerateKey();
            //This function throws an exception, and I want to catch it in the parent window (javascript)
    }

I want to catch the exception in the page that opens the iframe and show an alert box. I tried iframe.contentWindow.onerror, but it didn't work.

Thanks for the help,

Inbal.

Inbal
  • 909
  • 2
  • 28
  • 46
  • Correct the exception error - not try to find solution to catch it. – Aristos Jul 29 '12 at 07:13
  • 1
    @Aristos - I want to display an error to the user, but I want to do that inside the parent page. This is the "Correction". – Inbal Jul 29 '12 at 07:23
  • when you have the exception (capture it) : render a javascript code that show a message on the parent. There is no other way, the parent page is not running when your iframe throw the exception. – Aristos Jul 29 '12 at 07:55
  • I tried this inside the iframe server side: Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "parent.test();", true); but it didn't work. Do you have any suggestion why? Thanks a lot! – Inbal Jul 29 '12 at 08:04

1 Answers1

1

Cross origin may disallow you to control iframe. Inside your iframe page, you can catch its exception and call parent function to display it.

try{
//something
}catch(e){
   window.top.some_public_function(e);
   //window.parent.some_public_function(e) is also work
}
James
  • 13,571
  • 6
  • 61
  • 83