WKWebview does not run javascript (HTTP XML request) without adding parent view

I am updating my project from UIWebView to WKWebView. In the existing UIWebView approach, where the UIWebView has no parent until it runs javascript, and as soon as it has content, it will add the parent to the webview. Content is rendered using UIWebView. I use the same approach for WKWebView, however WKWebview is stuck on loading. Is there a way we can execute javascript on wkwebview without adding a parent element in webview. Another interesting thing is the work on the simulator is not on the device. Using localHTTPServer to serve html, css and images.

Any suggestions or tips to solve the above problem.

+8
source share
3 answers

I have observed similar behavior in my application running socket.io in a headless WKWebView. In my case, the web socket will disconnect all the time and not reconnect.

It seems that since WKWebView starts javascript off-process, it pauses any javascript that is considered inactive to save resources (<-IMO). Idle includes lack of parent or application / device inactive. So yes, it seems you are right that in most cases this requires a parent view. I was able to get around this using the following code:

WKWebViewConfiguration* webViewConfig = // set up config // provide empty frame rect WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfig]; // add to keyWindow to ensure it is 'active' [UIApplication.sharedApplication.keyWindow addSubview:webView]; 

This approach at least ensures javascript execution while the application is active and does not affect the user interface. If you need to display it later, you can remove the webView from keyWindow after rendering and resetting the frame. And, yes, I also noticed that this is not a problem in the simulator (javascript ALWAYS works, regardless of the state of the parent or application)

Hope this helps!

+12
source

The decision worked for me for a while. I tried something else that seems to work for me sequentially:

 self.keepWebViewActiveTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(_keepWKWebViewActive:) userInfo:nil repeats:YES]; 

Where _keepWKWebViewActive :

 -(void) _keepWKWebViewActive:(NSTimer*) timer{ if(self.webView) { [self.webView evaluateJavaScript:@"1+1" completionHandler:nil]; } } 
+2
source

Tried 2 solutions above but not working. Interruption of the connection when the application goes into the background.

0
source

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


All Articles