React Native WebView onMessage doesn't work on Android
See original GitHub issueDescription
WebView’s onMessage function never gets called on some Android versions.
This behaviour is not consistent on the Expo simulator. Test on physical devices.
Reproduction Steps
Se line 40 on the following snack.
If you test on a physical device and call window.postMessage
without the second parameter it will throw “Failed to execute ‘postMessage’ on ‘Window’: 2 arguments required, but only 1 present”.
The second parameter should be '*'
.
See postMessage api on Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
postMessage
seems to work only after the DOMContentLoaded event but not immediately. Expo simulator catches the two last events, but on a physical device I was able to trigger and receive messages before DOMContentLoaded. I think this should’ve been clarified on the docs.
Sample Code
https://snack.expo.io/HybU5stmW
Solution
Update the docs. Where is stated: “window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data. data must be a string.”
Should state:
window.postMessage requires two arguments, data, …, and targetOrigin
which should be '*'
.
Additional Information
- React Native version: react-native: 0.44.2
- Platform: Android 6.0 and 5.0 (didn’t tested on previous versions)
- Development Operating System: macOS 10.12.4
- Build tools: Xcode 8.3.3, Android Studio 2.3
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:12 (1 by maintainers)
Top GitHub Comments
My workaround:
add this to WebView injectedJavaScript prop
@fernandofranca I solved my problem. In my case, it worked well in Android 7.1 but not in below versions. I used some arrow functions in my <script></script>, and that was the problem. After I changed them to function(){ }, it works well in below versions. Thank you for your help!