IOS 与 Android WebView 中 JS 调用原生代码

1.当使用WebView 加载Web页面时.有时候需要用到 点击Web页面 跳转到原生Activity 或者 ViewController.混合开发的时候,就需要 通过JS 调用 原生代码.Java 或者 O-C 调用js 代码.

 两种方式(1)JS 与原生代码绑定 (2)URL  拦截


IOS使用

步骤.(1)首先创建 HTML页面 

   index.html   并将HTML文件放到程序.

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
            <title>Hello PhoneGap</title>
            <script type="text/javascript" charset="utf-8">
                function sendCommand(cmd,param){
                    var url="protocol://"+cmd+":"+param;
                    document.location = url;
                }
                function test(){
                
                    window.TEST.test(1,1);
                }
              function buttonClick()
              {
                jakilllog("hello world");
              }
            function ocClick(){
                ocClick();

            }
            function testjs(){
                alert("O-c 调用JS");     
            }
           </script>
        </head>
    <body>
        
        <h1>DEMO</h1>
        <div style="padding:10px;">
            <button type="button" class="button2" οnclick="test()">绑定调用</button>
            <input type="button" value="Url拦截" onClick="sendCommand('act','param');" />
             <button id="hallo" οnclick="buttonClick()"> 点击button</button>
                <button id="hallo" οnclick="ocClick()"> O-C 调用JS</button>
        </div>
        
    </body>
</html>

(2)创建一个类 继承于 NSObject 并在.h文件中 添加协议 实现<JSExport> 然后添加方法 方法名称与JS 中一致  例如  window.TEST.test(1,1);   O-C 定义为  -(BOOL)test:(int)params1 :(int)params2;


代码入下:

JsImp.h文件

//
//  JsImp.h
//  EasyJSWebViewSample
//
//  Created by 李挺哲 on 16/1/12.
//  Copyright © 2016年 Dukeland. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

@protocol TestJSObjectProtocol <JSExport,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
/**拍照,js回调 takePictureCallBack(localPath) */

-(BOOL)test:(int)params1 :(int)params2;

@end
@interface JsImp : NSObject<TestJSObjectProtocol>




@end

JsImp.m 文件
//
//  JsImp.m
//  EasyJSWebViewSample
//
//  Created by 李挺哲 on 16/1/12.
//  Copyright © 2016年 Dukeland. All rights reserved.
//

#import "JsImp.h"



@implementation JsImp

-(BOOL)test:(int)params1 :(int)params2{
    NSLog(@"  test  did  params1 =%d  ,params2 =%d ",params1,params2);
    [self performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    return YES;
}

-(void)show{
    UIAlertView* alert=[[UIAlertView alloc]
                        initWithTitle
                        :@"Called by JavaScript"
                        message:@"JS O-C 绑定" delegate:self cancelButtonTitle:@"Cancel"
                        otherButtonTitles:nil];
    [alert show];
    
}

@end
在ViewController中 获取JSContext

1.创建WebView 添加到页面上.

2.WebView 设置代理

3.testJS=[[JsImpalloc] init];初始化接口类

4.实现WebView中的方法

5.-(void)webViewDidFinishLoad:(UIWebView *)webView 此方法中会每次都获得JSContext

 JSContext *context = [webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];




(1)JS 与原生代码绑定


    context[@"TEST"]=testJS;

类似于Android 中WebView.addJavaScriptInteface(IMP,"Name");


(2) )URL  拦截


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

{

    //url解析规则自己定义

    NSString* rurl=[[request URL] absoluteString];

    if ([rurl hasPrefix:@"protocol://"]) {

        UIAlertView* alert=[[UIAlertViewalloc]initWithTitle:@"Called by JavaScript"

                                                     message:@"Url 拦截"delegate:selfcancelButtonTitle:@"Cancel"otherButtonTitles:nil];

        [alert show];

        

        return false;

    }

    

    return true;

}



ViewController.m

//
//  ViewController.m
//  JSAndOc
//
//  Created by 李挺哲 on 16/1/15.
//  Copyright © 2016年 ahy. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "JsImp.h"
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<UIWebViewDelegate>
{
    JsImp *testJS;

}

@property (strong, nonatomic)  UIWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [self.webView setDelegate:self];
    [self.view addSubview:_webView];
    testJS=[[JsImp alloc] init];
   NSString * path= [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
   NSURL * url= [[NSURL alloc] initWithString:path];
    NSURLRequest * request=[[NSURLRequest alloc] initWithURL:url];
    [_webView loadRequest:request];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
//    NSLog(@"did");
    
    
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //获取加载成功的JS对象
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //将TEST 与JS中的 TEST 写法一致
    context[@"TEST"]=testJS;
    context[@"jakilllog"] = ^() {
        
        NSLog(@"Begin Log");
        NSArray *args = [JSContext currentArguments];
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal);
        }
        JSValue *this = [JSContext currentThis];
        NSLog(@"-------End Log------- %@",this);
    };
     __block JSContext *blockJS = context;
    context[@"ocClick"] = ^() {
        
         [blockJS evaluateScript:@"testjs()"];
    
    };
 
   }

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //此url解析规则自己定义
    NSString* rurl=[[request URL] absoluteString];
    if ([rurl hasPrefix:@"protocol://"]) {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"Called by JavaScript"
                                                     message:@"Url 拦截" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        
        return false;
    }
    
    return true;
}


@end

Android 中WebView 中 JS 与 Java 绑定比较简单 .步骤如下;

1.创建WebView 

2.WebView设置

       webView.getSettings().setJavaScriptEnabled(true);

webView.addJavascriptInterface(jsimp, "TEST");

        webView.setWebChromeClient(new WebChromeClient() {

@Override

public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

return super.onJsAlert(view, url, message, result);

}

});


webView.loadUrl("file:///android_asset/index.html");


3.创建接口 与实现类

package com.example.helloweb;

import android.webkit.JavascriptInterface;

public interface JsInterface {
	
	public abstract boolean test(int params1,int params2);
	
}
 实现类中方法上 要加上 @ JavascriptInterface  要不然  会调用不成功


package com.example.helloweb;

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class JSImp implements JsInterface {
	private Context mContext;

	public JSImp(Context mContext) {
		super();
		this.mContext = mContext;
	}

	@Override
	@JavascriptInterface
	public boolean test(int params1, int params2) {
		// TODO Auto-generated method stub

		Toast.makeText(mContext, "test 调用  Java 中的Test方法" + params1 + "+" + params2, Toast.LENGTH_SHORT).show();
		return false;
	}

}




源代码--------->>>>>下载





 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值