wkwebview iOS下JS與OC互相調(diào)用衍慎,可以實(shí)時(shí)傳遞數(shù)據(jù)


js調(diào)oc 并返回值給js

js調(diào)oc 并返回值給js.gif
1.js 點(diǎn)擊‘獲取定位’
<input type="button" value="獲取定位" onclick="locationClick()" />

function locationClick() {
                window.webkit.messageHandlers.Location.postMessage(null);
            }
2 .ios 內(nèi)注冊(cè) js “Location” 命令
 -- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
}
3. ios 得到 js 發(fā)送的“Location” 命令
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
//    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    NSLog(@"body:%@",message.body);
if ([message.name isEqualToString:@"Location"]) {
        [self getLocation];//ios 通過(guò)調(diào)用 js方法的方式 悄泥,要把數(shù)據(jù)傳給js,
    } 
}

4. js 接收ios 結(jié)果回調(diào)

function setLocation(location) {
                asyncAlert(location);
                document.getElementById("returnValue").value = location;
            }
5. ios 將結(jié)果傳給 js
- (void)getLocation
{
    // 獲取位置信息
    
    // 將結(jié)果返回給js
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"廣東省深圳市南山區(qū)學(xué)府路XXXX號(hào)"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
   
}

js ------- index.html

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
            <script language="javascript">
            var ctuapp_share_img="www.baidu.com";
            function scanClick() {
                window.webkit.messageHandlers.ScanAction.postMessage(null);
            }
                
            function shareClick() {
                window.webkit.messageHandlers.Share.postMessage({title:'測(cè)試分享的標(biāo)題',content:'測(cè)試分享的內(nèi)容',url:'http://m.rblcmall.com/share/openShare.htm?share_uuid=shdfxdfdsfsdfs&share_url=http://m.rblcmall.com/store_index_32787.htm&imagePath=http://c.hiphotos.baidu.com/image/pic/item/f3d3572c11dfa9ec78e256df60d0f703908fc12e.jpg'});
            }
            
            function locationClick() {
                window.webkit.messageHandlers.Location.postMessage(null);
            }
            
            function setLocation(location) {
                asyncAlert(location);
                document.getElementById("returnValue").value = location;
            }
            
            function getQRCode(result) {
                asyncAlert(result);
                document.getElementById("returnValue").value = result;
            }
            
            function colorClick() {
                window.webkit.messageHandlers.Color.postMessage([67,205,128,0.5]);
            }
            
            function payClick() {
                window.webkit.messageHandlers.Pay.postMessage({order_no:'201511120981234',channel:'wx',amount:1,subject:'粉色外套'});
            }
            
            function payResult(str) {
                asyncAlert(str);
                document.getElementById("returnValue").value = str;
            }
            
            function shareResult(channel_id,share_channel,share_url) {
                var content = channel_id+","+share_channel+","+share_url;
                asyncAlert(content);
                document.getElementById("returnValue").value = content;
            }

            function shake() {
                window.webkit.messageHandlers.Shake.postMessage(null);
            }
            
            function goBack() {
                window.webkit.messageHandlers.GoBack.postMessage(null);
            }
            
            function playSound() {
                window.webkit.messageHandlers.PlaySound.postMessage('shake_sound_male.wav');
            }
            
            function asyncAlert(content) {
                setTimeout(function(){
                           alert(content);
                           },1);
            }
            
            
            </script>
            </head>
    
    <body>
        <h1>這是按鈕調(diào)用</h1>
        <input type="button" value="掃一掃" onclick="scanClick()" />
        <input type="button" value="獲取定位" onclick="locationClick()" />
        <input type="button" value="修改背景色" onclick="colorClick()" />
        <input type="button" value="分享" onclick="shareClick()" />
        <input type="button" value="支付" onclick="payClick()" />
        <input type="button" value="搖一搖" onclick="shake()" />
        <input type="button" value="返回" onclick="goBack()" />
        <input type="button" value="播放聲音" onclick="playSound()" />
        
        <h1>這是文件上傳</h1>

        <input type="file" />
        
        <h1>這是回調(diào)結(jié)果展示區(qū)</h1>
        <textarea id ="returnValue" type="value" rows="5" cols="40">
        
        </textarea>
        
        <h4>豎直方向的表頭:</h4>
        <table border="1" style="width:90%;height:600px">
            <tr>
                <th>姓名</th>
                <td>Bill Gates</td>
            </tr>
            <tr>
                <th>電話</th>
                <td>555 77 854</td>
            </tr>
            <tr>
                <th>傳真</th>
                <td>555 77 855</td>
            </tr>
        </table>
        
        
    </body>
</html>

ios --- WKWebViewController

//
//  WKWebViewController.m
//  JS_OC_URL
//
//  Created by Harvey on 16/8/4.
//  Copyright ? 2016年 Haley. All rights reserved.
//

#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

#import "WKWebViewController.h"
#import "HLAudioPlayer.h"

@interface WKWebViewController ()<WKUIDelegate,WKScriptMessageHandler>

@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;

