NSString *jsStr = @"執行的JS程式碼"; [webView stringByEvaluatingJavaScriptFromString:jsStr];
[webView evaluateJavaScript:@"執行的JS程式碼" completionHandler:^(id _Nullable response, NSError * _Nullable error) {}];
#import <Foundation/Foundation.h> #import <JavaScriptCore/JavaScriptCore.h> @protocol JSNativeProtocol <JSExport> - (NSDictionary *)QRCodeScan:(NSDictionary *)param; @end @interface AppJSModel : NSObject <JSNativeProtocol> @end #import "AppJSModel.h" @implementation AppJSModel - (NSDictionary *)QRCodeScan:(NSDictionary *)param { NSLog(@"param: %@",param); return @{@"name":@"jack"}; } @end
import './App.css'; import { useState } from 'react'; function OriginalWebViewApp() { const[name, setName] = useState('') // 0.公共 //原生髮訊息給JS,JS的回撥 window.qrResult = (res)=>{ setName(res) return '-------: '+res } // scheme攔截 const localPostion = () => { window.location.href = 'position://localPosition?name=jack&age=20' } // 2.UIWebView的互動 //js發訊息給原生 const qrActionOnAppModel = () => { const res = window.appModel.QRCodeScan({"name":"value"}) alert(res.name) } const showAlert = () => { window.showAlert() } return ( <div className="App"> <div>------------------公共------------------</div> <div><a href='position://abc?name=jack' style={{color:'white'}}>scheme攔截1:定位</a></div> <button onClick={localPostion}>scheme攔截2</button> <div> 原生執行程式碼的結果:{name} </div> <div>------------------UIWebView------------------</div> <button onClick={qrActionOnAppModel}>點選掃碼</button> <button onClick={showAlert}>彈窗</button> </div> ) } export default OriginalWebViewApp
- (void)webViewDidFinishLoad:(UIWebView *)webView { JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; AppJSModel *jsModel = [AppJSModel new]; jsContext[@"appModel"] = jsModel; jsContext[@"showAlert"] = ^(){ dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"請輸入支付資訊" message:@"" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:defaultAction]; UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"Cancle" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:cancleAction]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder=@"請輸入使用者名稱"; }]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder=@"請輸入支付密碼"; textField.secureTextEntry=YES; }]; [self presentViewController:alert animated:YES completion:nil]; }); }; }
Scheme攔截
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ([request.URL.scheme isEqualToString:@"position"]) { //自定義處理定位scheme JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString *jsCode = @"qrResult('杭州,之江')"; [jsContext evaluateScript:jsCode]; return NO; } return YES; }
import './App.css'; import { useState } from 'react'; function OriginalWebViewApp() { const[name, setName] = useState('') // 0.公共 //原生髮訊息給JS,JS的回撥 window.qrResult = (res)=>{ setName(res) return '-------: '+res } // scheme攔截 const localPostion = () => { window.location.href = 'position://localPosition?name=jack&age=20' } // 1.WKWebView的互動 //js發訊息給原生 const qrAction = () => { window.webkit.messageHandlers.QRCodeScan.postMessage({"name":"value"}) } return ( <div className="App"> <div>------------------公共------------------</div> <div><a href='position://abc?name=jack' style={{color:'white'}}>scheme攔截1:定位</a></div> <button onClick={localPostion}>scheme攔截2</button> <div> 原生執行程式碼的結果:{name} </div> <div>------------------WKWebView------------------</div> <button onClick={qrAction}>點選掃描</button> </div> ) } export default OriginalWebViewApp
override func viewDidLoad() { super.viewDidLoad() // WKWebViewConfiguration: 用於設定WKWebView的屬性和行為, 常見的操作有 let webViewConfiguration = WKWebViewConfiguration() //1.設定WKUserContentController,管理WKUserScript(cookie指令碼)和WKScriptMessageHandler原生與JS的互動 let userContentController = WKUserContentController() webViewConfiguration.userContentController = userContentController //新增WKScriptMessageHandler指令碼處理 userContentController.add(self, name: "QRCodeScan") //新增WKUserScript,injectionTime注入時機為atDocumentStart頁面載入時在,forMainFrameOnly不只在主框架中注入,所有的框架都注入。 let cookieScript = WKUserScript(source: "document.cookie = 'cookieName=cookieValue; domain=example.com; path=/';", injectionTime: .atDocumentStart, forMainFrameOnly: false) userContentController.addUserScript(cookieScript) //2.自定義處理網路,處理Scheme為position的定位網路操作 webViewConfiguration.setURLSchemeHandler(self, forURLScheme: "position") //3.偏好設定WKPreferences,設定網頁縮放,字型 let preferences = WKPreferences() preferences.minimumFontSize = 10 if #available(iOS 14, *) { let webpagePreferences = WKWebpagePreferences() webpagePreferences.allowsContentJavaScript = true webViewConfiguration.defaultWebpagePreferences = webpagePreferences } else { preferences.javaScriptEnabled = true } preferences.javaScriptCanOpenWindowsAutomatically = true webViewConfiguration.preferences = preferences //4.多媒體設定,設定視訊自動播放,畫中畫,逐步渲染 webViewConfiguration.allowsInlineMediaPlayback = true webViewConfiguration.allowsPictureInPictureMediaPlayback = true webViewConfiguration.allowsAirPlayForMediaPlayback = true webViewConfiguration.suppressesIncrementalRendering = true //5.cookie設定 //WKWebView中HTTPCookieStorage.shared單例預設管理著所有的cookie,一般無需我們做額外的操作,如果想單獨新增一個cookie,可以把建立的cookie放置到HTTPCookieStorage.shared中即可。 //建立cookie物件 let properties = [ HTTPCookiePropertyKey.name: "cookieName", HTTPCookiePropertyKey.value: "cookieValue", HTTPCookiePropertyKey.domain: "example.com", HTTPCookiePropertyKey.path: "/", HTTPCookiePropertyKey.expires: NSDate(timeIntervalSinceNow: 31556926) ] as [HTTPCookiePropertyKey : Any] let cookie = HTTPCookie(properties: properties)! // 將cookie新增到cookie storage中 HTTPCookieStorage.shared.setCookie(cookie) webView = WKWebView(frame: .zero, configuration: webViewConfiguration) webView.uiDelegate = self webView.navigationDelegate = self self.view.addSubview(webView) loadURL(urlString: "http://localhost:3000/") }
//WKScriptMessageHandler extension H5WKWebViewContainerController { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "QRCodeScan" { print(message) //JS回撥,原生處理完後,通知JS結果 //原生給js的回撥事件 會通過」原生呼叫js「方式放入到js執行環境的messageQueue中 let script = "qrResult('jack')" message.webView?.evaluateJavaScript(script,completionHandler: { res, _ in print(res) }) } } }
// 自定義處理網路請求Scheme // WKURLSchemeHandler 的 Delegate extension H5WKWebViewContainerController { func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { if urlSchemeTask.request.url?.scheme == "position" { //自定義處理定位scheme webView.evaluateJavaScript("qrResult('杭州,之江')") } print(webView) } func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { print(webView) } }
- (void)registerHandler:(NSString *)handlerName handler:(WVJBHandler)handler;
- (void)callHandler:(NSString *)handlerName data:(id)data
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame]; wkWebView.navigationDelegate = self; [self.view addSubview:wkWebView]; [WebViewJavascriptBridge enableLogging]; self.bridge = [WebViewJavascriptBridge bridgeForWebView:wkWebView]; // 在JS上下文中註冊callOC方法 [self.bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"收到了JS的呼叫"); responseCallback(@"Object-C Received"); }]; // iOS呼叫JS [self.bridge callHandler:@"testJavascriptHandler" data:@{@"state":@"before ready"}]; NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3000/"]]; [wkWebView loadRequest:req]; }
import React from "react" function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(window.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) } function WebViewJavaScriptBridgeApp() { return ( <div className="WebViewJavaScriptBridgeApp"> <div>---------WebViewJavaScript---------</div> <div id="buttons"></div> <div id="log"></div> <div> { setupWebViewJavascriptBridge(function(bridge) { var uniqueId = 1 function log(message, data) { var log = document.getElementById('log') var el = document.createElement('div') el.className = 'logLine' el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data) if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) } } bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) { log('ObjC called testJavascriptHandler with', data) var responseData = { 'Javascript Says':'Right back atcha!' } log('JS responding with', responseData) if (responseCallback !== undefined) { responseCallback(responseData) } }) document.body.appendChild(document.createElement('br')) if (document.getElementById('buttons') === null) { setTimeout(function() { document.getElementById('buttons').innerHTML = "" var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button')) callbackButton.innerHTML = 'js 呼叫 OC方法' callbackButton.onclick = function(e) { e.preventDefault() log('JS calling handler "testObjcCallback"') bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) { log('JS got response', response) }) } },0) } }) } </div> </div> ) } export default WebViewJavaScriptBridgeApp
window.WebViewJavascriptBridge = { // 儲存js註冊的處理常式:messageHandlers[handlerName] = handler; registerHandler: registerHandler, //JS呼叫OC方法 callHandler: callHandler, disableJavscriptAlertBoxSafetyTimeout: disableJavscriptAlertBoxSafetyTimeout, //JS呼叫OC的訊息佇列 _fetchQueue: _fetchQueue, //JS處理OC過來的方法呼叫。 _handleMessageFromObjC: _handleMessageFromObjC };
function _fetchQueue() { var messageQueueString = JSON.stringify(sendMessageQueue); sendMessageQueue = []; return messageQueueString; }
NSMutableDictionary* message = [NSMutableDictionary dictionary]; message[@"data"] = data; NSString* callbackId = [NSString stringWithFormat:@"objc_cb_%ld", ++_uniqueId]; self.responseCallbacks[callbackId] = [responseCallback copy]; message[@"callbackId"] = callbackId; message[@"handlerName"] = handlerName;
@interface WebViewJavascriptBridgeBase : NSObject // 在成員變數中定義欄位responseCallbacks @property (strong, nonatomic) NSMutableDictionary* responseCallbacks; @end //傳送訊息時,儲存回撥ID:回撥函數鍵值對。 - (void)sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName { NSMutableDictionary* message = [NSMutableDictionary dictionary]; if (data) { message[@"data"] = data; } if (responseCallback) { NSString* callbackId = [NSString stringWithFormat:@"objc_cb_%ld", ++_uniqueId]; self.responseCallbacks[callbackId] = [responseCallback copy]; message[@"callbackId"] = callbackId; } if (handlerName) { message[@"handlerName"] = handlerName; } [self _queueMessage:message]; }
// 在JS全域性上下文中定義物件responseCallbacks var responseCallbacks = {}; function _doSend(message, responseCallback) { if (responseCallback) { var callbackId = 'cb_'+(uniqueId++)+'_'+new Date().getTime(); //儲存回撥id:回撥方法,鍵值對 responseCallbacks[callbackId] = responseCallback; message['callbackId'] = callbackId; } sendMessageQueue.push(message); messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; }
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { if (webView != _webView) { return; } NSURL *url = navigationAction.request.URL; __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if ([_base isWebViewJavascriptBridgeURL:url]) { if ([_base isBridgeLoadedURL:url]) { //iOS原生進行js互動環境注入 [_base injectJavascriptFile]; } else if ([_base isQueueMessageURL:url]) { [self WKFlushMessageQueue]; } else { [_base logUnkownMessage:url]; } decisionHandler(WKNavigationActionPolicyCancel); return; } if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)]) { [_webViewDelegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler]; } else { decisionHandler(WKNavigationActionPolicyAllow); } }
另外
cd h5-demo npm install npm start