小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

JSContext監(jiān)控UIWebView上JS事件,並執(zhí)行JS方法,實現(xiàn)js與ios方法互調(diào)

 jerry_tom123 2016-01-15

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)了。
我就問你們嗨不嗨。

-

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多