Search code examples
c#winformsbrowseronbeforeunload

How to handle onbeforeunload event using winform webbrowser


I am having the exact same issue with a WinForms WebBrowser control and the onbeforeunload javascript event handling as this post (How to intercept the onbeforeunload event in a WebBrowser control?). I tried the same solution as presented to cast the onbeforeunload event to IDispatch and call the Invoke method. I get this error when doing so:

hr = -2147352319

I'm developing in .NET 3.5 on WinXP using IE 6.0.

I did not put the C# code here because it is exactly the same as the linked article above.

The JavaScript code is :

function onBeforeUnload()
{
    if (window.cObject.isTransferred)
    {
        event.returnValue = "\nYou are requesting to exit.\n";                   
    }
    else
    {
        event.returnValue = "\nYou are DELETING this object!!!\n";
    }
}

Solution

  • The error translates to 0x80020101, which in turn translates to SCRIPT_E_REPORTED (here's a how-to do this yourself). Microsoft has a confirmed bug that they say occurs often on multicore or multi-processor computers, but may occur on single processor computers as well. Microsoft explains that it has to do with the invocation of the COM interfaces.

    This backs up the story in your referred to thread, where the user eventually follows Hans Passant's answer, but receives this error. By changing the P/Invoke declarations, he manages to solve the problem (the answer is written in the question itself).

    Yet another source suggests that this might also mean an error in the script itself. If that's the case, you should be able to catch the script error by handling onScriptError.

    My suggestions:

    • try the suggested alternative approach in the referred thread (if you haven't tried so already)
    • create a handler for onScriptError

    EDIT: the OP has tried some suggestions and found out that this was above all a JavaScript error (my second suggestion): instead of event, window.event should've been used, or a common event access technique as described in this Quirksmode article.