美文网首页
JavaScriptCore框架 _JSContext (2)

JavaScriptCore框架 _JSContext (2)

作者: by小杰 | 来源:发表于2016-09-29 17:21 被阅读24次

    下面实现: 在iOS中,实现HTML中的button点击方法。

    //每次加载网页请求都会走该方法
    - (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    #pragma mark ------ JSContext(OC点击方法实现)
        //将context与HTML文件关联起来
        JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        
        //log为网页中button的onClick方法
        context[@"log"] = ^(){
    
            NSLog(@"ssss");
    
        };
    }     
    

    在viewDidLoad方法中,加载网页文件

    UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
        [self.view addSubview:web];
        web.delegate = self;
        
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
        
        NSString *str = [NSString stringWithContentsOfFile:bundle encoding:NSUTF8StringEncoding error:nil];
        
        [web loadHTMLString:str baseURL:nil];
    

    HTML文件index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
                <title></title>
                </head>
        <body>
            <input type="button" value="success" onclick="log()" />
        </body>
    <!--    //<script>-->
    <!--        function log(){-->
    <!--            console.log(1);-->
    <!--        }-->
    <!--    </script>-->
    </html>
    

    相关文章

      网友评论

          本文标题:JavaScriptCore框架 _JSContext (2)

          本文链接:https://www.haomeiwen.com/subject/npflyttx.html