Last active
December 11, 2024 15:55
-
-
Save alex-sherwin/69c42804b3b6e3d8f500f309747fb72a to your computer and use it in GitHub Desktop.
Setting custom HTTP headers on all capacitor:// scheme WKWebView web requests in capacitorjs framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this uses Objective-C swizzling pattern to swap method implementations at runtime to gain access to the | |
// WKURLSchemeTask so that it can be wrapped using a delegation pattern allowing us to modify the headers | |
// set by the original implementation to add additional ones before ultimately calling the real WKURLSchemeTask.didReceive() | |
// unfortunately, the whole point of this exercise was to attempt to enable OPFS by setting up the CORP/COEP headers | |
// but, ultimately this doesn't work. Window.crossOriginIsolated is always false, and this is because secure contexts (check | |
// MDN docs) only work under certain conditions, which includes localhost on http/https schemes, but not on custom schemes | |
// such as the capacitor:// scheme the capacitorjs framework uses. | |
// | |
// to the best of my knowledge, under a custom scheme, it is impossible to get the WKWebView safari to behave as a secure | |
// context that enables OPFS / SharedArrayBuffer / Atomics | |
import UIKit | |
import Capacitor | |
import Foundation | |
import WebKit | |
@UIApplicationMain | |
class AppDelegate: UIResponder, UIApplicationDelegate { | |
var window: UIWindow? | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { | |
WebViewAssetHandler.swizzleWebViewStart() | |
return true | |
} | |
func applicationWillResignActive(_ application: UIApplication) { | |
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. | |
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. | |
} | |
func applicationDidEnterBackground(_ application: UIApplication) { | |
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. | |
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. | |
} | |
func applicationWillEnterForeground(_ application: UIApplication) { | |
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. | |
} | |
func applicationDidBecomeActive(_ application: UIApplication) { | |
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. | |
} | |
func applicationWillTerminate(_ application: UIApplication) { | |
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. | |
} | |
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { | |
// Called when the app was launched with a url. Feel free to add additional processing here, | |
// but if you want the App API to support tracking app url opens, make sure to keep this call | |
return ApplicationDelegateProxy.shared.application(app, open: url, options: options) | |
} | |
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { | |
// Called when the app was launched with an activity, including Universal Links. | |
// Feel free to add additional processing here, but if you want the App API to support | |
// tracking app url opens, make sure to keep this call | |
return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) | |
} | |
} | |
// Custom URL Scheme Task wrapper that modifies headers | |
class CustomURLSchemeTask: NSObject, WKURLSchemeTask { | |
private let wrappedTask: WKURLSchemeTask | |
init(wrappedTask: WKURLSchemeTask) { | |
self.wrappedTask = wrappedTask | |
super.init() | |
} | |
var request: URLRequest { | |
return wrappedTask.request | |
} | |
func didReceive(_ response: URLResponse) { | |
if let httpResponse = response as? HTTPURLResponse { | |
// Create modified headers | |
var newHeaders = httpResponse.allHeaderFields | |
// Always set CORS headers | |
// newHeaders["Cross-Origin-Opener-Policy"] = "same-origin" | |
// newHeaders["Cross-Origin-Embedder-Policy"] = "require-corp" | |
// newHeaders["Cross-Origin-Resource-Policy"] = "cross-origin" | |
newHeaders["Access-Control-Allow-Origin"] = "*" | |
newHeaders["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS" | |
newHeaders["Access-Control-Allow-Headers"] = "*" | |
// Get the file extension to determine content type | |
let url = httpResponse.url?.absoluteString.lowercased() ?? "" | |
// Set Cross-Origin headers based on resource type | |
if url.hasSuffix(".html") { | |
// Main document | |
newHeaders["Cross-Origin-Opener-Policy"] = "same-origin" | |
newHeaders["Cross-Origin-Embedder-Policy"] = "require-corp" | |
newHeaders["Cross-Origin-Resource-Policy"] = "same-origin" | |
} else if url.hasSuffix(".js") || url.hasSuffix(".mjs") { | |
// JavaScript files (including workers) | |
newHeaders["Cross-Origin-Resource-Policy"] = "same-origin" | |
// Ensure workers can be loaded | |
if url.contains("worker") { | |
newHeaders["Service-Worker-Allowed"] = "/" | |
} | |
} else { | |
// All other resources (images, styles, etc) | |
newHeaders["Cross-Origin-Resource-Policy"] = "cross-origin" | |
} | |
// Create new response with modified headers | |
let modifiedResponse = HTTPURLResponse( | |
url: httpResponse.url!, | |
statusCode: httpResponse.statusCode, | |
httpVersion: "HTTP/1.1", | |
headerFields: newHeaders as? [String: String] | |
)! | |
wrappedTask.didReceive(modifiedResponse) | |
} else { | |
wrappedTask.didReceive(response) | |
} | |
} | |
func didReceive(_ data: Data) { | |
wrappedTask.didReceive(data) | |
} | |
func didFinish() { | |
wrappedTask.didFinish() | |
} | |
func didFailWithError(_ error: Error) { | |
wrappedTask.didFailWithError(error) | |
} | |
} | |
// this properly calls original | |
extension WebViewAssetHandler { | |
private static var originalImplementation: IMP? | |
@objc static func swizzleWebViewStart() { | |
guard | |
let originalMethod = class_getInstanceMethod( | |
WebViewAssetHandler.self, | |
#selector(webView(_:start:)) | |
), | |
let swizzledMethod = class_getInstanceMethod( | |
WebViewAssetHandler.self, | |
#selector(custom_webView(_:start:)) | |
) | |
else { | |
return | |
} | |
// Store the original implementation | |
originalImplementation = method_getImplementation(originalMethod) | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
@objc func custom_webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { | |
NSLog("Swizzled webView start method called") | |
// Wrap the original task with our custom implementation | |
let customTask = CustomURLSchemeTask(wrappedTask: urlSchemeTask) | |
// Call the original implementation directly with our wrapped task | |
typealias OriginalMethod = @convention(c) (AnyObject, Selector, WKWebView, WKURLSchemeTask) -> Void | |
if let imp = WebViewAssetHandler.originalImplementation { | |
let castedImplementation = unsafeBitCast(imp, to: OriginalMethod.self) | |
castedImplementation(self, #selector(webView(_:start:)), webView, customTask) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment