|
JSContext監(jiān)控UIWebView上JS事件,並執(zhí)行JS方法,實現(xiàn)js與ios方法互調(diào) 依賴庫 :#import <JavaScriptCore/JavaScriptCore.h> ios7的新庫,對js支持比較好 傳統(tǒng)的方式是在uiwebview內(nèi)捕獲js事件,但是如果人家點擊的時間不是跳轉(zhuǎn)或者說不含request請求的,那麼是不會進入shouldStartLoadWithRequest 方法的,那麼就捕獲不到此次的方法了。 上代碼: -(void)wb
{
if (!webView1) {
webView1 = [[UIWebView alloc]initWithFrame:CGRectMake(0, 90, SCREEN_WIDTH , SCREEN_HEIGHT)];
webView1.scalesPageToFit = YES;//自動對頁面進行縮放以適應(yīng)屏幕
[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內(nèi),點擊了“點這裏點這裏”按鈕後,會執(zhí)行test()方法。test()方法內(nèi)調(diào)用與ios端約定的方法tokenSend 那麼客戶端便會檢測到j(luò)s事件,便會_context的block內(nèi)。 在此便可以調(diào)用js方法aha()了。 爽不爽?不需要去 shouldStartLoadWithRequest判斷漫長的js方法了。 還有更爽的。對實現(xiàn)方式不關(guān)注的話,可以直接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調(diào)用本地方法都實現(xiàn)了。 我就問你們嗨不嗨。 -
|