淺談js和oc交互之UIWebView

因?yàn)轫?xiàng)目需求驅(qū)動(dòng)需求礁叔。折騰了幾天,由于之前沒有UIWebView與JS交互的經(jīng)歷,并且覺得這次寫完之后感覺以后原生的app和js交互會(huì)越來越多润匙,特此留下一點(diǎn)文字,方便日后回顧唉匾。
在這我用兩種方式小談UIWebView與JS交互孕讳,和一種WKWebView和js交互,相關(guān)的項(xiàng)目已上傳github巍膘,有些興趣的可以在后文中下載查看厂财。

首先說一下UIWebView與JS的交互

初始化UIWebView

UIWebView *web = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];

1.這是加載網(wǎng)絡(luò)連接的形式
   // NSURL *url = [NSURL URLWithString:@"https://baidu.com"];
   // NSURLRequest *request = [NSURLRequest //requestWithURL:url];
   // [web loadRequest:request];
2.加載本地html
//首先創(chuàng)建webView加載本地的html文件
    NSString *path = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:@"JSCallOC.html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request];

    [self.view  addSubview:web];
相關(guān)的代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
  
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
   
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
   
}
方式一

第一種方式是用JS發(fā)起一個(gè)響應(yīng)的URL請(qǐng)求,然后利用UIWebView的代理方法攔截這次請(qǐng)求峡懈,然后再做相應(yīng)的處理璃饱。
我寫了一個(gè)簡(jiǎn)單的HTML網(wǎng)頁和一個(gè)btn點(diǎn)擊事件用來與原生OC交互,HTML代碼如下:

<html>
    <!--描述網(wǎng)頁信息-->
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>小黃</title>
        <style>
            .btn{height:40px; width:60%; padding: 0px 30px; background-color: #0071E7; border: solid 1px #0071E7; border-radius:5px; font-size: 1.2em; color: white}
        </style>
        
        <script>
            
            function clear(){
                document.getElementById('mobile').innerHTML = ''
                document.getElementById('name').innerHTML = ''
                document.getElementById('msg').innerHTML = ''
            }
            
            //提供給OC調(diào)用JS的方法列表
            function alertMobile() {
                //alert('我是上面的小黃 手機(jī)號(hào)是:13300001111')
                document.getElementById('mobile').innerHTML = '我是上面的小黃 手機(jī)號(hào)是:13300001111'
            }

            function alertName(msg) {
                //alert('你好 ' + msg + ', 我也很高興見到你')
                document.getElementById('name').innerHTML = '你好 ' + msg + ', 我也很高興見到你'
            }

            function alertSendMsg(num,msg) {
                //alert('這是我的手機(jī)號(hào):' + num + ',' + msg + '!!')
                document.getElementById('msg').innerHTML = '這是我的手機(jī)號(hào):' + num + ',' + msg + '!!'
            }
        
            //JS調(diào)用oc響應(yīng)方法列表
            function btnClick1() {
                location.href = "rrcc://showMobile"
            }
        
            function btnClick2() {
                location.href = "rrcc://showName_?xiaohuang"
            }
        
            function btnClick3() {
                location.href = "rrcc://showSendNumber_msg_?13300001111&go climbing this weekend"
            }

        </script>
        
        
    </head>

    <!--網(wǎng)頁具體內(nèi)容-->
    <body>
        <br/><br/>

        <div>
            <label>小黃:13300001111</label>
        </div>
        <br/><br/>

        <div id="mobile"></div>
        <br/>
        <div>
            <button class="btn" type="button" onclick="btnClick1()">小紅的手機(jī)號(hào)</button>
        </div>
        <br/>
        <div id="name"></div>
        <br/>
        <div>
            <button class="btn" type="button" onclick="btnClick2()">打電話給小紅</button>
        </div>
        <br/>
        <div id="msg"></div>
        <br/>
        <div>
            <button class="btn" type="button" onclick="btnClick3()">發(fā)短信給小紅</button>
        </div>


    </body>
</html>

然后在項(xiàng)目的控制器中實(shí)現(xiàn)UIWebView的代理方法:

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC調(diào)用JS是基于協(xié)議攔截實(shí)現(xiàn)的 下面是相關(guān)操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1個(gè)或多個(gè)參數(shù)
            
            if ([subPath containsString:@"&"]) {//多個(gè)參數(shù)
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1個(gè)參數(shù)
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//沒有參數(shù)
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}

注意:1. 通過scheme進(jìn)行攔截到我們需要的url做出響應(yīng)的判斷肪康。
2.html中需要設(shè)置編碼荚恶,否則中文參數(shù)可能會(huì)出現(xiàn)編碼問題。
3.JS用直接用document.location的方式,這是一種早期的交互方式磷支,現(xiàn)在oc里面有一個(gè)javascriptcore的框架谒撼,后面在詳解。

早期的JS與原生交互的開源庫很多都是用得這種方式來實(shí)現(xiàn)的齐唆,例如:PhoneGap嗤栓、WebViewJavascriptBridge。關(guān)于這種方式調(diào)用OC方法箍邮,唐巧早期有篇文章有過介紹:關(guān)于UIWebView和PhoneGap的總結(jié)

方式二

在iOS 7之后茉帅,apple添加了一個(gè)新的庫JavaScriptCore,用來做JS交互锭弊,因此JS與原生OC交互也變得簡(jiǎn)單了許多堪澎。
首先導(dǎo)入JavaScriptCore庫, 然后在OC中獲取JS的上下文

  • JS調(diào)OC方法

首先導(dǎo)入頭文件

#import <JavaScriptCore/JavaScriptCore.h>

屬性中添加

@property (strong, nonatomic) JSContext *context;

JS調(diào)用OC方法一般在WebView的代理方法中實(shí)現(xiàn)

#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 以 html title 設(shè)置 導(dǎo)航欄 title
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    // 禁用 頁面元素選擇
    //[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    // 禁用 長按彈出ActionSheet
    //[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    // Undocumented access to UIWebView's JSContext
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    // 打印異常
    self.context.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"%@", exceptionValue);
    };
    
    // 以 JSExport 協(xié)議關(guān)聯(lián) native 的方法
    self.context[@"native"] = self;
    
    // 以 block 形式關(guān)聯(lián) JavaScript function
    self.context[@"log"] =
    ^(NSString *str)
    {
        NSLog(@"%@", str);
    };
    
    // 以 block 形式關(guān)聯(lián) JavaScript function
    self.context[@"alert"] =
    ^(NSString *str)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:str delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alert show];
    };
    
    __block typeof(self) weakSelf = self;
    self.context[@"addSubView"] =
    ^(NSString *viewname)
    {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 500, 300, 100)];
        view.backgroundColor = [UIColor redColor];
        UISwitch *sw = [[UISwitch alloc]init];
        [view addSubview:sw];
        [weakSelf.view addSubview:view];
    };
    //多參數(shù)
    self.context[@"mutiParams"] =
    ^(NSString *a,NSString *b,NSString *c)
    {
        NSLog(@"%@ %@ %@",a,b,c);
    };
    
}

