APP中Web容器的核心实现
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
APP中Web容器的核心实现的更多相关文章
- 【转载】web开发中 web 容器的作用(如tomcat)
我们讲到servlet可以理解服务器端处理数据的java小程序,那么谁来负责管理servlet呢?这时候我们就要用到web容器.它帮助我们管理着servlet等,使我们只需要将重心专注于业务逻辑. 什 ...
- spring中WebApplicationContext、DispatcherServlet与web容器的ServletContext关系梳理
学习源码过程中,对各种context(上下文)表示很懵逼.特地留此一篇. 1.要了解各个上下文之间的关系.首先走一遍spring在web容器(tomcat)中的启动过程 a) ServletConte ...
- JavaEE中Web服务器、Web容器、Application服务器区别及联系
在JavaEE 开发Web中,我们经常会听到Web服务器(Web Server).Web容器(Web Container).应用服务器(Application Server),等容易混淆不好理解名词. ...
- Spring 在web 容器中的启动过程
1.对于一个web 应用,其部署在web 容器中,web 容器提供其一个全局的上下文环境,这个上下文就是 ServletContext ,其后面的spring IoC 容器提供宿主环境 2.在web. ...
- 集群: 如何在spring 任务中 获得集群中的一个web 容器的端口号?
系统是两台机器, 跑四个 web 容器, 每台机器两个容器 . nginx+memcached+quartz集群,web容器为 tomcat . web 应用中 用到spring 跑多个任务,任务只能 ...
- 用Chrome devTools 调试Android手机app中的web页面。
(1) 手机要满足Android系统为4.4或更高版本,低版本不支持这种方式.(2) 确保App已经开启了webview的debug调试模式,由Android工程师协助.(2) 用usb数据线连接好手 ...
- IOC容器在web容器中初始化——(一)两种配置方式
参考文章http://blog.csdn.net/liuganggao/article/details/44083817,http://blog.csdn.net/u013185616/article ...
- IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式
先来看一下ContextServletListener的代码 public class ContextLoaderListener extends ContextLoader implements S ...
- [转帖]JavaEE中Web服务器、Web容器、Application服务器区别及联系
JavaEE中Web服务器.Web容器.Application服务器区别及联系 https://www.cnblogs.com/vipyoumay/p/5853694.html 在JavaEE 开发W ...
- 如何在集群中获得处理本次请求的web容器的端口号?
系统四台机器,每台机器部署四个Tomcat Web容器.现需要根据端口号随机切换到映射的数据源,若一台机器一个Tomcat则用IP识别,可现在一台机器四个Tomcat,因此还需要获得Web容器的端口号 ...
随机推荐
- Java设计模式 —— 观察者模式
16 观察者模式 16.1 观察者模式概述 Observer Pattern: 定义对象之间的依赖关系(一对多),当一个对象的状态发生改变时,其关联的依赖对象均收到通知并自动更新. 观察者模式又称:发 ...
- vivo全球商城:电商交易平台设计
作者:vivo 官网商城开发团队 - Cheng Kun.Liu Wei 本文介绍了交易平台的设计理念和关键技术方案,以及实践过程中的思考与挑战. 点击查阅:<vivo 全球商城>系列文章 ...
- python字符串集合面试笔试题
python字符串面试笔试题 以下代码的输出是? s = 'foo' t = 'bar' print('barf' in 2 * (s + t)) A.True B.Fasle +运算符连接字符串,而 ...
- Amazon S3 对象存储Java API操作记录(Minio与S3 SDK两种实现)
缘起 今年(2023年) 2月的时候做了个适配Amazon S3对象存储接口的需求,由于4月份自学考试临近,一直在备考就拖着没总结记录下,开发联调过程中也出现过一些奇葩的问题,最近人刚从考试缓过来顺手 ...
- [Tensorflow]模型持久化的原理,将CKPT转为pb文件,使用pb模型预测
文章目录 [Tensorflow]模型持久化的原理,将CKPT转为pb文件,使用pb模型预测 一.模型持久化 1.持久化代码实现 convert_variables_to_constants固化模型结 ...
- 【leetcode】258. 各位相加
[leetcode]258. 各位相加 C++解法: class Solution { public: int addDigits(int num) { string s;//用来将num转换成字符串 ...
- 16.ReentrantLock全解读
大家好,我是王有志,欢迎和我聊技术,聊漂泊在外的生活.快来加入我们的Java提桶跑路群:共同富裕的Java人. 经历了AQS的前世和今生后,我们已经知道AQS是Java中提供同步状态原子管理,线程阻塞 ...
- 2023-04-04:使用 Golang 和 ffmpeg-go 库实现 demuxing_decoding.c,轻松掌握音视频分离解码技巧。
2023-04-04:使用 Golang 和 ffmpeg-go 库实现 demuxing_decoding.c,轻松掌握音视频分离解码技巧. 答案2023-04-05: 使用github/moonf ...
- 2022-06-24:golang选择题,以下golang代码输出什么?A:1;B:3;C:4;D:编译失败。 package main import ( “fmt“ ) func mai
2022-06-24:golang选择题,以下golang代码输出什么?A:1:B:3:C:4:D:编译失败. package main import ( "fmt" ) func ...
- 2021-09-24:给定一个正整数 n ,输出的第 n 项。前五项如下:1:1。2:11。3:21。4:1211。5:111221。第一项是数字 1 。描述前一项,这个数是 1 即 “ 一 个 1
2021-09-24:给定一个正整数 n ,输出的第 n 项.前五项如下:1:1.2:11.3:21.4:1211.5:111221.第一项是数字 1 .描述前一项,这个数是 1 即 " 一 ...