Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluateJavaScript WKWebView iOS 15 not working

I'm using WebCrypto library to decrypt the data but it's not working on iOS 15 Its working fine in iOS 14

I have checked the evaluateJavaScript function of webView is throwing error

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=27, 
WKJavaScriptExceptionMessage=TypeError: undefined is not an object (evaluating 'y.importKey'), WKJavaScriptExceptionColumnNumber=8260, 
WKJavaScriptExceptionSourceURL=undefined, NSLocalizedDescription=A JavaScript exception occurred}
like image 291
Kishore Suthar Avatar asked Nov 07 '22 00:11

Kishore Suthar


1 Answers

I stumbled also upon this, the new IOS15 behavior did break our code too. Apparently Apple changed the semantics of evaluateJavaScript : depending on when the following code has been called the new function does not appear in the JS namespace if it is called too early.

[_webview evaluateJavaScript:@"function foobar() {console.log('in foobar');}" completionHandler:^(NSObject* res,NSError* err) {
}];

if this code is called prior to

[_webview loadRequest:req];

then it doesn't have any effect anymore (But no error is raised at that point..the function lands in nirvana ). The solution is to add such code as user script as pointed out at https://developer.apple.com/forums/thread/684020

WKUserScript *script = [[WKUserScript alloc] initWithSource:@"function foobar() {console.log('in foobar');" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[_webview.configuration.userContentController addUserScript:script];
like image 186
Leo Avatar answered Nov 30 '22 06:11

Leo