@@ -1401,6 +1401,12 @@ - (void) webView:(WKWebView *)webView
1401
1401
decisionHandler (WKNavigationActionPolicyCancel );
1402
1402
return ;
1403
1403
}
1404
+ } else if ([self isDownloadableFileURL: navigationAction.request.URL]) {
1405
+ if (_onFileDownload) {
1406
+ [self handleRegularFileDownload: urlString];
1407
+ decisionHandler (WKNavigationActionPolicyCancel );
1408
+ return ;
1409
+ }
1404
1410
}
1405
1411
1406
1412
dispatch_once (&onceToken, ^{
@@ -2053,6 +2059,50 @@ - (void)handleBlobDownloadUrl:(NSString *)urlString {
2053
2059
[self .webView evaluateJavaScript: jsCode completionHandler: ^(id result, NSError *error) {}];
2054
2060
}
2055
2061
2062
+ - (BOOL )isDownloadableFileURL: (NSURL *)url {
2063
+ if (!url || !url.pathExtension ) {
2064
+ return NO ;
2065
+ }
2066
+
2067
+ NSString *extension = [url.pathExtension lowercaseString ];
2068
+ NSSet *downloadableExtensions = [NSSet setWithObjects:
2069
+ @" jpg" , @" jpeg" , @" png" , @" gif" , @" bmp" , @" webp" , @" svg" , // Images
2070
+ @" pdf" , @" doc" , @" docx" , @" xls" , @" xlsx" , @" ppt" , @" pptx" , // Documents
2071
+ @" txt" , @" rtf" , @" csv" , @" json" , @" xml" , // Text files
2072
+ @" zip" , @" rar" , @" 7z" , @" tar" , @" gz" , // Archives
2073
+ @" mp3" , @" wav" , @" m4a" , @" aac" , @" flac" , // Audio
2074
+ @" mp4" , @" avi" , @" mov" , @" wmv" , @" mkv" , @" webm" , // Video
2075
+ nil
2076
+ ];
2077
+
2078
+ return [downloadableExtensions containsObject: extension];
2079
+ }
2080
+
2081
+ - (void )handleRegularFileDownload: (NSString *)urlString {
2082
+ NSString *jsCode = [NSString stringWithFormat:
2083
+ @" fetch('%@ ')"
2084
+ " .then(response => {"
2085
+ " if (!response.ok) throw new Error('Network response was not ok');"
2086
+ " return response.blob();"
2087
+ " })"
2088
+ " .then(blob => {"
2089
+ " const reader = new FileReader();"
2090
+ " reader.onloadend = function() {"
2091
+ " window.webkit.messageHandlers.base64Handler.postMessage(reader.result);"
2092
+ " };"
2093
+ " reader.readAsDataURL(blob);"
2094
+ " })"
2095
+ " .catch(error => {"
2096
+ " console.error('Download failed:', error);"
2097
+ " });" , urlString];
2098
+
2099
+ [self .webView evaluateJavaScript: jsCode completionHandler: ^(id result, NSError *error) {
2100
+ if (error) {
2101
+ NSLog (@" Error downloading file: %@ " , error.localizedDescription );
2102
+ }
2103
+ }];
2104
+ }
2105
+
2056
2106
@end
2057
2107
2058
2108
@implementation RNCWeakScriptMessageDelegate
0 commit comments