### Bidirectional Communication Example Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md This example demonstrates how to register JavaScript handlers called by native code and how to call native handlers from JavaScript. It includes examples for displaying messages, getting scroll positions, logging, retrieving device info, and submitting form data. ```javascript setupWebViewJavascriptBridge(function(bridge) { // ===== Register JavaScript handlers (called by native) ===== bridge.registerHandler('displayMessage', function(message) { document.getElementById('message').innerHTML = message; }); bridge.registerHandler('getScrollPosition', function(data, responseCallback) { responseCallback({ x: window.scrollX, y: window.scrollY }); }); // ===== Call native handlers (invoke native code) ===== // Log when page loads bridge.callHandler('log', 'Page loaded'); // Get device info bridge.callHandler('getDeviceInfo', null, function(info) { console.log('Device: ' + info.deviceName); console.log('OS: ' + info.osVersion); }); // User interaction document.getElementById('submitBtn').addEventListener('click', function() { var formData = { name: document.getElementById('name').value, email: document.getElementById('email').value }; bridge.callHandler('submitForm', formData, function(response) { if (response.success) { alert('Form submitted'); } else { alert('Error: ' + response.error); } }); }); }); ``` -------------------------------- ### Setup WebViewJavascriptBridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/Tests/WebViewJavascriptBridgeTests/echo.html Initializes the WebViewJavascriptBridge and registers an 'echoHandler' that simply sends back the received data. This is a fundamental setup for communication. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` ```javascript setupWebViewJavascriptBridge(function(bridge) { bridge.registerHandler('echoHandler', function(data, responseCallback) { responseCallback(data) }) bridge.registerHandler('jsRcvResponseTest', function(data, responseCallback) { bridge.callHandler('objcEchoToJs', { foo:'bar' }, function(response) { if (response && response.foo == 'bar') { responseCallback("Response from JS") } else { responseCallback("Failed") } }) }) }) ``` -------------------------------- ### Setup WKWebView Bridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Instantiate a WKWebView and initialize the WebViewJavascriptBridge for it. This is the recommended approach for iOS. ```objc WKWebView* web = [[WKWebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:web]; ``` -------------------------------- ### Setup WebViewJavascriptBridge with WKWebView on iOS Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md This example demonstrates initializing WebViewJavascriptBridge with a WKWebView and loading a URL. It requires importing both WebViewJavascriptBridge and WebKit headers. ```objc #import "WebViewJavascriptBridge.h" #import @interface ViewController : UIViewController @property WebViewJavascriptBridge* bridge; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; // Create bridge self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; // Load URL [webView loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:@"http://example.com"]]]; } @end ``` -------------------------------- ### JavaScript API - Setup Pattern Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md The recommended pattern for initializing the WebViewJavascriptBridge in a web view. ```APIDOC ## Setup Pattern ### Description The recommended pattern for initializing the WebViewJavascriptBridge in a web view. This function ensures the bridge is ready before executing the provided callback. ### Function - **setupWebViewJavascriptBridge(callback)**: Initializes the bridge and calls the provided callback function with the bridge instance once ready. ### Usage ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` ``` -------------------------------- ### Register and Call Handler (Objective-C Example) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Demonstrates how to register a handler on the native side and call it from JavaScript. ```APIDOC ## Register and Call Handler (Objective-C Example) ### Description Shows how to register a handler in native code and invoke it from JavaScript. ### Native Registration ```objc [bridge registerHandler:@"alert" handler:^(id data, WVJBResponseCallback callback) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:data delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; }]; ``` ### JavaScript Call ```javascript bridge.callHandler('alert', 'Hello from JS'); ``` ``` -------------------------------- ### Old WebViewJavascriptBridge Setup (5.0.x) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md This is the legacy JavaScript setup code used in WebViewJavascriptBridge version 5.0.x. It should be updated for newer versions. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } // Old implementation... } ``` -------------------------------- ### Setup macOS WebView Bridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Instantiate a macOS WebView and initialize the WebViewJavascriptBridge for it. This is for macOS applications. ```objc WebView* web = [[WebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:web]; ``` -------------------------------- ### Handler with Response (Objective-C Example) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Illustrates registering a handler that provides a response back to the caller, using Objective-C. ```APIDOC ## Handler with Response (Objective-C Example) ### Description Demonstrates registering a handler that sends a response back to the caller, using Objective-C. ### Native Registration ```objc [bridge registerHandler:@"getTime" handler:^(id data, WVJBResponseCallback callback) { callback(@([[NSDate date] timeIntervalSince1970])); }]; ``` ### JavaScript Call ```javascript bridge.callHandler('getTime', null, function(timestamp) { console.log('Server time: ' + timestamp); }); ``` ``` -------------------------------- ### Create WebViewJavascriptBridge Instance (ObjC) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Instantiate a WebViewJavascriptBridge for a given web view. This is the initial setup step. ```objc [WebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### Setup WebView Javascript Bridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md This function sets up the bridge. It should be pasted into your HTML. It handles cases where the bridge is already loaded or needs to be initialized. ```javascript // Step 1: Define the setup function (paste into your HTML) function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } // Step 2: Use the bridge when it's ready setupWebViewJavascriptBridge(function(bridge) { // Register handlers bridge.registerHandler('displayAlert', function(message) { alert(message); }); bridge.registerHandler('getCurrentPageUrl', function(data, responseCallback) { responseCallback(document.location.toString()); }); // Call handlers bridge.callHandler('log', 'JavaScript loaded'); bridge.callHandler('getScreenHeight', null, function(height) { console.log('Screen height: ' + height); }); }); ``` -------------------------------- ### Install WebViewJavascriptBridge with CocoaPods Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Add this line to your Podfile to install the library using CocoaPods. Ensure you run 'pod install' afterwards. ```ruby pod 'WebViewJavascriptBridge', '~> 6.0' ``` -------------------------------- ### New WebViewJavascriptBridge Setup (6.0.x) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md This is the updated JavaScript setup code for WebViewJavascriptBridge version 6.0.x. It uses a callback queue and a new URL scheme for more robust initialization. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` -------------------------------- ### Setup WebViewJavascriptBridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/Example Apps/ExampleSwiftApp-iOS/echo.html This function sets up the bridge. It should be called once when the page loads. It handles cases where the bridge is already loaded or needs to be initialized. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptbridge) { return callback(WebViewJavascriptbridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` -------------------------------- ### Incoming Message Format Example Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example structure for messages received from native code in JavaScript, including handler name, payload, response ID, and response data. ```javascript { "handlerName": "displayAlert", "data": "Hello from native!", "callbackId": "objc_cb_1" } ``` -------------------------------- ### Install WebViewJavascriptBridge via CocoaPods Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Command to execute in the terminal to install the WebViewJavascriptBridge library after adding it to your Podfile. This command fetches and integrates the library into your project. ```bash pod install ``` -------------------------------- ### Setup WebViewJavascriptBridge in JavaScript Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md This JavaScript function is essential for initializing the bridge. Copy and paste it into your JavaScript code. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` -------------------------------- ### JavaScript Bridge Setup Pattern Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Provides the standard pattern for initializing the WebViewJavascriptBridge in a web view. This function ensures the bridge is ready before executing callbacks. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } ``` -------------------------------- ### Registering a Handler with WVJBHandler Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/types.md Example demonstrating how to define and register a WVJBHandler. The handler logs received data and sends a response back. ```Objective-C WVJBHandler myHandler = ^(id data, WVJBResponseCallback responseCallback) { NSLog(@"Handler called with: %@", data); if (responseCallback) { responseCallback(@"Response from handler"); } }; [bridge registerHandler:@"myHandler" handler:myHandler]; ``` -------------------------------- ### Outgoing Message Format Example Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example structure for messages sent from JavaScript to native code, including handler name, payload, and callback ID. ```javascript { "handlerName": "log", "data": "Message from JS", "callbackId": "cb_1_1234567890000" } ``` -------------------------------- ### WVJBMessage Examples Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/types.md Illustrates the structure of outgoing, incoming, and response messages using WVJBMessage type. These are standard NSDictionary objects. ```Objective-C // Outgoing message (native → JavaScript) WVJBMessage* message = @{ @"handlerName": @"displayAlert", @"data": @"Hello from Objective-C", @"callbackId": @"objc_cb_1" }; // Incoming message (JavaScript → native) WVJBMessage* incomingMessage = @{ @"handlerName": @"getScrollPosition", @"callbackId": @"cb_1_1234567890" }; // Response message (native → JavaScript) WVJBMessage* response = @{ @"responseId": @"cb_1_1234567890", @"responseData": @{@"x": @0, @"y": @100} }; ``` -------------------------------- ### JavaScript Bridge Setup and Usage Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/README.md This snippet demonstrates how to set up the WebViewJavascriptBridge in JavaScript and then register handlers or call native handlers. Ensure this script is executed within the web view's context. ```javascript function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'https://__bridge_loaded__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } setupWebViewJavascriptBridge(function(bridge) { // Register handlers bridge.registerHandler('handler', function(data, callback) { callback(response); }); // Call handlers bridge.callHandler('nativeHandler', data, function(response) { // Handle response }); }); ``` -------------------------------- ### Call Native Handler With Response Callback Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example of calling a native handler named 'getScreenHeight' and providing a callback function to receive the screen height as a response. ```javascript bridge.callHandler('getScreenHeight', null, function(height) { console.log('Screen height: ' + height); }); ``` -------------------------------- ### Register Simple Handler Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example of registering a JavaScript handler named 'log' that simply logs a message received from native code. This handler does not expect a response. ```javascript bridge.registerHandler('log', function(data) { console.log('Native said: ' + data); }); ``` -------------------------------- ### Bidirectional Call (Objective-C and JavaScript) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Provides an example of bidirectional communication where both native and JavaScript can register and call handlers. ```APIDOC ## Bidirectional Call (Objective-C and JavaScript) ### Description Illustrates bidirectional communication, allowing both native code and JavaScript to register and call handlers. ### Native Registers Handler, Calls JavaScript ```objc // Native registers handler [bridge registerHandler:@"onDataReceived" handler:^(id data, WVJBResponseCallback callback) { NSLog(@"Data: %@", data); }]; // Native calls JavaScript handler [bridge callHandler:@"fetchData" data:nil responseCallback:^(id response) { NSLog(@"Response: %@", response); }]; ``` ### JavaScript Registers Handler, Calls Native ```javascript // JavaScript registers handler bridge.registerHandler('fetchData', function(data, callback) { callback(data || [1, 2, 3]); }); // JavaScript calls native handler bridge.callHandler('onDataReceived', [4, 5, 6], function(response) { console.log('Processed'); }); ``` ``` -------------------------------- ### Bidirectional Call Example (Objective-C and JavaScript) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Illustrates bidirectional communication where native registers a handler and calls a JavaScript handler, and vice-versa. This enables complex interactions between the two environments. ```objective-c // Native registers and calls JavaScript [bridge registerHandler:@"onDataReceived" handler:^(id data, WVJBResponseCallback callback) { NSLog(@"Data: %@", data); }]; [bridge callHandler:@"fetchData" data:nil responseCallback:^(id response) { NSLog(@"Response: %@", response); }]; // JavaScript does the same bridge.registerHandler('fetchData', function(data, callback) { callback(data || [1, 2, 3]); }); bridge.callHandler('onDataReceived', [4, 5, 6], function(response) { console.log('Processed'); }); ``` -------------------------------- ### Setup WebViewJavascriptBridge with UIWebView on iOS Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md This snippet shows how to initialize WebViewJavascriptBridge with a UIWebView and load basic HTML content. Ensure you have imported the necessary headers. ```objc #import "WebViewJavascriptBridge.h" @interface ViewController : UIViewController @property WebViewJavascriptBridge* bridge; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; // Create bridge self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; // Load HTML NSString* html = @"Hello"; [webView loadHTMLString:html baseURL:nil]; } @end ``` -------------------------------- ### Objective-C Native Code Setup Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md This Objective-C code sets up the WebViewJavascriptBridge in a UIViewController. It registers native handlers for JavaScript calls and loads the chat interface HTML. Ensure WebViewJavascriptBridge.h is imported and the necessary UI elements are configured. ```objc #import "WebViewJavascriptBridge.h" @interface ChatViewController : UIViewController @property WebViewJavascriptBridge* bridge; @property UIWebView* webView; @end @implementation ChatViewController - (void)viewDidLoad { [super viewDidLoad]; // Setup WebView self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; self.webView.scrollView.scrollEnabled = NO; [self.view addSubview:self.webView]; // Create bridge self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView]; // Enable logging for debugging [WebViewJavascriptBridge enableLogging]; // Register native handlers [self registerNativeHandlers]; // Load HTML [self loadChatInterface]; } - (void)registerNativeHandlers { // Handler to send message [self.bridge registerHandler:@"sendMessage" handler:^(id data, WVJBResponseCallback responseCallback) { NSString* message = data; [self sendMessageToServer:message]; if (responseCallback) { responseCallback(@{@"status": @"sent"}); } }]; // Handler to get user info [self.bridge registerHandler:@"getUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) { NSDictionary* userInfo = @{ @"userId": @123, @"userName": @"John Doe", @"avatar": @"https://example.com/avatar.jpg" }; if (responseCallback) { responseCallback(userInfo); } }]; // Handler to close chat [self.bridge registerHandler:@"closeChat" handler:^(id data, WVJBResponseCallback responseCallback) { [self dismissViewControllerAnimated:YES completion:nil]; }]; } - (void)loadChatInterface { NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"chat" ofType:@"html"]; NSString* html = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil]; NSURL* baseURL = [NSURL fileURLWithPath:htmlPath]; [self.webView loadHTMLString:html baseURL:baseURL]; } - (void)sendMessageToServer:(NSString*)message { // Send message to backend... NSLog(@"Sending message: %@", message); // After message is sent, notify JavaScript [self.bridge callHandler:@"messageReceived" data:@{ @"message": message, @"timestamp": @([[NSDate date] timeIntervalSince1970]) }]; } @end ``` -------------------------------- ### Setup WebViewJavascriptBridge with WebView on macOS Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md This snippet illustrates how to set up WebViewJavascriptBridge with a WebView on macOS, including loading HTML content. Ensure you import the necessary headers for WebViewJavascriptBridge and WebKit. ```objc #import "WebViewJavascriptBridge.h" #import @interface ViewController : NSViewController @property WebViewJavascriptBridge* bridge; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; WebView* webView = [[WebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; // Create bridge self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; // Load HTML [[webView mainFrame] loadHTMLString:@"Hello" baseURL:nil]; } @end ``` -------------------------------- ### Register a Public Handler Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Example of registering a public handler named 'publicAction' for the bridge. It's recommended to only register necessary handlers and avoid exposing internal APIs. ```objectivec // Only register necessary handlers [self.bridge registerHandler:@"publicAction" handler:^(id data, WVJBResponseCallback callback) { // Public API }]; // Don't register internal APIs // [self.bridge registerHandler:@"internalSecret" ...]; ``` -------------------------------- ### Register Handler with Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example of registering a JavaScript handler named 'getCurrentPageUrl'. This handler retrieves the current page URL and sends it back to native code using the provided response callback. ```javascript bridge.registerHandler('getCurrentPageUrl', function(data, responseCallback) { responseCallback(document.location.toString()); }); ``` -------------------------------- ### Call Native Handler with Complex Data and Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example of calling a native handler 'updateProfile' with complex user data and a callback to handle the success or failure response from the native side. ```javascript bridge.callHandler('updateProfile', { firstName: 'John', lastName: 'Doe', email: 'john@example.com' }, function(response) { if (response.success) { console.log('Profile updated'); } }); ``` -------------------------------- ### Get JavaScript Command to Fetch Message Queue Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md Returns the JavaScript code snippet used to fetch the message queue from the WebViewJavascriptBridge object in the JavaScript environment. ```Objective-C - (NSString *)webViewJavascriptFetchQueyCommand ``` -------------------------------- ### Set Custom UIWebView Delegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md Configure a custom delegate for UIWebView to manage bridge setup and handle page load events. Ensure the delegate conforms to the UIWebViewDelegate protocol. ```Objective-C @interface ViewController : UIViewController @property WebViewJavascriptBridge* bridge; @end @implementation ViewController - (void)setupBridge { UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; [self.bridge setWebViewDelegate:self]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"Page loaded"); // Now the JavaScript is loaded, we can call handlers [self.bridge callHandler:@"setupPage"]; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSLog(@"Load error: %@", error); } @end ``` -------------------------------- ### Register Handler with Complex Data Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Example of registering a JavaScript handler named 'displayUser' that processes complex user data received from native code. It updates the DOM and sends a status response back. ```javascript bridge.registerHandler('displayUser', function(userData, responseCallback) { var name = userData.firstName + ' ' + userData.lastName; document.getElementById('username').innerHTML = name; responseCallback({ status: 'success', message: 'User displayed' }); }); ``` -------------------------------- ### Initialize macOS WebView Bridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Sets up a WebView and the WebViewJavascriptBridge for macOS applications supporting 10.9+. ```objc WebView* webView = [[WebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### Bridge Lifecycle Management Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Demonstrates the lifecycle of the WebViewJavascriptBridge, showing how it's retained by the WebView and how to manage your own references. ```objc // Bridge is retained by WebView as delegate WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; // Can safely release your reference bridge = nil; // WebView still holds a strong reference ``` -------------------------------- ### Configuration Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Methods for configuring the behavior and settings of the WebViewJavascriptBridge. ```APIDOC ## Configuration ### `setWebViewDelegate:` #### Description Sets a custom delegate for the web view. #### Method `setWebViewDelegate:` #### Class Both ### `disableJavscriptAlertBoxSafetyTimeout` #### Description Disables the safety timeout check for JavaScript alert boxes. #### Method `disableJavscriptAlertBoxSafetyTimeout` #### Class Both ### `+enableLogging` #### Description Enables debug logging for the bridge. #### Method `+enableLogging` #### Class Both ### `+setLogMaxLength:` #### Description Sets the maximum length for log messages, truncating longer messages. #### Method `+setLogMaxLength:` #### Class Both ### `reset` #### Description Resets the bridge state and reinjects the necessary JavaScript for WKWebViewJavascriptBridge. #### Method `reset` #### Class WKWebViewJavascriptBridge ``` -------------------------------- ### Call Native Handler with Query Data and Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Illustrates calling a native handler 'queryDatabase' with query parameters and processing the results in the response callback. ```javascript bridge.callHandler('queryDatabase', {table: 'users', limit: 10}, function(results) { results.forEach(function(user) { console.log(user.name); }); } ); ``` -------------------------------- ### Unsafe Handler Blocking Main Thread Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Illustrates an unsafe pattern where a handler blocks the main thread, for example, by performing a synchronous network request. This should be avoided. ```Objective-C // Don't block on network requests [self.bridge registerHandler:@"fetchData" handler:^(id data, WVJBResponseCallback callback) { // WRONG - blocks main thread! NSString* result = [self synchronousNetworkRequest]; callback(result); }]; ``` -------------------------------- ### Objective-C Bridge Implementation Files Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/overview.md This snippet lists the source files organized for the Objective-C bridge implementation, differentiating between UIWebView/WebView and WKWebView support. ```text WebViewJavascriptBridge/ ├── WebViewJavascriptBridge.h - UIWebView/WebView interface ├── WebViewJavascriptBridge.m - UIWebView/WebView implementation ├── WKWebViewJavascriptBridge.h - WKWebView interface ├── WKWebViewJavascriptBridge.m - WKWebView implementation ├── WebViewJavascriptBridgeBase.h - Shared protocol & types ├── WebViewJavascriptBridgeBase.m - Shared message handling ├── WebViewJavascriptBridge_JS.h - JavaScript bundle header └── WebViewJavascriptBridge_JS.m - JavaScript bundle implementation ``` -------------------------------- ### Factory Methods Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Methods for creating instances of WebViewJavascriptBridge and WKWebViewJavascriptBridge. ```APIDOC ## Factory Methods ### `+bridgeForWebView:` #### Description Creates a bridge instance for a given web view (UIWebView, WebView, or WKWebView). #### Method `+bridgeForWebView:` #### Returns `WebViewJavascriptBridge` ### `+bridge:` #### Description An alias for `+bridgeForWebView:`. #### Method `+bridge:` #### Returns `WebViewJavascriptBridge` ### `+[WKWebViewJavascriptBridge bridgeForWebView:]` #### Description Creates a bridge instance specifically for a WKWebView. #### Method `+[WKWebViewJavascriptBridge bridgeForWebView:]` #### Returns `WKWebViewJavascriptBridge` ``` -------------------------------- ### Initialize WKWebView Bridge (iOS) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Initializes a WKWebView and the WebViewJavascriptBridge. Supports iOS 7.1+. Demonstrates both automatic detection and direct instantiation of WKWebViewJavascriptBridge. ```objc WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; // Or directly: WKWebViewJavascriptBridge* bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### Get JavaScript Command to Check Bridge Loaded Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md Returns the JavaScript code snippet used to check if the WebViewJavascriptBridge object is present and loaded in the JavaScript environment. ```Objective-C - (NSString *)webViewJavascriptCheckCommand ``` -------------------------------- ### Call JavaScript Handler with Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md Invoke a JavaScript handler from Objective-C and receive a response back. Use this when you need to get data or confirmation from the JavaScript side. ```objc [self.bridge callHandler:@"getCurrentPageUrl" data:nil responseCallback:^(id responseData) { NSLog(@"Current URL: %@", responseData); }]; ``` -------------------------------- ### Handler with Response (Objective-C) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Shows how to register a handler in Objective-C that returns a response (a timestamp) to JavaScript. JavaScript then logs this timestamp. ```objective-c // Register [bridge registerHandler:@"getTime" handler:^(id data, WVJBResponseCallback callback) { callback(@([[NSDate date] timeIntervalSince1970])); }]; // Call from JavaScript bridge.callHandler('getTime', null, function(timestamp) { console.log('Server time: ' + timestamp); }); ``` -------------------------------- ### Fetch Outgoing Message Queue Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Internal method to retrieve the outgoing message queue. Called by native code to get pending messages and empties the queue. ```javascript function _fetchQueue() ``` -------------------------------- ### Register and Call Handler (Objective-C) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Demonstrates how to register a handler named 'alert' in Objective-C and then call it from JavaScript. The handler displays an alert with the provided data. ```objective-c // Register [bridge registerHandler:@"alert" handler:^(id data, WVJBResponseCallback callback) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:data delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; }]; // Call from JavaScript bridge.callHandler('alert', 'Hello from JS'); ``` -------------------------------- ### Instantiate WebViewJavascriptBridge Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Create an instance of WebViewJavascriptBridge, associating it with a specific web view (WKWebView, UIWebView, or WebView). ```objectivec self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### webViewJavascriptFetchQueyCommand Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md Returns the JavaScript command string used to fetch the message queue from the JavaScript side. ```APIDOC ## webViewJavascriptFetchQueyCommand ### Description Returns the specific JavaScript command string that can be evaluated in the WebView to fetch the current message queue from the JavaScript side of the bridge. ### Method NSString* ### Return Type NSString* - The JavaScript command: `"WebViewJavascriptBridge._fetchQueue();"`. ``` -------------------------------- ### + bridgeForWebView: Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/wkwebviewjavascriptbridge-class.md Factory method to create a bridge instance for a given WKWebView. It initializes the bridge and injects necessary JavaScript. ```APIDOC ## + bridgeForWebView: ### Description Factory method to create a bridge for the given WKWebView. ### Method + ### Endpoint bridgeForWebView: ### Parameters #### Path Parameters - **webView** (WKWebView*) - Required - A WKWebView instance to bridge ### Response #### Success Response (WKWebViewJavascriptBridge) - **WKWebViewJavascriptBridge** (instancetype) - A WKWebViewJavascriptBridge instance ### Details Automatically calls `reset()` to initialize the bridge state and inject the JavaScript bridge code. ### Example ```objc #import "WebViewJavascriptBridge.h" WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init]; WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; WKWebViewJavascriptBridge* bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView]; ``` ``` -------------------------------- ### Call Native Handler With Data, No Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Shows how to call a native handler named 'log' and pass a string message as data. No response callback is provided. ```javascript bridge.callHandler('log', 'Message from JavaScript'); ``` -------------------------------- ### Bridge Initialization and Handler Registration Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/Example Apps/ExampleSwiftApp-iOS/echo.html After the bridge is set up, this code registers handlers and makes calls to native code. It demonstrates greeting the native side, echoing data, and testing response handling. ```javascript setupWebViewJavascriptBridge(function(bridge) { bridge.callHandler('Greet', 'Hello world'); bridge.registerHandler('echoHandler', function(data, responseCallback) { responseCallback(data) }); bridge.registerHandler('jsRcvResponseTest', function(data, responseCallback) { bridge.callHandler('objcEchoToJs', { foo:'bar' }, function(response) { if (response && response.foo == 'bar') { responseCallback("Response from JS") } else { responseCallback("Failed") } }) }) }) ``` -------------------------------- ### Implement Objective-C Response Callbacks Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/types.md Create blocks to handle responses from JavaScript. Callbacks can log data, update UI elements on the main thread, or parse complex response data. ```objc // Simple callback WVJBResponseCallback simpleCallback = ^(id responseData) { NSLog(@"Response: %@", responseData); }; // Callback that updates UI WVJBResponseCallback uiCallback = ^(id responseData) { NSString* text = responseData; dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = text; }); }; // Callback with type conversion WVJBResponseCallback complexCallback = ^(id responseData) { if ([responseData isKindOfClass:[NSDictionary class]]) { NSDictionary* dict = responseData; NSString* status = dict[@"status"]; NSArray* items = dict[@"items"]; [self handleStatus:status items:items]; } }; ``` -------------------------------- ### Initialize UIWebView Bridge (iOS) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Instantiates a UIWebView and initializes the WebViewJavascriptBridge for use with it. This is for older iOS versions (5.0-12). ```objc UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### Startup Message Queue Property Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md A queue for messages that need to be sent before the JavaScript bridge is fully loaded. These messages are flushed once the bridge code is injected. ```objc @property (strong, nonatomic) NSMutableArray* startupMessageQueue ``` -------------------------------- ### setWebViewDelegate: Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridge-class.md Optionally sets a delegate to receive WebView lifecycle events. ```APIDOC ## - (void)setWebViewDelegate:(id)webViewDelegate ### Description Optionally set a delegate to receive WebView lifecycle events. ### Method Objective-C Instance Method ### Parameters #### Path Parameters - **webViewDelegate** (id) - Required - Delegate implementing UIWebViewDelegate (iOS) or WebViewDelegate (macOS) ### Details If provided, the delegate receives all WebView events (didFinishLoad, didFailLoad, shouldStartLoad, etc.) in addition to bridge message handling. ### Request Example ```objc @interface MyViewController : UIViewController @property WebViewJavascriptBridge* bridge; @end @implementation MyViewController - (void)setupBridge { self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; [self.bridge setWebViewDelegate:self]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"Page loaded"); } @end ``` ``` -------------------------------- ### Call Native Handler With Data and Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Demonstrates calling a native handler named 'getUserData' with a user ID and providing a callback to process the returned user data object. ```javascript bridge.callHandler('getUserData', {userId: 123}, function(userData) { console.log('User: ' + userData.name); }); ``` -------------------------------- ### webViewJavascriptCheckCommand Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md Returns the JavaScript command string used to check if the bridge is loaded in the WebView. ```APIDOC ## webViewJavascriptCheckCommand ### Description Returns the specific JavaScript command string that can be evaluated in the WebView to check if the `WebViewJavascriptBridge` object is available and loaded. ### Method NSString* ### Return Type NSString* - The JavaScript command: `"typeof WebViewJavascriptBridge == 'object';"`. ``` -------------------------------- ### Create Bridge for WebView Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridge-class.md Use this factory method to initialize a WebViewJavascriptBridge instance for a given WebView. Ensure the provided webView is of a supported type (UIWebView, WebView, or WKWebView). ```objc + (instancetype)bridgeForWebView:(id)webView ``` ```objc #import "WebViewJavascriptBridge.h" UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; WebViewJavascriptBridge* bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### injectJavascriptFile Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridgebase-class.md Injects the necessary JavaScript bridge code into the WebView. After injection, any queued startup messages are flushed. ```APIDOC ## injectJavascriptFile ### Description Injects the embedded JavaScript bridge code into the WebView context. After the code is injected, any messages that were queued during startup are flushed. ### Method void ### Parameters None ### Example (internal use): ```objc [baseInstance injectJavascriptFile]; ``` ``` -------------------------------- ### Create Bridge for UIWebView, WebView, or WKWebView Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Use this factory method to create a bridge instance that can work with UIWebView, WebView, or automatically detect and use WKWebView. ```Objective-C +bridgeForWebView: ``` -------------------------------- ### Create WKWebViewJavascriptBridge Instance Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/wkwebviewjavascriptbridge-class.md Use this factory method to create a bridge for a given WKWebView. It automatically initializes the bridge state and injects the necessary JavaScript. ```objc + (instancetype)bridgeForWebView:(WKWebView*)webView ``` ```objc #import "WebViewJavascriptBridge.h" WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init]; WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; WKWebViewJavascriptBridge* bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView]; ``` -------------------------------- ### ObjC API: bridgeForWebView Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Creates a javascript bridge for the given web view (WKWebVIew, UIWebView, or WebView). ```APIDOC ## bridgeForWebView ### Description Create a javascript bridge for the given web view. ### Method Objective-C ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```objc [WebViewJavascriptBridge bridgeForWebView:webView]; ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Import WebViewJavascriptBridge Header Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Import the necessary header file in your Objective-C code to use the WebViewJavascriptBridge library. ```objectivec #import "WebViewJavascriptBridge.h" ``` -------------------------------- ### Register Handler and Call Handler in ObjC Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Demonstrates registering a handler in Objective-C to receive messages from JavaScript and calling a JavaScript handler from Objective-C. ```objectivec [self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"ObjC Echo called with: %@", data); responseCallback(data); }]; [self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) { NSLog(@"ObjC received response: %@", responseData); }]; ``` -------------------------------- ### Call Native Handler Without Data or Response Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/javascript-api.md Demonstrates calling a native handler named 'showAlert' without passing any data or expecting a response from the native side. ```javascript bridge.callHandler('showAlert'); ``` -------------------------------- ### setWebViewDelegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/wkwebviewjavascriptbridge-class.md Optionally sets a delegate to receive WKWebView navigation events. The provided delegate must conform to the WKNavigationDelegate protocol. ```APIDOC ## setWebViewDelegate ### Description Optionally set a delegate to receive WKWebView navigation events. ### Method void ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **webViewDelegate** (id) - Required - Delegate implementing WKNavigationDelegate protocol ### Request Example ```objc [bridge setWebViewDelegate:self]; ``` ### Response None ``` -------------------------------- ### Native Callback Storage Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/message-protocol.md Illustrates the native Objective-C property used for storing response callbacks, keyed by callback ID. ```objc @property (strong, nonatomic) NSMutableDictionary* responseCallbacks; // Key: callbackId // Value: WVJBResponseCallback block ``` -------------------------------- ### ObjC API: setWebViewDelegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md Optionally sets a WKNavigationDelegate or UIWebViewDelegate to respond to web view lifecycle events. ```APIDOC ## setWebViewDelegate ### Description Optionally, set a `WKNavigationDelegate/UIWebViewDelegate` if you need to respond to the [web view's lifecycle events](https://developer.apple.com/reference/uikit/uiwebviewdelegate). ### Method Objective-C ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Register and Call Handlers in JavaScript Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/README.md After setting up the bridge, use this code to register JavaScript handlers and call Objective-C handlers. ```javascript setupWebViewJavascriptBridge(function(bridge) { /* Initialize your app here */ bridge.registerHandler('JS Echo', function(data, responseCallback) { console.log("JS Echo called with:", data) responseCallback(data) }) bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) { console.log("JS received response:", responseData) }) }) ``` -------------------------------- ### Batch Bridge Calls for Performance (Objective-C) Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md Optimize performance by batching multiple bridge calls into a single roundtrip. Instead of making sequential calls, use a single handler that returns all necessary data at once. ```objc // Avoid this - multiple roundtrips [self.bridge callHandler:@"getName" data:nil responseCallback:^(id name) { [self.bridge callHandler:@"getEmail" data:nil responseCallback:^(id email) { [self.bridge callHandler:@"getPhone" data:nil responseCallback:^(id phone) { // Use data... }]; }]; }]; ``` ```objc // Better - single roundtrip [self.bridge callHandler:@"getUserData" data:nil responseCallback:^(id userData) { NSString* name = userData[@"name"]; NSString* email = userData[@"email"]; NSString* phone = userData[@"phone"]; // Use data... }]; ``` -------------------------------- ### Safe UI Update Handler Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Demonstrates a safe pattern for registering a handler that updates UI elements. This handler is invoked on the main thread, making direct UI access safe. ```Objective-C [self.bridge registerHandler:@"updateUI" handler:^(id data, WVJBResponseCallback callback) { // Safe to update UI - called on main thread self.label.text = data; }]; ``` -------------------------------- ### Set WKWebView Delegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/usage-examples.md Implement a custom delegate for WKWebView to handle navigation events and bridge initialization. The delegate must conform to the WKNavigationDelegate protocol. ```Objective-C @interface ViewController : UIViewController @property WKWebViewJavascriptBridge* bridge; @end @implementation ViewController - (void)setupBridge { WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView]; [self.bridge setWebViewDelegate:self]; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"Navigation completed"); } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { NSLog(@"Navigation failed: %@", error); } @end ``` -------------------------------- ### Registering a Handler with Background Task Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Register a handler for a specific event, performing background I/O and returning to the main thread for the callback. This pattern ensures UI thread safety for network or file operations. ```objc [bridge registerHandler:@"download" handler:^(id data, WVJBResponseCallback callback) { // Main thread - safe for UI dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Background thread - for network/file I/O NSString* result = [self downloadData]; // Back to main for callback dispatch_async(dispatch_get_main_queue(), ^{ callback(result); }); }); }]; ``` -------------------------------- ### Set WKWebView Navigation Delegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/wkwebviewjavascriptbridge-class.md Optionally set a delegate to receive WKWebView navigation events. The delegate must implement the WKNavigationDelegate protocol. ```objc - (void)setWebViewDelegate:(id)webViewDelegate ``` ```objc @interface MyViewController : UIViewController @property WKWebViewJavascriptBridge* bridge; @end @implementation MyViewController - (void)setupBridge { WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView]; [self.bridge setWebViewDelegate:self]; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"Navigation completed"); } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { NSLog(@"Navigation failed: %@", error); } @end ``` -------------------------------- ### Setting WebView Delegate Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/webviewjavascriptbridge-class.md Optionally set a delegate to receive WebView lifecycle events. The delegate must conform to `UIWebViewDelegate` (iOS) or `WebViewDelegate` (macOS). ```Objective-C - (void)setWebViewDelegate:(id)webViewDelegate ``` ```Objective-C @interface MyViewController : UIViewController @property WebViewJavascriptBridge* bridge; @end @implementation MyViewController - (void)setupBridge { self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; [self.bridge setWebViewDelegate:self]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"Page loaded"); } @end ``` -------------------------------- ### Callback Invocation and Cleanup Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Shows how a callback block is invoked once and automatically cleaned up by the bridge after execution. ```objc [self.bridge callHandler:@"getData" data:nil responseCallback:^(id response) { // Block is automatically removed from responseCallbacks after this invocation NSLog(@"Response: %@", response); }]; ``` -------------------------------- ### Define Old and New Protocol Schemes Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/migration-notes.md Defines the old (v5.x) and new (v6.x) protocol schemes used by the bridge for backward compatibility. The bridge accepts both, but JavaScript should use the new scheme. ```objectivec #define kOldProtocolScheme @"wvjbscheme" // Old scheme (v5.x) #define kNewProtocolScheme @"https" // New scheme (v6.x) ``` -------------------------------- ### Create Bridge Specifically for WKWebView Source: https://github.com/marcuswestin/webviewjavascriptbridge/blob/master/_autodocs/api-index.md Use this factory method when you need to create a bridge instance exclusively for a WKWebView. ```Objective-C +[WKWebViewJavascriptBridge bridgeForWebView:] ```