Javascript not running in WKWebview in background

In current project, We are doing migration from UIwebview to WKwebview.

Our application designed in such a way, to keep a webview instance in background whenever it is not in use, based on the need basis, we bring the webview to foreground and render it in screen. Even in background we execute some javascript and update few data. This approach worked well in UIWebview so far, but in WKWebview is not working as expected.

Problem Statement:
When we try to execute some javascript in wkwebview with help of "evaluateJavaScript" method in background, sometimes javascript stopped executing in between, but if we keep webview in foreground, then no issues, same javascript code executing without any issue.

Any suggestions to execute Javascript in wkwebview in background will helpful. Thanks.

Replies

You can get the Javascript to work by adding the WKWebView to the view hierarchy. You can hide the web view by giving it a zero rect.

let config = WKWebViewConfiguration()
_webView = WKWebView.init(frame: CGRect.zero, configuration: config)
instanceOfYourView.addSubview(_webView!)