0

I have written logic to logout from web application in beforeunload even, as follows:

window.addEventListener("beforeunload", function (event) {  
   //Logout logic
   //Calling logout api with values from session
   //clearing the session on success 
});

it is working fine in all web browsers (IE, Mozilla, Chrome), however It is not working from WebBrowser control in winform application.

What could be the reason behind it?

PS: there is nothing wrong with javascript, when I call this same script by invoking it as below, it works fine:

   HtmlElement head = webBrowser4.Document.GetElementsByTagName("head")[0];
   HtmlElement scriptEl = webBrowser4.Document.CreateElement("script");
   IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
   element.text = @"function Logout() {
   $.ajax({
         url: '/api/Logout',
         type: ""GET"",
         contentType: ""application/json;charset=utf-8"",
         success: function(returnVal) {
                    },
         complete: function() {
                     sessionStorage.clear();
                    },
         error: function(returnVal) {
                        }
                    });
                 }";
     head.AppendChild(scriptEl);
     webBrowser4.Document.InvokeScript("Logout");

What is the problem with beforeunload event in WebBrowser control in winform?

YoungMonk
  • 63
  • 6
  • Try to use `InvokeScript` method, here is a thread https://stackoverflow.com/questions/7322420/calling-javascript-object-method-using-webbrowser-document-invokescript – Pavel Anikhouski Feb 26 '19 at 12:15
  • What if I don't have control over the logout implementation in the future? – YoungMonk Feb 26 '19 at 12:46
  • 1
    If you expect to handle it in close event of the form, it will not work. But if you expect it work when navigating to another address, it works properly. – Reza Aghaei Feb 26 '19 at 13:49
  • Just in case you want user start a new session (not being logged in) when you open your application, you can disable cache and cookies. Take a look at [this example](https://stackoverflow.com/a/52133282/3110834). – Reza Aghaei Feb 26 '19 at 13:55
  • @RezaAghaei thanks for your help, but because of application requirements this will not work for me. – YoungMonk Feb 27 '19 at 05:55

1 Answers1

0

Did you try it without listener?

window.onbeforeunload = function(event)
Koxo
  • 507
  • 4
  • 10