1

I have following HTML structure to load in WKWebView :

<html>
<body>
...
//CSS code
...
<div id='main-div'>
<div id='inner-div'>
...
//Actual contents to display
...
</div>
</div>
...
//Javascript code
...
</body>
</html>

I'm loading above HTML as a string in WKWebview:

[webView loadHTMLString:htmlString baseURL:nil]

And calculating inner div height (which resized automatically based on css to fit content) as :

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
NSString *height = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('inner-div').offsetHeight;"];

NSLog(@"Height :: %@",height);
.
.
.     
}

Where stringByEvaluatingJavaScriptFromString function implemented in WKWebView category :

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script {
    __block NSString *resultString = nil;
    __block BOOL finished = NO;

    [self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
        if (error == nil) {
            if (result != nil) {
                resultString = [NSString stringWithFormat:@"%@", result];
            }
        } else {
            NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
        }
        finished = YES;
    }];

    while (!finished)
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return resultString;
}

My problem is I'm getting Error : "A JavaScript exception occurred", or sometimes incorrect value when using stringByEvaluatingJavaScriptFromString. However, I tried evaluating same javascript for height with UIWebView and it returned correct value. Whats wrong with WKWebview ?

Thanks !

iAkshay
  • 1,143
  • 1
  • 13
  • 35

0 Answers0