@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"MessageHandler";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(rightClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self initWKWebView];
    
    [self initProgressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // addScriptMessageHandler 很容易導(dǎo)致循環(huán)引用
    // 控制器 強(qiáng)引用了WKWebView,WKWebView copy(強(qiáng)引用了)configuration, configuration copy (強(qiáng)引用了)userContentController
    // userContentController 強(qiáng)引用了 self (控制器)
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ScanAction"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Pay"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"PlaySound"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 因此這里要記得移除handlers
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ScanAction"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Pay"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Shake"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"PlaySound"];
}

- (void)initWKWebView
{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    
//    NSString *urlStr = @"http://www.baidu.com";
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//    [self.webView loadRequest:request];
    
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
}

- (void)initProgressView
{
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
}

- (void)rightClick
{
    [self goBack];
}

- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - private method
- (void)getLocation
{
    // 獲取位置信息
    
    // 將結(jié)果返回給js
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"廣東省深圳市南山區(qū)學(xué)府路XXXX號(hào)"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
   
}

- (void)shareWithParams:(NSDictionary *)tempDic
{
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSString *title = [tempDic objectForKey:@"title"];
    NSString *content = [tempDic objectForKey:@"content"];
    NSString *url = [tempDic objectForKey:@"url"];
    // 在這里執(zhí)行分享的操作
    
    // 將分享結(jié)果返回給js
    NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

- (void)changeBGColor:(NSArray *)params
{
    if (![params isKindOfClass:[NSArray class]]) {
        return;
    }
    
    if (params.count < 4) {
        return;
    }
    
    CGFloat r = [params[0] floatValue];
    CGFloat g = [params[1] floatValue];
    CGFloat b = [params[2] floatValue];
    CGFloat a = [params[3] floatValue];
    
    self.view.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
}

- (void)payWithParams:(NSDictionary *)tempDic
{
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSString *orderNo = [tempDic objectForKey:@"order_no"];
    long long amount = [[tempDic objectForKey:@"amount"] longLongValue];
    NSString *subject = [tempDic objectForKey:@"subject"];
    NSString *channel = [tempDic objectForKey:@"channel"];
    NSLog(@"%@---%lld---%@---%@",orderNo,amount,subject,channel);
    
    // 支付操作
    
    // 將支付結(jié)果返回給js
    NSString *jsStr = [NSString stringWithFormat:@"payResult('%@')",@"支付成功"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

- (void)shakeAction
{
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
    [HLAudioPlayer playMusic:@"shake_sound_male.wav"];
}

- (void)goBack
{
    [self.webView goBack];
}

- (void)playSound:(NSString *)fileName
{
    if (![fileName isKindOfClass:[NSString class]]) {
        return;
    }
    
    [HLAudioPlayer playMusic:fileName];
}

#pragma mark - KVO
// 計(jì)算wkWebView進(jìn)度條
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
//    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    NSLog(@"body:%@",message.body);
if ([message.name isEqualToString:@"Location"]) {
        [self getLocation];
    }
}

@end

注:ios 注入js 方法 ↓

 NSString *postParamJs = [NSString stringWithFormat:@" function getWKWebViewPostParamsInIOS(){return %@ } ",jsonParamStr];
    
    WKUserScript *script = [[WKUserScript alloc] initWithSource:postParamJs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:true];
    [self.wkWebView.configuration.userContentController addUserScript:script];

demo 地址 https://github.com/lizhi0123/JS_OC_MessageHandler

原貼地址:http://www.reibang.com/p/433e59c5a9eb
原貼demo地址 https://github.com/Haley-Wong/JS_OC/tree/master/JS_OC_MessageHandler

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末纱兑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子化借,更是在濱河造成了極大的恐慌潜慎,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蓖康,死亡現(xiàn)場(chǎng)離奇詭異铐炫,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)蒜焊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)倒信,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人泳梆,你說(shuō)我怎么就攤上這事鳖悠。” “怎么了优妙?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵乘综,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我套硼,道長(zhǎng)卡辰,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任熟菲,我火速辦了婚禮看政,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘抄罕。我一直安慰自己允蚣,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布呆贿。 她就那樣靜靜地躺著嚷兔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪做入。 梳的紋絲不亂的頭發(fā)上冒晰,一...
    開(kāi)封第一講書(shū)人閱讀 49,007評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音竟块,去河邊找鬼壶运。 笑死,一個(gè)胖子當(dāng)著我的面吹牛浪秘,可吹牛的內(nèi)容都是我干的蒋情。 我是一名探鬼主播埠况,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼棵癣!你這毒婦竟也來(lái)了辕翰?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤狈谊,失蹤者是張志新(化名)和其女友劉穎喜命,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體河劝,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡壁榕,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了丧裁。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片护桦。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡含衔,死狀恐怖煎娇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贪染,我是刑警寧澤缓呛,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站杭隙,受9級(jí)特大地震影響哟绊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜痰憎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一票髓、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧铣耘,春花似錦洽沟、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至炉媒,卻和暖如春踪区,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背吊骤。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工缎岗, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人白粉。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓传泊,卻偏偏與公主長(zhǎng)得像茅郎,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子或渤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容