How can I catch an exception thrown from inside an iframe?

1.8k views Asked by At

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.

1

There are 1 answers

2
Nhu Trinh On

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
}