WKWebView doesn't run JavaScript when on background WKWebView doesn't run JavaScript when on background xcode xcode

WKWebView doesn't run JavaScript when on background


Unfortunately, WKWebView must be in the view hierarchy to use it. You must have added it as a sub view of an on-screen view controller.

You can add this off-screen so it was not visible. Hidden attribute might have worked as well. Either way you must call addSubview with it to make it work.

There are some other questions and answers here which verify this.

So, I researched a lit bit a found this

WKWebViewConfiguration* webViewConfig = // set up config// provide empty frame rectWKWebView *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 the javascript runs while the app is active and doesn't effect the UI. If you need to display it later you can remove the webView from the keyWindow after render and reset the frame.

Hope this helps!

EDIT

Javascript is disabled by default. In order to run Javascript, you must enable it through WKPreferences. You need to set the javascriptEnabled field of the preferences object to true.

Specifically your code to initialize the WKWebView should look like this.

let contentController = WKUserContentController()contentController.add(self, name: "handler") let configuration = WKWebViewConfiguration()configuration.userContentController = contentControllerconfiguration.preferences = WKPreferences()configuration.preferences.javaScriptEnabled = truewebview = WKWebView(frame: self.view.frame, configuration: configuration)webview.uiDelegate = selfwebview.navigationDelegate = selfself.view = self.webview

Also you can check this post to see a different approach.