OC與JS互相調用,OCJS調用

來源:互聯網
上載者:User

OC與JS互相調用,OCJS調用

最近項目中要用到html5來實現,涉及到OC調用JS,以及JS調用OC的方法,這裡把遇到的問題以及實現方法介紹一下。


////  ViewController.h//  OC_And_JS////  Created by 張傑 on 15/7/9.//  Copyright © 2015年 張傑. All rights reserved.//#import <UIKit/UIKit.h>@interface ViewController : UIViewController <UIWebViewDelegate>@property (weak, nonatomic) IBOutlet UIButton *oc_call_js_no_params;@property (weak, nonatomic) IBOutlet UIButton *oc_call_js_has_params;@property (weak, nonatomic) IBOutlet UIWebView *mWebView;@property (weak, nonatomic) IBOutlet UILabel *js_call_oc_show;- (IBAction)ocCallJsNoParams:(id)sender;- (IBAction)ocCallJsHasParams:(id)sender;@end


////  ViewController.m//  OC_And_JS////  Created by 張傑 on 15/7/9.//  Copyright © 2015年 張傑. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    _mWebView.delegate = self;        //開啟URL    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];    [self.mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];}- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString *urlstr = request.URL.absoluteString;    NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];    if (range.length!=0) {        _js_call_oc_show.text = [NSString stringWithFormat:@"請訪問地址:%@", urlstr];    }    return YES;}-(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{    NSLog(@"載入失敗");}-(void)webViewDidStartLoad:(nonnull UIWebView *)webView{    NSLog(@"開始載入");}-(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{    NSLog(@"開始結束");//    對於調用js的時候最好這個方法裡面或者之後}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (IBAction)ocCallJsNoParams:(id)sender {    NSString *js = [NSString stringWithFormat:@"ocCallJsNoParamsFunction();"];    [self.mWebView stringByEvaluatingJavaScriptFromString:js];}- (IBAction)ocCallJsHasParams:(id)sender {    NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];    [self.mWebView stringByEvaluatingJavaScriptFromString:js];}@end

function ocCallJsNoParamsFunction(){    alert("OC調用JS中的無參方法");    var e = document.getElementById("js_shouw_text");    e.options.add(new Option("OC調用JS中的無參方法", 2));}function ocCallJsHasParamsFunction(name, url){    alert(name+"的部落格地址為:"+url);    var e = document.getElementById("js_shouw_text");    e.options.add(new Option("OC調用JS中的有參方法", 2));}

<!DOCTYPE html><html lang="zh-CN"><head>    <meta charset="utf-8">    <title>OC與JS互相調用</title></head><body>    <div >        <select id="js_shouw_text">            <option>                展示OC調用JS無參數            </option>        </select>    </div>    <div>        <BR/>        <input type="button" value="JS調用OC方法" onclick="js_call_oc()"/>    </div>    <!--  這裡要清楚,雖然test.js跟index.html不同及目錄,實際安裝到程式裡面後,是在同級目錄的,所以這裡src不能加目錄,同樣css也是一樣的  -->    <script type="text/javascript" src="test.js" charset="UTF-8"></script>    <script type="text/javascript">        function js_call_oc()        {            var iFrame;            iFrame = document.createElement("iframe");            iFrame.setAttribute("src", "ios://jwzhangjie");            iFrame.setAttribute("style", "display:none;");            iFrame.setAttribute("height", "0px");            iFrame.setAttribute("width", "0px");            iFrame.setAttribute("frameborder", "0");            document.body.appendChild(iFrame);            // 發起請求後這個iFrame就沒用了,所以把它從dom上移除掉            iFrame.parentNode.removeChild(iFrame);            iFrame = null;        }            </script></body></html>

規避1:對於OC去調用JS內容最好在webViewDidFinishLoad方法裡或者之後

規避2:在html裡面引用js或者css的時候src不要帶有路徑,因為安裝後檔案都在同級目錄下面

規避3:OC調用JS的規範

 NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];    [self.mWebView stringByEvaluatingJavaScriptFromString:js];
規避4:JS調用OC,這裡通過html裡面發送一個請求,然後在ios中使用shouldStartLoadWithRequest攔截請求,根據請求url的不同進行處理。

 function js_call_oc()        {            var iFrame;            iFrame = document.createElement("iframe");            iFrame.setAttribute("src", "ios://jwzhangjie");            iFrame.setAttribute("style", "display:none;");            iFrame.setAttribute("height", "0px");            iFrame.setAttribute("width", "0px");            iFrame.setAttribute("frameborder", "0");            document.body.appendChild(iFrame);            // 發起請求後這個iFrame就沒用了,所以把它從dom上移除掉            iFrame.parentNode.removeChild(iFrame);            iFrame = null;        }

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString *urlstr = request.URL.absoluteString;    NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];    if (range.length!=0) {        _js_call_oc_show.text = [NSString stringWithFormat:@"請訪問地址:%@", urlstr];    }    return YES;}

源碼地址:

http://jwzhangjie.cn/forum.php?mod=viewthread&tid=3&page=1&extra=#pid3


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.