@@ -429,7 +429,10 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
429
429
// does something like:
430
430
// window.webkit.messageHandlers.interOp.postMessage({"action": "DoSomething"});
431
431
[webConfig.userContentController addScriptMessageHandler: self name: @" interOp" ];
432
-
432
+
433
+ // Add a script message handler
434
+ [webConfig.userContentController addScriptMessageHandler: self name: @" jsErrorHandler" ];
435
+
433
436
// Some additional settings we may want to set:
434
437
// see more at http://jonathanblog2000.blogspot.com/2016/11/understanding-ios-wkwebview.html
435
438
// [prefs setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
@@ -1179,16 +1182,41 @@ - (void)applicationWillTerminate:(NSNotification *)notification
1179
1182
// This method is for WKScriptMessageHandler, and is triggered each time 'interOp' is sent a
1180
1183
// message from the JavaScript code with something like:
1181
1184
// window.webkit.messageHandlers.interOp.postMessage({"val": 1});
1185
+ // window.webkit.messageHandlers.jsErrorHandler.postMessage({"message": message, "source": source, ...} );
1182
1186
- (void )userContentController : (WKUserContentController *)userContentController
1183
1187
didReceiveScriptMessage : (WKScriptMessage *)message {
1184
1188
NSDictionary *sentData = (NSDictionary *)message.body ;
1185
-
1189
+
1186
1190
if ( sentData == nil )
1187
1191
{
1188
1192
NSLog ( @" didReceiveScriptMessage: got nil dictionary" );
1189
1193
return ;
1190
1194
}
1191
-
1195
+
1196
+ if ([message.name isEqualToString: @" jsErrorHandler" ]) {
1197
+ NSString *errorMessage = sentData[@" message" ];
1198
+ NSString *source = sentData[@" source" ];
1199
+ NSNumber *lineNumber = sentData[@" lineno" ];
1200
+ NSNumber *columnNumber = sentData[@" colno" ];
1201
+ NSString *errorDetails = sentData[@" error" ];
1202
+
1203
+ // Create the alert
1204
+ NSAlert *alert = [[NSAlert alloc ] init ];
1205
+ alert.messageText = @" JavaScript Error" ;
1206
+ alert.
informativeText = [
NSString stringWithFormat: @" Unexpected JavaScript Error - please consider reporting to [email protected] and restarting app:\n\n Message: %@ \n Source: %@ \n Line: %@ \n Column: %@ \n Details: %@ " ,
1207
+ errorMessage ?: @" Unknown" ,
1208
+ source ?: @" Unknown" ,
1209
+ lineNumber ?: @0 ,
1210
+ columnNumber ?: @0 ,
1211
+ errorDetails ?: @" No additional details" ];
1212
+ alert.alertStyle = NSAlertStyleWarning;
1213
+
1214
+ [alert addButtonWithTitle: @" OK" ];
1215
+ [alert runModal ];
1216
+
1217
+ return ;
1218
+ }// if( a JS error )
1219
+
1192
1220
id val = [sentData objectForKey: @" action" ];
1193
1221
if ( val != (id )[NSNull null ] )
1194
1222
{
0 commit comments