Sample of page loaded in web view:
<html> <body> <script> function getWindowInfo() { return { width: window.innerWidth || document.body.clientWidth, height: window.innerHeight || document.body.clientHeight } }; </script> </body> </html>
In a UIView
or UIViewController
:
import WebKit // Enable Javascript in web view let config = WKWebViewConfiguration() let prefs = WKPreferences() prefs.javaScriptEnabled = true config.preferences = prefs // Instantiate web view. Use self.view.bounds in a UIViewController. var webView: WKWebView = WKWebView(frame: self.bounds, configuration: config) // Load page in web view let url = "https://example.com/test.html" let webViewUrl = URL(string: url)! webView.load(URLRequest(url: webViewUrl)) // Run inline Javascript or call a function on the page loaded in the web view let script = "getWindowInfo();" webView.evaluateJavaScript(script, completionHandler: { (result, error) in // result is the value of the final statement in the injected javascript // if script is "var x = 1; x++;", result will be 2 // Do some error checking if (error != nil || result == nil) { return } // If the Javascript function returns an object, cast it into a Dictionary let dict = result as! [String:AnyObject] // Print the key-value pairs in the dictionary for (key, value) in dict { print("\(key) : \(value)") } })