工程代碼如下
1、OC代碼
//
// ViewController.m
// OCJSTest
//
// Created by 馮闖 on 2022/1/25.
//
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)WKWebView *webview;
@property (nonatomic,assign)NSInteger count;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
self.webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 400)];
[self.view addSubview:self.webview];
NSURL *url = [[NSBundle mainBundle ] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *requst = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:requst];
self.webview.backgroundColor = [UIColor redColor];
self.webview.navigationDelegate = self;
self.count = 0;
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, [UIScreen mainScreen].bounds.size.height-100, [UIScreen mainScreen].bounds.size.width-100, 40)];
[btn setTitle:@"本地調(diào)用JS方法" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor = [UIColor orangeColor];
[self.view addSubview:btn];
}
- (void)btnAction{
//1. webview調(diào)用JS函數(shù), JS代碼可根據(jù)需要拼接好。
self.count += 1;
NSString *jsFunc = [NSString stringWithFormat:@"showalert(%ld)",(long)self.count];
[self.webview evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"evaluateJavaScript:\n result = %@ error = %@",result, error);
}];
}
#pragma mark -- 網(wǎng)頁加載完畢
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"加載完成");
}
//加載失敗
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"加載失敗1");
}
//加載失敗
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"加載失敗2");
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"啦啦啦");
}
@end
2、html 代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>這是一個網(wǎng)頁</title>
<style>
#content{
display: flex;
justify-content: space-between;
flex-direction: column;
background-color: blue;
height: 1000px;
width: 100%;
}
.topP{
line-height: 180px;
font-size: 80px;
background-color: green;
text-align: center;
margin-left: 50px;
margin-right: 50px;
}
.bottomButton{
font-size: 80px;
background-color: gold;
line-height: 180px;
margin-left: 50px;
margin-right: 50px;
margin-bottom: 50px;
}
</style>
</head>
<body>
<div id="content">
<p class="topP" > 這里是一個網(wǎng)頁 </p>
<button class="bottomButton" >點擊調(diào)用OC方法</button>
</div>
</body>
<script>
function showalert(message) {
var pp = document.getElementsByClassName('topP')[0]
pp.innerHTML = '本地改變第(' + message + ')次'
}
</script>
</html>
經(jīng)過仔細(xì)研究 OC 調(diào)用JS 還是很簡單的
OC調(diào)用JS函數(shù), JS代碼可根據(jù)需要拼接好。
如下圖:

596FCDC135E86D77D23D66E52D383099.png
OC 直接將JS代碼 封裝成字符串 然后通過
evaluateJavaScript 方法將字符串注入JS
然后JS 接受到OC傳過來的字符串 然后解析 最后調(diào)用
JS調(diào)用OC
OC代碼
//
// ViewController.m
// OCJSTest
//
// Created by 馮闖 on 2022/1/25.
//
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler>
@property (nonatomic,strong)WKWebView *webview;
@property (nonatomic,assign)NSInteger count;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
// 2. 網(wǎng)頁JS調(diào)原生:
// 1> 需要先設(shè)置Webview.config 的WKUserContentController
// 2> 注冊方法名 [userCC addScriptMessageHandler:self name:];
// 3> 遵守協(xié)議<WKScriptMessageHandler>,實現(xiàn)其方法.
// 4> 在控制器銷毀時,需要移除方法名注冊
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.selectionGranularity = WKSelectionGranularityCharacter;
configuration.userContentController = [WKUserContentController new];
[configuration.userContentController addScriptMessageHandler:self name:@"changeviewColor"];
self.webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 400) configuration:configuration];
[self.view addSubview:self.webview];
NSURL *url = [[NSBundle mainBundle ] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *requst = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:requst];
self.webview.backgroundColor = [UIColor redColor];
self.webview.navigationDelegate = self;
self.count = 0;
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, [UIScreen mainScreen].bounds.size.height-100, [UIScreen mainScreen].bounds.size.width-100, 40)];
[btn setTitle:@"本地調(diào)用JS方法" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor = [UIColor orangeColor];
[self.view addSubview:btn];
}
/*
這里是h5發(fā)送過來的消息,這里有多個控制器要加載,通過model屬性去判斷就可以了
@param userContentController userContentController description
@param message 根據(jù)messageName來判斷是什么類型的操作
*/
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@--%@",message.name,message.body);
if ([message.name isEqualToString:@"changeviewColor"]) {
[self changeviewColor];
}
}
- (void)btnAction{
// 1. webview調(diào)用JS函數(shù), JS代碼可根據(jù)需要拼接好。
self.count += 1;
NSString *jsFunc = [NSString stringWithFormat:@"showalert(%ld)",(long)self.count];
[self.webview evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"evaluateJavaScript:\n result = %@ error = %@",result, error);
}];
}
#pragma mark -- 網(wǎng)頁加載完畢
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"加載完成");
}
//加載失敗
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"加載失敗1");
}
//加載失敗
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"加載失敗2");
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"啦啦啦");
}
- (void)changeviewColor{
NSArray *colorArr = @[[UIColor yellowColor],[UIColor blueColor],[UIColor redColor],[UIColor cyanColor]];
int value = arc4random() % colorArr.count;
self.view.backgroundColor = colorArr[value];
}
@end
JS 代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>這是一個網(wǎng)頁</title>
<style>
#content{
display: flex;
justify-content: space-between;
flex-direction: column;
background-color: blue;
height: 1000px;
width: 100%;
}
.topP{
line-height: 180px;
font-size: 80px;
background-color: green;
text-align: center;
margin-left: 50px;
margin-right: 50px;
}
.bottomButton{
font-size: 80px;
background-color: gold;
line-height: 180px;
margin-left: 50px;
margin-right: 50px;
margin-bottom: 50px;
}
</style>
</head>
<body>
<div id="content">
<p class="topP" > 這里是一個網(wǎng)頁 </p>
<button class="bottomButton" onclick="btnAction()" >點擊調(diào)用OC方法</button>
</div>
</body>
<script>
function showalert(message) {
var pp = document.getElementsByClassName('topP')[0]
pp.innerHTML = '本地改變第(' + message + ')次'
}
function btnAction(){
window.webkit.messageHandlers.changeviewColor.postMessage('333');
}
</script>
</html>
其實 JS調(diào)用OC方法也很簡單 主要實現(xiàn)以下幾個步驟即可
- 網(wǎng)頁JS調(diào)原生:
1> 需要先設(shè)置Webview.config 的WKUserContentController
2> 注冊方法名 [userCC addScriptMessageHandler:self name:];
3> 遵守協(xié)議<WKScriptMessageHandler>,實現(xiàn)其方法.
4> 在控制器銷毀時,需要移除方法名注冊