ios怎么实现了本地帐号和webview的互通

2025-05-11 04:57:26
推荐回答(1个)
回答1:

方法/步骤
方法一:
通过webview的delegate方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
在上面这个函数中,通过截取NSURLRequest解析js中传递过来的参数,和网址再根据参数来调用已定义好的方法。
但现在我们介绍另外一种方法。
方法二:我们用 javascriptCore.framework 这个库。
首先在建立一个UIWebView,代码如下:
#import "webview.h"
#import

@implementation webview

-(id)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];

if( self ){
self.webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 310, self.bounds.size.width, 300)];
self.webview.backgroundColor=[UIColor lightGrayColor];
NSString *htmlPath=[[NSBundle mainBundle] resourcePath];
htmlPath=[htmlPath stringByAppendingPathComponent:@"html/index.html"];
NSURL *localURL=[[NSURL alloc]initFileURLWithPath:htmlPath];
[self.webview loadRequest:[NSURLRequest requestWithURL:localURL]];
[self addSubview:self.webview];

JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"log"] = ^() {

NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];

for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}

JSValue *this = [JSContext currentThis];
NSLog(@"this: %@",this);
NSLog(@"-------End Log-------");

};

}
return self;
}

@end

在上面代码中,我们先引入了javascriptCore.framework这个库,然后webview那一套就不多说了,注意我加载一个静态网页。然后我用
JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
获取该UIWebview的javascript执行环境。

在该javascript执行环境中,定义一个js函数,注意关键点来了,这个函数的执行体完全是 objective-c代码写的,也就是下面:
context[@"jakilllog"] = ^() {

NSLog(@"Begin Log");
NSArray *args = [JSContext currentArguments];

for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}

JSValue *this = [JSContext currentThis];
NSLog(@"-------End Log-------");

};
oc端已经写好了,我们现在进行html部分。
看看UIWebView 中所加载的 html及其js代码是如何写的。
























上面html定义了一个button,然后引用index.js,点击button的响应函数为buttonClick() 。
该函数在index.js中定义,如下
function buttonClick()
{
jakilllog("hello world");
}
注意,jakilllog("hello world"); 函数名jakilllog才是我们oc端调用的
oc端调用时的代码。
context[@"jakilllog"] = ^() {

NSLog(@"Begin Log");
NSArray *args = [JSContext currentArguments];

for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}

JSValue *this = [JSContext currentThis];
NSLog(@"-------End Log-------");

};

现在的流程是,点击button按钮,响应buttonClick(),去掉用buttonClick()这个方法
function buttonClick()
{
jakilllog("hello world");
}
然后执行jakilllog("hello world"); 并传参“hello world“ 这个函数。这个函数实现在我们oc端,所以调用方法:
context[@"jakilllog"] = ^() {

NSLog(@"Begin Log");
NSArray *args = [JSContext currentArguments];

for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}

JSValue *this = [JSContext currentThis];
NSLog(@"-------End Log-------");

};