zoukankan      html  css  js  c++  java
  • webView与js交互

    问:在UIWebView上点击回复,如何使用UITextField进行回复?

    答:UIWebView有一个stringByEvaluatingJavaScriptFromString方法,可以将js嵌入页面中,通过这个方法,我们可以在iOS中与web的网页元素交互。通过js获取点击时间,弹出UITextField,输入字符串后,可以通过post请求发送回复。

      

    一、App调用JS方法

        首先app调用js方法使用系统自带的stringByEvaluatingJavaScriptFromString,这里简单实现就在webView加载完成的时候调用js内部alert方法 

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        
        // 第一步 app call js method
        [self.webView stringByEvaluatingJavaScriptFromString:@"alert()"];
    }
    

      

    二、JS调用App方法

       实现思路:使用webView代理方法webView:shouldStartLoadWithRequest:navigationType:(是否允许加载某个请求)拦截JS重定向的URL,然后对URL进行解析

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        // 第二步  js all app method
        
        NSURL *url = [request URL];
    
        NSString *urlStr = [url absoluteString];
        NSLog(@"absoluteString --> %@",urlStr);
        
        if ([[url scheme] isEqualToString:@"jscalloc"]) {
            NSArray *arr = [urlStr componentsSeparatedByString:@"://"];
            NSString *methodName = [arr lastObject];
            
            SEL sel = NSSelectorFromString(methodName);
            
            [self performSelector:sel];
        }
        
        return YES;
    }
    
    - (void)test {
        
        NSLog(@"i love jiang beibei");
    }
    

      下面是html部分代码

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
        
    <script>
        function action() {
            window.location.href = "jscalloc://test";
        }
    </script>
    
    </head>
    
    <body>
    
    <p>我爱姜贝贝</p>
    <p>我爱姜贝贝</p>
    <p>我爱姜贝贝</p>
    
    <button onclick="action()">btnbtn</button>
    
    </body>
    </html>

     

    本文  Demo传送门

  • 相关阅读:
    偏态分布的均值与中位数关系
    Leetcode 769. Max Chunks To Make Sorted
    【STL】max_element()函数
    [LeetCode] 1338. Reduce Array Size to The Half
    [LeetCode] 985. Sum of Even Numbers After Queries
    [LeetCode] 984. String Without AAA or BBB
    [LeetCode] 1405. Longest Happy String
    [LeetCode] 1646. Get Maximum in Generated Array
    [LeetCode] 926. Flip String to Monotone Increasing
    [LeetCode] 1658. Minimum Operations to Reduce X to Zero
  • 原文地址:https://www.cnblogs.com/jiangzzz/p/5610292.html
Copyright © 2011-2022 走看看