Wkwebkit JavaScript Execution When Not Attached to a View Hierarchy

Keeping a WKWebView and it's UIViewController in the background running and accessible from multiple ViewControllers

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.

This was fine for me. I added 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.

Intercept javascript file from loading in web view

Following is the complete example. I hope it will help you.

import UIKit

class ViewController: UIViewController,UIWebViewDelegate {

private var webView: UIWebView!

override func loadView() {
webView = UIWebView(frame: .zero)
webView.delegate = self
view = webView
}

override func viewDidLoad() {
super.viewDidLoad()
// set the view controller title, navigation etc
self.loadWebPage()
}

func loadWebPage() {
let url = URL(string: "https://www.google.com.pk/")
// let localFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "ExampleHtmlFileName", ofType: "html", inDirectory: "HtmlFilesFolderName")!)
let myRequest = URLRequest(url: url!)
webView.loadRequest(myRequest)
}

//MARK: UIWebView Delegate
func webViewDidFinishLoad(_ webView: UIWebView) {

let jsScript = "exampleJSMethod()"
_ = webView.stringByEvaluatingJavaScript(from: jsScript)
}

}

WkWebView does not load links to pdfs

There are a few things you can check:

  1. Verify that the <a href links doesn't contain target="_blank" attribute since WKWebView doesn't know how to open the link in a new tab. see https://stackoverflow.com/a/25853806/810466 for how to work around that.

  2. Check if the link is HTTPS or update the App Transport Security Settings with the Allow Arbitrary Loads option

  3. Make sure that you start the loading request only after adding the WKWebView to the view hierarchy in didMoveToParentViewController: since it may make javascript to fail if it tries to run outside the view hierarchy

  4. Implement the WKWebView NavigationDelegate methods and make sure you return WKNavigationActionPolicyAllow when deciding the policy for the request



Related Topics



Leave a reply



Submit