From 9622fc8e057b4654c06f77e4007ea55a73f50469 Mon Sep 17 00:00:00 2001 From: ed Date: Fri, 19 Feb 2021 17:41:35 +0000 Subject: [PATCH] macOS: Added support for loading local files in WebBrowserComponent --- .../native/juce_mac_WebBrowserComponent.mm | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/modules/juce_gui_extra/native/juce_mac_WebBrowserComponent.mm b/modules/juce_gui_extra/native/juce_mac_WebBrowserComponent.mm index d9e3a7b7f5..3ba0a42f52 100644 --- a/modules/juce_gui_extra/native/juce_mac_WebBrowserComponent.mm +++ b/modules/juce_gui_extra/native/juce_mac_WebBrowserComponent.mm @@ -45,9 +45,9 @@ static NSMutableURLRequest* getRequestForURL (const String& url, const StringArr NSString* urlString = juceStringToNS (url); #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_9) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9) - urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; + urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]]; #else - urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; #endif if (NSURL* nsURL = [NSURL URLWithString: urlString]) @@ -312,7 +312,9 @@ public: const StringArray* headers, const MemoryBlock* postData) { - if (url.trimStart().startsWithIgnoreCase ("javascript:")) + auto trimmed = url.trimStart(); + + if (trimmed.startsWithIgnoreCase ("javascript:")) { [webView evaluateJavaScript: juceStringToNS (url.fromFirstOccurrenceOf (":", false, false)) completionHandler: nil]; @@ -322,8 +324,17 @@ public: stop(); - if (NSMutableURLRequest* request = getRequestForURL (url, headers, postData)) + if (trimmed.startsWithIgnoreCase ("file:")) + { + auto file = URL (url).getLocalFile(); + + if (NSURL* nsUrl = [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]) + [webView loadFileURL: nsUrl allowingReadAccessToURL: nsUrl]; + } + else if (NSMutableURLRequest* request = getRequestForURL (url, headers, postData)) + { [webView loadRequest: request]; + } } void goBack() { [webView goBack]; } @@ -540,7 +551,24 @@ public: stop(); - if (NSMutableURLRequest* request = getRequestForURL (url, headers, postData)) + auto getRequest = [&]() -> NSMutableURLRequest* + { + if (url.trimStart().startsWithIgnoreCase ("file:")) + { + auto file = URL (url).getLocalFile(); + + if (NSURL* nsUrl = [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]) + return [NSMutableURLRequest requestWithURL: nsUrl + cachePolicy: NSURLRequestUseProtocolCachePolicy + timeoutInterval: 30.0]; + + return nullptr; + } + + return getRequestForURL (url, headers, postData); + }; + + if (NSMutableURLRequest* request = getRequest()) { #if JUCE_MAC [[webView mainFrame] loadRequest: request];