1.当使用WebView 加载Web页面时.有时候需要用到 点击Web页面 跳转到原生Activity 或者 ViewController.混合开发的时候,就需要 通过JS 调用 原生代码.Java 或者 O-C 调用js 代码.
两种方式(1)JS 与原生代码绑定 (2)URL 拦截
IOS使用
步骤.(1)首先创建 HTML页面
index.html 并将HTML文件放到程序.
Hello PhoneGap
DEMO
(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
#import
#import
@protocol TestJSObjectProtocol
/**拍照,js回调 takePictureCallBack(localPath) */
-(BOOL)test:(int)params1 :(int)params2;
@end
@interface JsImp : NSObject
@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");
- (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
#import "JsImp.h"
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
{
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
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;
}
}
源代码--------->>>>>下载