react native 中webview內的點擊事件傳到外部原生調用


先說一下我使用webview的時候遇到的一個功能需求

是這樣的,上圖中的這個頁面是用h5做的,但是由於點擊“我的優惠劵”是需要跳轉到我原生的頁面,也就是說我需要獲得這個h5提供的點擊事件,但是由於這個頁面不是在我們本地弄的,而是在后台那邊弄好,然后通過給一個h5鏈接,所以我們在本地是沒有辦法給它添加點擊事件。嗯,是的,我們沒有辦法給它添加事件點擊,但是我們沒有拿到這個點擊事件,我們怎么進行跳轉呢。到重點了。

在react native有一個第三方的組件,是可以實現這個功能的:

1 react-native-webview-bridge

是的就是這個東西。這個具體怎么有哪些方法,大家可以到Github上看看,直接搜索這個就可以了,我這里只說我實現這個功能用到的一些東東。

首先,我們得將這個家伙添加到我們的項目中去

1 var WebViewBridge = require('react-native-webview-bridge');

然后webViewBridge就可以作為一個控件一樣使用了。

 1 'use strict';
 2 import React, {
 3     Component
 4 } from 'react';
 5 
 6 import  {
 7     AppRegistry,
 8     StyleSheet,
 9     View,
10     WebView,
11 } from 'react-native';
12 
13 import WebViewPage from '../wiget/webViewPage';
14 
15 var WebViewBridge = require('react-native-webview-bridge');
16 
17 
18 /**
19  * webView
20  * 22  * @url     跳轉的地址
23  */
24 export default class WebViewForBridge extends Component {
25     constructor(props) {
26         super(props);
27     }
28 
29 
30     onBridgeMessage(message) {
31         const {navigator} = this.props;
32         if (message === "coupons") {
33             if (navigator) {
34                 navigator.push({
35                     component: WebViewPage,
36                     params: {
37                         url: this.props.myCoupons,
38                         title: Strings.MyCoupons,
39                     },
40                 });
41             }
42         } 
43     }
44 
45     render() {
46         return (
47             <View style={{flex: 1}}>
48               
49                 <WebViewBridge
50                     ref="webViewBridge"
51                     onBridgeMessage={this.onBridgeMessage.bind(this)}
52                     style={styles.webViewStyle}
53                     source={{uri: this.props.url === undefined ? DEFAULT_URL : this.props.url}}
54                     startInLoadingState={true}
55                     domStorageEnabled={true}
56                     javaScriptEnabled={true}/>
57             </View>
58         );
59     }
60 }
61 
62 var styles = StyleSheet.create({
63     webViewStyle: {
64         backgroundColor: ‘#f2f2f2’
65     }
66 });

 

soource是我顯示的h5鏈接,因為有些東西是我們自己項目封裝的,所以不方便貼出來,朋友們不要傻傻的全部復制粘貼啊,嗯好了,原生代碼就寫完了,當然你現在測試的話,一點用都沒有,因為我們還需要改h5鏈接里面的代碼。
我在前面弄了一張圖,我下面就把h5的源代碼貼出來,

  1 <!DOCTYPE html>
  2 <html>
  3 <head lang="en">
  4     <meta charset="UTF-8">
  5     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=2.0">
  6     <title>慢錢精選小額理財-慢錢</title>
  7     <meta name="keywords" content="小額理財、零錢理財、普惠理財、精選理財">
  8     <meta name="description" content="慢錢獨家打造,精選小額理財,優中選優,輕松實現財務自由">
  9     
 10 
 11 
 12 
 13 <script>
 14 
 15     // 百度統計
 16     var _vds = _vds || [];
 17     window._vds = _vds;
 18     (function(){
 19         _vds.push(['setAccountId', 'df10dc61bd6c48c7854b439c2dbb4295']);
 20         (function() {
 21             var vds = document.createElement('script');
 22             vds.type='text/javascript';
 23             vds.async = true;
 24             vds.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'dn-growing.qbox.me/vds.js';
 25             var s = document.getElementsByTagName('script')[0];
 26             s.parentNode.insertBefore(vds, s);
 27         })();
 28     })();
 29 
 30     var browser = {
 31         versions: function () {
 32             var u = navigator.userAgent, app = navigator.appVersion;
 33             return {     //移動終端瀏覽器版本信息
 34                 trident: u.indexOf('Trident') > -1, //IE內核
 35                 presto: u.indexOf('Presto') > -1, //opera內核
 36                 webKit: u.indexOf('AppleWebKit') > -1, //蘋果、谷歌內核
 37                 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐內核
 38                 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否為移動終端
 39                 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端
 40                 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android終端或uc瀏覽器
 41                 iPhone: u.indexOf('iPhone') > -1, //是否為iPhone或者QQHD瀏覽器
 42                 iPad: u.indexOf('iPad') > -1, //是否iPad
 43                 webApp: u.indexOf('Safari') == -1 //是否web應該程序,沒有頭部與底部
 44             };
 45         }(),
 46         language: (navigator.browserLanguage || navigator.language).toLowerCase()
 47     }
 48 
 49     var _hmt = _hmt || [];
 50     (function() {
 51         var hm = document.createElement("script");
 52         hm.src = "https://hm.baidu.com/hm.js?4fbebe5a92c9c38862e6bad7fc00d6bd";
 53         var s = document.getElementsByTagName("script")[0];
 54         s.parentNode.insertBefore(hm, s);
 55     })();
 56 </script>
 57 
 58 <link rel="stylesheet" type="text/css" href="/static/css/mui.min.css?v=2016123481123">
 59 <link rel="stylesheet" type="text/css" href="/static/css/manqianbao.min.css?v=2016123481123">
 60 <link rel="stylesheet" type="text/css" href="/static/css/swiper-3.4.0.min.css?v=2016123481123">
 61 <script src="/static/js/jquery.v2.1.1-min.js?v=2016123481123"></script>
 62 <script src="/static/js/swiper-3.4.0.jquery.min.js?v=2016123481123"></script>
 63 <script src="/static/js/progressbar.min.js?v=2016123481123"></script>
 64 <script src="/static/js/common.min.js?v=2016123481123"></script>
 65 <script src="/static/js/jquery.dateFormat.min.js?v=2016123481123"></script>
 66 <script src="/static/js/mui.min.js?v=2016123481123"></script>
 67 
 68 <div class="opt" style="z-index: 99;"></div>
 69 <div class="head-daohang">
 70     <table>
 71         <tbody>
 72         <tr>
 73             <td onclick="window.location.href='/'">慢錢首頁</td><td onclick="window.location.href='/bao/list.html'">零錢理財</td>
 74         </tr>
 75         <tr>
 76             <td onclick="window.location.href='/product/index.html'">百萬理財</td><td onclick="window.location.href='http://www.manqian.cn/master.html'">金牌理財師</td>
 77         </tr>
 78         <tr>
 79             <td onclick="window.location.href='http://m.toutiao.manqian.cn/'">慢錢頭條</td><td onclick="window.location.href='http://www.manqian.cn/research/all_1.html'">投研中心</td>
 80         </tr>
 81         <tr>
 82             <td onclick="window.location.href='http://www.manqian.cn/subject.html'">熱門資訊</td><td onclick="window.location.href='/user/index.html'">個人主頁</td>
 83         </tr>
 84         </tbody>
 85     </table>
 86 </div>
 87 
 88 <!----------頁面共用的錯誤提示------------>
 89 <div class="common-error">
 90     <p></p>
 91 </div>
 92 <script>
 93 
 94     //自動隱藏的錯誤提示框
 95     function ErrorOut(){
 96         $('.common-error').fadeOut();
 97     }
 98     function errorTip(msg, e) {
 99         e.stopPropagation();
100         $('.common-error').find('p').text(msg);
101         $('.common-error').show();
102         setTimeout(ErrorOut,3000);
103     }
104     $('.common-error').click(function(e){
105         e.stopPropagation();
106     })
107     $('body').click(function(){
108         $('.common-error').fadeOut();
109     })
110 
111     function result(code, msg) {
112         var result = new Object();
113         result.code = code;
114         result.msg = msg;
115         return result;
116     }
117 </script>
118 
119     <script src="/static/js/webviewbridge.min.js?v=2016123481123" type="text/javascript"></script>
120 </head>
121 
122 
123 <body class="f2bg">
124 
125 <div class="wrap">
126     <div class="center-banner my-zichan-YE">
127         <div class="my-zichan">
128             <table>
129                 <tbody>
130                 <tr><td>資產總額(元)</td>
131                 </tr>
132                 <tr>
133                     <td></td>
134                 </tr>
135                 </tbody>
136             </table>
137         </div>
138     </div>
139 
140     <div class="center-menu my-zichan-YE2 mt10">
141         <li>賬戶余額(元) <em></em> <button class="zichan-tixian zichan-tixian-red" id="withdraw">提現</button></li>
142         <li>待收本金(元) <span></span></li>
143         <li>待收收益(元) <span></span></li>
144     </div>
145 
146     <div class="center-menu my-zichan-YE3 mt10">
147         <li class="acticveBg-gray" onclick="window.location.href='/discountCoupon/list.html'">我的優惠券<span class="mui-icon mui-navigate-right"></span></li>
148     
149     </div>
150 
151 </div>
152 
153 </body>
154 
155 <script>
156     $(function () {
157       /*  $('#myCoupons').on("click", function () {
158             WebViewBridge.send("coupons");
159         });
160 */
161         $("#withdraw").click(function(){
162             window.location.href="/asset/withdrawInfo.html";
163         });
164     })
165 
166 </script>
167 
168 </html>

前面一大堆的代碼不用管,只需要關注幾個地方就好了,

其中一個就是這里

<script src="/static/js/webviewbridge.min.js?v=2016123481123" type="text/javascript"></script>

這個就是將這個第三方集成進來,如果不懂的朋友,可以找做js的朋友幫忙。

其次是這里
 <li class="acticveBg-gray" onclick="window.location.href='/discountCoupon/list.html'">我的優惠券<span class="mui-icon mui-navigate-right"></span></li>

給這個定義一個ID,

通過ID,我們可以寫一個方法

1  $('#myCoupons').on("click", function () {
2             WebViewBridge.send("coupons");
3         });

然后通過webViewBridge.send();發送一個字符串過去,發送什么字符串,由自己決定,我這里傳遞這個,是方便我識別。

好了,又回到原生頁面中,

找到這一段代碼

 1 onBridgeMessage(message) {
 2 31         const {navigator} = this.props;
 3 32         if (message === "coupons") {
 4 33             if (navigator) {
 5 34                 navigator.push({
 6 35                     component: WebViewPage,
 7 36                     params: {
 8 37                         url: this.props.myCoupons,
 9 38                         title: Strings.MyCoupons,
10 39                     },
11 40                 });
12 41             }
13 42         } 
14 43     }

是不是瞬間明白了。是不是很簡單。吃飯去了

 
        

 


免責聲明!

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



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