JSContext監控UIWebView上JS事件,並執行JS方法,實現js與ios方法互調 依賴庫 :#import <JavaScriptCore/JavaScriptCore.h> ios7的新庫,對js支持比較好 傳統的方式是在uiwebview內捕獲js事件,但是如果人家點擊的時間不是跳轉或者說不含request請求的,那麽是不會進入shouldStartLoadWithRequest 方法的,那麽就捕獲不到此次的方法了。 上代碼: -(void)wb
{
if (!webView1) {
webView1 = [[UIWebView alloc]initWithFrame:CGRectMake(0, 90, SCREEN_WIDTH , SCREEN_HEIGHT)];
webView1.scalesPageToFit = YES;//自動對頁面進行縮放以適應屏幕
[self.view addSubview:webView1];
}
webView1.delegate = self;
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"ios_test" ofType:@"html"];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView1 loadHTMLString:html baseURL:baseURL];
_context = [webView1 valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
WeakSelf(bSelf);
_context[@"tokenSend"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
NSLog(@"this: %@",this);
NSLog(@"-------End Log-------");
[bSelf.context evaluateScript:@"aha('dddee222')"];
};
本地html文件代碼 <!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Document</title></head><script>functiontest() {//alert("點得好!!"+new Date());
tokenSend("1");
};
functionaha(xx) {
alert(xx);
}
</script><body><inputtype="button"value="點這點這點這"onclick="test();"></body></html>
解釋: 方法“tokenSend”爲客戶端與js約定的一個方法名, html內,點擊了“點這裏點這裏”按鈕後,會執行test()方法。test()方法內調用與ios端約定的方法tokenSend 那麽客戶端便會檢測到js事件,便會_context的block內。 在此便可以調用js方法aha()了。 爽不爽?不需要去 shouldStartLoadWithRequest判斷漫長的js方法了。 還有更爽的。對實現方式不關注的話,可以直接return值給js! html代碼 <!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Document</title></head><script>functiontest() {//alert("點得好!!"+new Date());var aa= tokenSend("1");
alert(aa);
};
</script><body><inputtype="button"value="點這點這點這"onclick="test();"></body></html>
ios代碼 _context[@"tokenSend"] = ^() {
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
return @"token111";
};
就這麽簡單,檢測js時間,傳值給js,js調用本地方法都實現了。 我就問你們嗨不嗨。 -
|