Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView and unload event

I'm loading local html contents into a UIWebView. The javascript code of the loaded contents includes this event listener:

window.addEventListener("unload", function(){
  // do something here;
});

That javascript code it is only executed when (before) the UIWebView component is released (e.g. when navigating back to another view controller) but it is not executed when another page is loaded. For example:

document.addEventListener("click", function(){ document.location = "www.google.com"; });
window.addEventListener("unload", function(){ alert("bye bye"); });

If executing this piece of code in safari, when I click on the document, before navigating to google.com, it would display the alert box. If I run the same code in UIWebView, the unload listener it is not executed. However, If I delete the UIWebView, the code is then executed.

My need is to have the same as in Safari, that is the unload method to be executed also when navigating away from the page.

like image 293
lviggiani Avatar asked Jul 08 '13 14:07

lviggiani


People also ask

What is unload event?

The unload event occurs when the user navigates away from the page. The unload event is triggered when: a link to leave the page is clicked. a new URL is typed in the address bar.

How do I reset Wkwebview?

To clear old contents of webview With UIWebView you would use UIWebViewDelegate 's - webViewDidFinishLoad: .


1 Answers

I too have had problems in the past with JavaScript code that doesn't behave the same way in a desktop browser than in a UIWebView. I honestly don't know why it isn't working the way you want it to, but here I offer you a work around:

Instead of using the unload listener you have in JavaScript, try using UIWebViewDelegate's method webView:shouldStartLoadWithRequest:navigationType:. This method gets called whenever the user requests to load a new page (or content). If you then need to execute more JavaScript code you could use UIWebView's method stringByEvaluatingJavaScriptFromString:.

Hope this helps!

like image 160
LuisCien Avatar answered Sep 20 '22 20:09

LuisCien