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>框架來實現的,實測有效.不過對其方法不太了解,沒選擇這種方法來做,也推薦一下.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM