@@ -46,10 +46,12 @@ import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
46
46
2 . add the following code to add the package to ` MainActivity.java `
47
47
48
48
``` java
49
- mReactInstanceManager = ReactInstanceManager . builder()
50
- ...
51
- .addPackage(new WebViewBridgePackage ())
52
- ...
49
+ protected List<ReactPackage > getPackages() {
50
+ return Arrays . < ReactPackage > asList(
51
+ new MainReactPackage (),
52
+ new WebViewBridgePackage () // <- this
53
+ );
54
+ }
53
55
```
54
56
55
57
3 . add the following codes to your ` android/setting.gradle `
@@ -123,49 +125,39 @@ This example can be found in `examples` folder.
123
125
124
126
``` js
125
127
const injectScript = `
126
- function webViewBridgeReady(cb) {
127
- //checks whether WebViewBirdge exists in global scope.
128
- if (window.WebViewBridge) {
129
- cb(window.WebViewBridge);
130
- return;
131
- }
132
-
133
- function handler() {
134
- //remove the handler from listener since we don't need it anymore
135
- document.removeEventListener('WebViewBridge', handler, false);
136
- //pass the WebViewBridge object to the callback
137
- cb(window.WebViewBridge);
138
- }
139
-
140
- //if WebViewBridge doesn't exist in global scope attach itself to document
141
- //event system. Once the code is being injected by extension, the handler will
142
- //be called.
143
- document.addEventListener('WebViewBridge', handler, false);
144
- }
145
-
146
- webViewBridgeReady(function (webViewBridge) {
147
- webViewBridge.onMessage = function (message) {
148
- alert('got a message from Native: ' + message);
149
-
150
- webViewBridge.send("message from webview");
151
- };
152
- });
128
+ (function () {
129
+ if (WebViewBridge) {
130
+
131
+ WebViewBridge.onMessage = function (message) {
132
+ if (message === "hello from react-native") {
133
+ WebViewBridge.send("got the message inside webview");
134
+ }
135
+ };
136
+
137
+ WebViewBridge.send("hello from webview");
138
+ }
139
+ }());
153
140
` ;
154
141
155
142
var Sample2 = React .createClass ({
156
- componentDidMount () {
157
- setTimeout (() => {
158
- this .refs .webviewbridge .sendToBridge (" hahaha" );
159
- }, 5000 );
160
- },
161
- onBridgeMessage : function (message ) {
162
- console .log (message);
143
+ onBridgeMessage (message ){
144
+ const { webviewbridge } = this .refs ;
145
+
146
+ switch (message) {
147
+ case " hello from webview" :
148
+ webviewbridge .sendToBridge (" hello from react-native" );
149
+ break ;
150
+ case " got the message inside webview" :
151
+ console .log (" we have got a message from webview! yeah" );
152
+ break ;
153
+ }
163
154
},
164
- render : function () {
155
+
156
+ render () {
165
157
return (
166
158
< WebViewBridge
167
159
ref= " webviewbridge"
168
- onBridgeMessage= {this .onBridgeMessage }
160
+ onBridgeMessage= {this .onBridgeMessage . bind ( this ) }
169
161
injectedJavaScript= {injectScript}
170
162
source= {{uri: " http://google.com" }}/ >
171
163
);
0 commit comments