以上只是相關(guān)主要代碼,詳細(xì)的請(qǐng)移步github查看


OC調(diào)JS

  • 初始化JSContext
  • 加載js文件
  • 在oc中創(chuàng)建JSValue代表JS中的對(duì)象,讓JS對(duì)象去執(zhí)行方法
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"oc call js";
    self.context = [[JSContext alloc] init];
    [self.context evaluateScript:[self loadJsFile:@"test"]];
    

}
- (NSString *)loadJsFile:(NSString*)fileName
{
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"js"];
    NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    return jsScript;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendToJS:(id)sender {
    NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
    JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];
    JSValue *result = [function callWithArguments:@[inputNumber]];
    self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
}

以上是關(guān)于UIWebView和js的交互味滞。

戳這里:本文的DEMO地址歡迎star樱蛤,下載。
戳這里:本文的DEMO地址-JavaScriptCore歡迎star剑鞍,下載昨凡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市蚁署,隨后出現(xiàn)的幾起案子便脊,更是在濱河造成了極大的恐慌,老刑警劉巖光戈,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件哪痰,死亡現(xiàn)場(chǎng)離奇詭異遂赠,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)晌杰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門跷睦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人肋演,你說我怎么就攤上這事抑诸。” “怎么了爹殊?”我有些...
    開封第一講書人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵哼鬓,是天一觀的道長。 經(jīng)常有香客問我异希,道長绒瘦,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任惰帽,我火速辦了婚禮憨降,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘该酗。我一直安慰自己,他們只是感情好呜魄,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著爵嗅,像睡著了一般娇澎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上睹晒,一...
    開封第一講書人閱讀 52,785評(píng)論 1 314
  • 那天趟庄,我揣著相機(jī)與錄音伪很,去河邊找鬼。 笑死锉试,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼絮短,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了丁频?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤席里,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后改基,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡秕狰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年躁染,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吞彤。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖饰恕,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情埋嵌,我是刑警寧澤,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布拌喉,位于F島的核電站,受9級(jí)特大地震影響尿背,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜田藐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望汽久。 院中可真熱鬧,春花似錦景醇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽散劫。三九已至,卻和暖如春获搏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背谋币。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來泰國打工症概, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蕾额,地道東北人彼城。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像募壕,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子舱馅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

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