minoue10
minoue10

Reputation: 81

WKWebview's javascript call returns nil

I'm trying to migrate from using a UIWebview to a WKWebview, and I need to invoke various Javascript functions that live in the webview.

In the UIWebview I have no trouble doing this, but the WKWebview throws an WKErrorDomain Error 4 for any and all calls. I thought it might be a race condition where I was calling functions that didn't exist in the DOM yet, but I added a debug statement to make those same calls once the page loaded and they're not working. I even did a 'document.body.innerHTML' which returned nil when there's clearly content being displayed in the webview.

The twist is that when inspecting the web code via Safari Web Inspector, everything works well and all calls work.

Why and how could this be? I do initialize the WKWebView with a WKWebViewConfiguration so that it'll share cookies across different webviews, so there might be something there, but I'm stumped.

This is how i initialize the WKWebView

WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.processPool = [[WKProcessPool alloc] init];
WKUserContentController* userContentController = WKUserContentController.new; 
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie = 'cookie1=value1; domain=blah; path=/;';" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
config.userContentController = userContentController;
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,50,50) configuration:config];

Here's a debugging statement where I log the document's innerHTML into the console log, which prints (nil) instead of the HTML.

NSLog(@"%@", [self.webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:nil]);

Upvotes: 1

Views: 1769

Answers (1)

Subbu
Subbu

Reputation: 2148

WKWebView executes JS async unlike UIWebView; You cannot print like how you are doing..

Try this

  [self.webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id result, NSError *error) {
    NSLog(@"Error is %@",error);
    NSLog(@"JS result %@" ,result);
}];

Upvotes: 2

Related Questions