• UIWebView开发中,js与oc,js与swift交互,相互传递参数的方法


    实际开发中经常遇到需要向webView传递参数或从webView取参数,在此写了个超简单的demo供大家参考,本人js刚学了一天,所以不足之处海涵.

    废话不多说,直接上代码

    oc版

     1 #import "ViewController.h"
     2 @interface ViewController ()<UIWebViewDelegate>
     3 @property (nonatomic, strong)UIWebView * webView;
     4 @end
     5 
     6 @implementation ViewController
     7 
     8 - (void)viewDidLoad {
     9     [super viewDidLoad];
    10     // Do any additional setup after loading the view, typically from a nib.
    11     self.view.backgroundColor = [UIColor whiteColor];
    12     self.title = @"Web Test";
    13     [self.view addSubview:self.webView];
    14 }
    15 
    16 -(UIWebView *)webView{
    17     if (!_webView) {
    18         _webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    19         _webView.delegate = self;
    20         NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@".html"];
    21         NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:filePath]];
    22         [_webView loadRequest:request];
    23     }
    24     return _webView;
    25 }
    26 
    27 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    28     
    29     if ([request.URL.absoluteString hasSuffix:@"clickLoginBtn"]) {
    30 //        向js传递数据
    31         [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"loginCallBack('I am id from app','I am token from app')"]];
    32 //        从js获取数据
    33         NSString *webData = [_webView stringByEvaluatingJavaScriptFromString:@"returnData();"];
    34         NSLog(@"%@",webData);
    35         
    36         [_webView stopLoading];
    37     }
    38     return YES;
    39 }

     主要方法就是在webView的代理中执行: stringByEvaluatingJavaScriptFromString:@"JS的方法名"这个方法,即可在web中调用js的函数

     1 <!DOCTYPE HTML>
     2 <html>
     3     
     4     <head>
     5         
     6         <script>
     7             function loginCallBack(id,token){
     8                 var x=document.getElementById("logindata");
    10 alert(id) 11 alert(token) 12 } 13 </script> 14 15 </head> 16 17 <body> 18 <h2 id="logindata" align= center>Clict To Transmit Data</h2> 19 <button id="hello" onclick="buttonClick()" >login</button> 20 <script > 21 function buttonClick() 22 {
                //webview重定向
    23 document.location = "clickLoginBtn" 24 } 25 function returnData(){ 26 return document.getElementById("logindata").script 27 } 28 </script> 29 </body> 30 </html>

    写在<script></script>间的function函数会被oc的上述方法调用,再根据函数的类型,传入参数和传出参数,即可实现oc与js相互间传递参数了.

    注意,当点击web上的按钮时,执行buttonClick方法,但若不为web页面重定向,就不会发送新的request请求,不会执行webview中的代理方法,代理方法也就不会被执行,而代理方法的执行是传递参数的前提条件,所以一定不要忘了给webview重定向.

    Swift版

    基本原理就这些,下面再附上swift与js的交互,原理是相通的

    swift代码

     1 import UIKit
     2 class ViewController: UIViewController ,UIWebViewDelegate{
     3 
     4     override func viewDidLoad() {
     5         super.viewDidLoad()
     6         // Do any additional setup after loading the view, typically from a nib.
     7         
     8         self.title = "Web-JS Test"
     9         self.view.backgroundColor = UIColor.blueColor()
    10         
    11         let filePath : String = NSBundle.mainBundle().pathForResource("test", ofType: ".html")!
    12         let request = NSURLRequest.init(URL: NSURL(fileURLWithPath: filePath))
    13         
    14         let webView = UIWebView.init(frame: UIScreen.mainScreen().bounds)
    15         webView.delegate = self;
    16         self.view.addSubview(webView)
    17         
    18         webView.loadRequest(request)
    19 
    20     }
    21     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    22         //核心代码
    23         if request.URL!.absoluteString.hasSuffix("url"){
    24             let id = "'I am id from app'"
    25             let tocken = "'I am tocken from app'"
    26 //            向h5传递参数
    27             webView.stringByEvaluatingJavaScriptFromString("sendDataToWeb((id) , (tocken))")
    28 //            从h5接收参数
    29             let returnStr = webView.stringByEvaluatingJavaScriptFromString("getDataFromWeb()")
    30             print(returnStr)
    31             webView.stopLoading()
    32         }
    33         return true
    34     }

    js代码

     1 <!DOCTYPE HTML>
     2 <html>
     3     <body>
     4         <h2 align=center  id="logindata">Click To Transmit Data</h2>
     5         <button id="hallo" onclick="buttonClick()" align=center>login</button>
     6         <script>
     7             function buttonClick()
     8             {
     9                 //重指向
    10                 document.location = "url"
    11             }
    12         
    13             function sendDataToWeb(id,token){
    14                 alert(id)
    15                 alert(token)
    16                 document.getElementById("logindata").innerHTML = "Data Transmit Complete"
    17             }
    18         
    19             function getDataFromWeb(){
    20                 return "I am a string from web "
    21             }
    22         
    23         </script>
    24 
    25 
    26     </body>
    27 </html>

    此外还有一种方法javascript直接调用oc代码而非通过改变url回调方式,可以通过不执行webview代理直接调用js函数,通过<JavaScriptCore/JavaScriptCore.h>框架来实现的,实测有效.不过对其方法不太了解,没选择这种方法来做,也推荐一下.

  • 相关阅读:
    BZOJ3674:可持久化并查集加强版
    BZOJ3772:精神污染
    BZOJ3932:[CQOI2015]任务查询系统
    BZOJ3123:[SDOI2013]森林
    BZOJ1926:[SDOI2010]粟粟的书架
    029 列表类型内置方法
    02 Python爬虫之盗亦有道
    01 Python爬虫之Requests库入门
    028 字符串类型内置方法
    027 数字类型内置方法
  • 原文地址:https://www.cnblogs.com/shadowtree/p/4921639.html
Copyright © 2020-2023  润新知