onMessage prop is required in some or all environments for injectedJavaScript/injectedJavaScriptBeforeContentLoaded to work
See original GitHub issueSeveral users (e.g. in #1260 and #1291) are tripping up on the unintuitive behaviour of an onMessage
prop needing to be provided in order for injectedJavaScript
to run. It also tripped me up when I first came to use this package.
We currently document the behaviour in docs/Guide.md
, in the section The window.ReactNativeWebView.postMessage method and onMessage prop
:
However, I see no reason in the first place why lack of onMessage
should abrogate JS injection, other than the fact that it’s always behaved like this.
Here is what’s causing it, in case anyone feels like making a PR:
src/WebView.ios.tsx#L339
messagingEnabled
is set tofalse
only ifonMessage
is defined.src/WebView.macos.tsx#L320
messagingEnabled
is set tofalse
only ifonMessage
is defined.src/WebView.android.tsx#L329
messagingEnabled
is set tofalse
only ifonMessage
is defined.src/WebView.windows.tsx#L235
messagingEnabled
is set tofalse
only ifonMessage
is defined.ios/RNCWebView.m#L1249-L1254
: theinjectedJavaScriptBeforeContentLoaded
andinjectedJavaScript
user scripts do not get added ifmessagingEnabled
isfalse
(my own FIXME recommendation appears above these lines).android/src/main/java/com/reactnativecommunity/webview/RNCWebViewManager.java#L1058-L1062
: Addition and removal of JS interfaces are toggled by the state ofmessagingEnabled
.- I can’t find references to
messagingEnabled
inwindows/ReactNativeWebView
. Maybe I’m just looking in the wrong places, or maybe JS injection isn’t supported at all on Windows, yet?
Since #1286 was merged, this issue is solved for iOS, but hasn’t to my understanding been addressed for any of the other platforms.
The PR also didn’t touch src/WebView.ios.ts
, so it may furthermore be incomplete in any case.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:8
Top GitHub Comments
I am already using ‘onMessage’. Still it is not working to inject javascript. My WebView something like that: <WebView onLoadEnd={() => { this._setstatus() }} onNavigationStateChange={this.on_navigaton_new} injectedJavaScript={custom_script} onMessage={x => this.onMessageGet(x)} javaScriptEnabled={true} source={{ uri: this.state.url, forceReload: this.state.forceReload }} allowsLinkPsreview={true} incognito={true} domStorageEnabled={true} ref={(ref) => this.myWebView = ref}/>
Earlier it was working fine. Suddenly it stop injectjavascript automatically without changing anything.
Still an issue as of 10.3.2.