1. 程式人生 > >JS和app互動

JS和app互動

智者精選,每天獲取勵志認知能量 www.5izhjx.com

一、    H5上程式碼的對接

要點:1.Object型別的傳參、2.同一個與app互動的JS方法、3.指令碼方法需內嵌到head裡面。

<html>

    <head>

        <meta http-equiv="Content-Type"    content="text/html;charset=UTF-8">

            <script type="text/javascript">

var share = JSON.stringify({"title":"Migi000",

"desc"

:"簡書",

"shareUrl":"http://www.jianshu.com/p/f896d73c670a"

                                           });

//IOS

function startFunction(share){

               window.android.startFunction(share)//android

            }

                </script>

<script>

     // testFunction()

    </script>

    <divonClick="testFunction()">dffddjjjjlj;ljlhhnljkhljhkjf</div>

     <divid="app-root"></div>

    <script type="text/javascript"src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

    <script>

      var _hmt = _hmt || [];(function() {var hm= document.createElement("script");hm.src ="//hm.baidu.com/hm.js?f84dde8c08e5b9c97f9c39e2fcb4d658";var s =document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();

    </script>

    <scripttype="text/javascript">

      function loadURL(url)

        {

            var iFrame;

            iFrame =document.createElement("iframe");

           iFrame.setAttribute("src", url);

            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;

        }

        function testFunction(share)

        {

           loadURL("testfunction://?title=分享的標題&content=分享的內容&url=連結地址&imagePath=圖片地址");

        }

        var share =JSON.stringify({"title": "分享的標題","content":"分享的內容","url":"http://www.jianshu.com/p/f896d73c670a"});

        testFunction(share)    </script>

    </head>

    <body>

     <br/>

    <h1>Objective-CJavaScript互動的那些事    </h1>

  <br/>

        <input  type="button" value="Share" onClick="startFunction(share)" >點選呼叫原生程式碼並傳遞引數</a>

</body>

</html>

二、    IOS上的程式碼對接

   注意點:#import<JavaScriptCore/JavaScriptCore.h> 需放在.h檔案中

#import"ViewController.h"

#import<JavaScriptCore/JavaScriptCore.h>

@interfaceViewController ()<UIWebViewDelegate>@property (nonatomic)UIWebView*webView;

@property(nonatomic)JSContext *jsContext;

@property(nonnull,strong) UIButton *btn;

@end

@implementationViewController

-(void)viewDidLoad{

    [super viewDidLoad];

    self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds];

    self.webView.delegate = self;

    [self.view addSubview:_webView];

    NSString *str = [[NSBundle mainBundle]pathForResource:@"migi" ofType:@"html"];

    [self.webView loadRequest:[NSURLRequestrequestWithURL:[NSURL fileURLWithPath:@"f"]]];

// 在上面新增一個按鈕,實現oc端控制h5實現彈alert方法框

    self.btn = [[UIButton alloc]initWithFrame:CGRectMake(100,400,100, 40)];

    self.btn.backgroundColor = [UIColorredColor];

    [self.btn addTarget:selfaction:@selector(showAlert) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:self.btn];

}

-(void)showAlert

{

//要將scriptalert()方法轉化為string型別

    NSString *[email protected]"alert('Hello Word')";

    [_jsContext evaluateScript:alertJs];

}

-(void)webViewDidFinishLoad:(UIWebView*)webView{

    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    _jsContext[@"startFunction"] =^(id obj){

////這裡通過block回撥從而獲得h5傳來的json資料

/*block中捕獲JSContexts

我們知道block會預設強引用它所捕獲的物件,如下程式碼所示,如果block中直接使用context也會造成迴圈引用,這使用我們最好採用[JSContext currentContext]來獲取當前的JSContext:

         */

        [JSContext currentContext];

        NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ];

        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:nil];

        NSLog(@"data   %@   ====== ShareUrl %@",obj,dict[@"shareUrl"]);

    };

//

    _jsContext.exceptionHandler = ^(JSContext*context, JSValue *exceptionValue) {

        context.exception = exceptionValue;

//比如把js中的方法名改掉,OC找不到相應方法,這裡就會列印異常資訊

        NSLog(@"異常資訊:%@", exceptionValue);

};

_jsContext[@"testFunction"] =^(id obj){

            //這裡通過block回撥從而獲得h5傳來的json資料

            [JSContext currentContext];

            NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ];

            NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

//            NSLog(@" data   %@  ======  ShareUrl%@",obj,dict[@"shareUrl"]);

            UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:dict[@"title"]message:dict[@"content"]delegate:nilcancelButtonTitle:@"cancel"otherButtonTitles:nil,nil];

            [alertView show];

        };

}

-(BOOL)webView:(UIWebView *)webViewshouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

    NSURL * url = [requestURL];

    //NSLog(@"scheme資訊:%@", [urlscheme]);

    if ([[url scheme] isEqualToString:@"testfunction"])

    {

        NSArray *params =[url.querycomponentsSeparatedByString:@"&"];

        NSMutableDictionary *tempDic = [NSMutableDictionarydictionary];

        for (NSString *paramStrin params) {

            NSArray *dicArray = [paramStrcomponentsSeparatedByString:@"="];

            if (dicArray.count >1) {

                NSString *decodeValue =[dicArray[1]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

                [tempDic setObject:decodeValueforKey:dicArray[0]];

            }

        }

        UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:tempDic[@"title"]message:tempDic[@"content"]delegate:selfcancelButtonTitle:@"收到"otherButtonTitles:nil];

        [alertView show];

        NSLog(@"tempDic:%@",tempDic);

        return NO;

    }

    return true;   //yes載入內容,否則不

}

三、    Android程式碼上的互動

mWebH5.addJavascriptInterface(new MyJavaScriptInterface(this), "android");
mWebH5.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //返回值是true的時候控制去WebView開啟,為false呼叫系統瀏覽器或第三方瀏覽器view.loadUrl(url);return true;
    }
});

@JavascriptInterface
 publicvoid startFunction(String json){
    if(SharedPrefs.getInstance().getUserAccessToken()==null){

    Gson gson=new Gson();
    finalShareLinkBean shareLinkBean =gson.fromJson(json, ShareLinkBean.class);
    LogUtils.i("test",json);
    mActivity.runOnUiThread(new Runnable() {
        @Override
        publicvoid run() {
            //跑相關邏輯
        }
    });

 }