Monday, January 30, 2017

Will JavaScripts embedded in an HTML file loaded by WKWebView be accessible?

Leave a Comment

I have a basic foo.html in my iOS 10 application. The markup is straight forward:

<!doctype html> <html>     <head>         <meta charset="utf-8">         <meta http-equiv="x-ua-compatible" content="ie=edge">         <title>Example</title>         <meta name="viewport" content="width=device-width, initial-scale=1">     </head>     <body>         <p>Hello, World!</p>          <div id="container"></div>     </body>     <script type="text/javascript" src="bar.js"></script>     <script type="text/javascript">         // Bar is defined in bar.js         var bar = new Bar();     </script> </html> 

I load it with the following:

let htmlFile = Bundle.main.path(forResource: "foo", ofType: "html") let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8) webView.loadHTMLString(html!, baseURL: nil) 

In my iOS app, I'm trying to access the bar variable. After the DOM is loaded as confirmed by by WKNavigationDelegate's method: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

I have code like this:

var htmlContent : String {    var s = "console.log(bar)"     return s }  webView.evaluateJavaScript(htmlContent, completionHandler: { result, error in   if let error = error {     print("error: \(error)")   }    if let result = result {     print("result: \(result)")   } }) 

I end up getting an error:

error: Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: Bar, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=47} 

Is what I'm trying to do possible? Do I have to approach the problem a different way? Does evaluateJavaScript have access to the scope of my DOM after it's loaded because as of right now, it seems it does not.

1 Answers

Answers 1

I figured it out - will put the answer here hoping it helps someone else:

The problem was here:

webView.loadHTMLString(html!, baseURL: nil)

I had to ensure baseURL is not nil, the following fixes it:

webView.loadHTMLString(html!, baseURL: Bundle.main.bundleURL)

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment