瀏覽代碼

feat(demo): Update demo to show off how to open html links in phone browser

GoMinO 5 年之前
父節點
當前提交
79eb066af4
共有 3 個文件被更改,包括 95 次插入14 次删除
  1. 68
    10
      demo/App.js
  2. 26
    3
      demo/config.js
  3. 1
    1
      package-lock.json

+ 68
- 10
demo/App.js 查看文件

@@ -2,7 +2,14 @@
2 2
 
3 3
 import React, { Component } from 'react';
4 4
 
5
-import { ScrollView, StyleSheet, Text, TouchableOpacity, Platform } from 'react-native';
5
+import {
6
+  ScrollView,
7
+  StyleSheet,
8
+  Text,
9
+  TouchableOpacity,
10
+  Platform,
11
+  Linking
12
+} from 'react-native';
6 13
 
7 14
 import AutoHeightWebView from 'react-native-autoheight-webview';
8 15
 
@@ -13,6 +20,8 @@ import {
13 20
   autoWidthHtml0,
14 21
   autoWidthHtml1,
15 22
   autoWidthScript,
23
+  autoDetectLinkHtml,
24
+  autoDetectLinkScript,
16 25
   style0,
17 26
   inlineBodyStyle
18 27
 } from './config';
@@ -40,22 +49,42 @@ export default class Explorer extends Component {
40 49
 
41 50
   changeSource = () => {
42 51
     this.setState(prevState => ({
43
-      widthHtml: prevState.widthHtml === autoWidthHtml0 ? autoWidthHtml1 : autoWidthHtml0,
44
-      heightHtml: prevState.heightHtml === autoHeightHtml0 ? autoHeightHtml1 : autoHeightHtml0
52
+      widthHtml:
53
+        prevState.widthHtml === autoWidthHtml0
54
+          ? autoWidthHtml1
55
+          : autoWidthHtml0,
56
+      heightHtml:
57
+        prevState.heightHtml === autoHeightHtml0
58
+          ? autoHeightHtml1
59
+          : autoHeightHtml0
45 60
     }));
46 61
   };
47 62
 
48 63
   changeStyle = () => {
49 64
     this.setState(prevState => ({
50
-      widthStyle: prevState.widthStyle == inlineBodyStyle ? style0 + inlineBodyStyle : inlineBodyStyle,
65
+      widthStyle:
66
+        prevState.widthStyle == inlineBodyStyle
67
+          ? style0 + inlineBodyStyle
68
+          : inlineBodyStyle,
51 69
       heightStyle: prevState.heightStyle == null ? style0 : null
52 70
     }));
53 71
   };
54 72
 
55 73
   changeScript = () => {
56 74
     this.setState(prevState => ({
57
-      widthScript: prevState.widthScript === null ? autoWidthScript : null,
58
-      heightScript: prevState.heightScript === null ? autoHeightScript : null
75
+      widthScript:
76
+        prevState.widthScript !== autoWidthScript ? autoWidthScript : null,
77
+      heightScript:
78
+        prevState.heightScript !== autoHeightScript ? autoHeightScript : null
79
+    }));
80
+  };
81
+
82
+  changeTryBrowser = () => {
83
+    this.setState(_ => ({
84
+      widthHtml: autoWidthHtml0,
85
+      heightHtml: autoDetectLinkHtml,
86
+      widthScript: autoDetectLinkScript,
87
+      heightScript: autoDetectLinkScript
59 88
     }));
60 89
   };
61 90
 
@@ -79,8 +108,7 @@ export default class Explorer extends Component {
79 108
         contentContainerStyle={{
80 109
           justifyContent: 'center',
81 110
           alignItems: 'center'
82
-        }}
83
-      >
111
+        }}>
84 112
         <AutoHeightWebView
85 113
           customStyle={heightStyle}
86 114
           onError={() => console.log('height on error')}
@@ -94,12 +122,37 @@ export default class Explorer extends Component {
94 122
           onSizeUpdated={heightSize => this.setState({ heightSize })}
95 123
           source={{ html: heightHtml }}
96 124
           customScript={heightScript}
125
+          onMessage={event => {
126
+            console.log('onMessage', event.nativeEvent.data);
127
+            let { data } = event.nativeEvent;
128
+
129
+            // maybe parse stringified JSON
130
+            try {
131
+              data = JSON.parse(data);
132
+            } catch (e) {
133
+              console.log(e.message);
134
+            }
135
+
136
+            if (typeof data === 'object') {
137
+              const { url } = data;
138
+              // check if this message concerns us
139
+              if (url && url.startsWith('http')) {
140
+                Linking.openURL(url).catch(err =>
141
+                  console.error('An error occurred', err)
142
+                );
143
+              }
144
+            }
145
+          }}
97 146
         />
98 147
         <Text style={{ padding: 5 }}>
99 148
           height: {heightSize.height}, width: {heightSize.width}
100 149
         </Text>
101 150
         <AutoHeightWebView
102
-          baseUrl={Platform.OS === 'android' ? 'file:///android_asset/webAssets/' : 'webAssets/'}
151
+          baseUrl={
152
+            Platform.OS === 'android'
153
+              ? 'file:///android_asset/webAssets/'
154
+              : 'webAssets/'
155
+          }
103 156
           style={{
104 157
             marginTop: 15
105 158
           }}
@@ -133,7 +186,12 @@ export default class Explorer extends Component {
133 186
         <TouchableOpacity onPress={this.changeStyle} style={styles.button}>
134 187
           <Text>change style</Text>
135 188
         </TouchableOpacity>
136
-        <TouchableOpacity onPress={this.changeScript} style={[styles.button, { marginBottom: 100 }]}>
189
+        <TouchableOpacity onPress={this.changeTryBrowser} style={styles.button}>
190
+          <Text>try browser links</Text>
191
+        </TouchableOpacity>
192
+        <TouchableOpacity
193
+          onPress={this.changeScript}
194
+          style={[styles.button, { marginBottom: 100 }]}>
137 195
           <Text>change script</Text>
138 196
         </TouchableOpacity>
139 197
       </ScrollView>

+ 26
- 3
demo/config.js 查看文件

@@ -26,7 +26,9 @@ const inlineBodyStyle = `
26 26
 
27 27
 const autoHeightScript = `
28 28
 var styleElement = document.createElement('style');
29
-styleElement.innerHTML = '${style1.replace(/\'/g, "\\'").replace(/\n/g, '\\n')}';
29
+styleElement.innerHTML = '${style1
30
+  .replace(/\'/g, "\\'")
31
+  .replace(/\n/g, '\\n')}';
30 32
 document.head.appendChild(styleElement);
31 33
 document.body.style.background = 'cornflowerblue';
32 34
 `;
@@ -46,10 +48,29 @@ const autoWidthHtml1 = `
46 48
 
47 49
 const autoWidthScript = `
48 50
 var styleElement = document.createElement('style');
49
-styleElement.innerHTML = '${style1.replace(/\'/g, "\\'").replace(/\n/g, '\\n')}';
51
+styleElement.innerHTML = '${style1
52
+  .replace(/\'/g, "\\'")
53
+  .replace(/\n/g, '\\n')}';
50 54
 document.head.appendChild(styleElement);
51 55
 `;
52 56
 
57
+const autoDetectLinkHtml = `
58
+  <p style="font-weight: 400;font-style: normal;font-size: 21px;line-height: 1.58;letter-spacing: -.003em;">
59
+      <a href="https://github.com/iou90/react-native-autoheight-webview">Tags</a> are great for describing the essence of your story in a single word or phrase, but stories are rarely about a single thing.
60
+      <span style="background-color: transparent !important;background-image: linear-gradient(to bottom, rgba(146, 249, 190, 1), rgba(146, 249, 190, 1));">If I pen a story about moving across the country to start a new job in a car with my husband, two cats, a dog, and a tarantula, I wouldn't only tag the piece with "moving". I’d also use the <a href="http://x-squad.com">tags</a> "pets", "marriage", "career change", and "travel tips".</span>
61
+  </p>
62
+`;
63
+
64
+//https://medium.com/@elhardoum/opening-external-links-in-browser-in-react-native-webview-18fe6a66312a
65
+const autoDetectLinkScript = `
66
+!function(){
67
+  function isUrl(str){
68
+    return str.startsWith('http');
69
+  }
70
+  var e=function(e,n,t){if(n=n.replace(/^on/g,""),"addEventListener"in window)e.addEventListener(n,t,!1);else if("attachEvent"in window)e.attachEvent("on"+n,t);else{var o=e["on"+n];e["on"+n]=o?function(e){o(e),t(e)}:t}return e},n=document.querySelectorAll("a[href]");if(n)for(var t in n)n.hasOwnProperty(t)&&e(n[t],"onclick",function(e){!isUrl(this.href)||(e.preventDefault(),window.postMessage(JSON.stringify({url:this.href})))})
71
+}();
72
+`;
73
+
53 74
 export {
54 75
   autoHeightHtml0,
55 76
   autoHeightHtml1,
@@ -58,5 +79,7 @@ export {
58 79
   autoWidthHtml0,
59 80
   autoWidthHtml1,
60 81
   autoWidthScript,
61
-  inlineBodyStyle
82
+  inlineBodyStyle,
83
+  autoDetectLinkHtml,
84
+  autoDetectLinkScript
62 85
 };

+ 1
- 1
package-lock.json 查看文件

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "react-native-autoheight-webview",
3
-  "version": "0.10.1",
3
+  "version": "0.10.2",
4 4
   "lockfileVersion": 1,
5 5
   "requires": true,
6 6
   "dependencies": {