UIWebView Event and Upload

I am loading local html content in a UIWebView. The javascript code for the downloaded content includes this event listener:

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

This javascript code is executed only when (before) the UIWebView component is freed up (for example, when switching to another view controller), but it does not execute when another page loads. For instance:

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

If you execute this piece of code in safari when I click on a document, it will display a warning window before going to google.com. If I run the same code in UIWebView, the unloading listener will not execute. However, if I remove the UIWebView, the code will be executed.

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

+4
source share
2 answers

Thanks to the LuisCien decision above (please vote for his message if you like the solution) . I was able to solve the problem by manually creating and sending the unload event with objective-c. This does not require any changes to my client code (javascript), which now behaves the same in UIWebView and any other web browser. Here is the code snippet that needs to be added to the view controller:

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { [webView stringByEvaluatingJavaScriptFromString:@"var e=document.createEvent('Event'); e.initEvent('unload', true, true); window.dispatchEvent(e);"]; return YES; } 
0
source

I also had problems in the past with JavaScript code that does not behave the same in the desktop browser than in UIWebView . I honestly don’t know why it doesn’t work the way you want it to, but here I offer you a job:

Instead of using the unload listener that you have in JavaScript, try using the UIWebViewDelegate webView:shouldStartLoadWithRequest:navigationType: method. This method is called every time a user requests to load a new page (or content). If you need to execute another JavaScript code, you can use the UIWebView stringByEvaluatingJavaScriptFromString: method.

Hope this helps!

+5
source

Source: https://habr.com/ru/post/1490307/


All Articles