react-native-webview: 'injectJavaScript' method not working on Android in v11.22.0 or greater

I have a WebView setup to communicate with the app rendered inside of it. Everything works fine in v11.21.2. But it stops working in v11.22.0 or greater. I saw one error in my app when running Jest tests related to the new version of react-native-webview, but nothing blows up.

The WebView itself seems to load just fine when running the app, but its blank. After trying to debug through the issue, I realized that communications from the HTML inside the WebView were being recieved by the WebView, but messages from the host/WebView were not getting to the HTML app inside the WebView.

It looks like the injectJavaScript command is not working on Android anymore. It works fine on iOS.

I cannot upgrade to the new version until that works again.

This is the line of code I am using to send messages to the nested app which no longer seems to work on Android.

// post messages to the WebView. webViewRef is the WebView reference saved on the class instance.
this.webViewRef.injectJavaScript(`window.postMessage(${JSON.stringify(payload)}, '*');`);

This is the error I saw when running Jest tests for Android only. iOS/Web tests passed.

TypeError: Cannot read property 'isFileUploadSupported' of undefined

Again, this only happens when upgrading to v11.22.0 or greater.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 7
  • Comments: 16

Most upvoted comments

I was also facing TypeError: Cannot read property 'isFileUploadSupported' of undefined after updating react-native-webview above v11.22.0.

The corresponding change (remove static from function definition) was made in: https://github.com/react-native-webview/react-native-webview/pull/2508/files#diff-8576be466ba1cccbe7c11ba839c58655910cfcea677ad1de381d2a5194089ad8R209

However this causes jest to fail when testing the library, as it requires NativeModules to be mocked. With help of react-native/issues/28839#issuecomment-625453688 I was able to write a jest-mock, for tests to pass.

Here is the snippet (put it in __mocks__/react-native.js):

jest.mock('react-native', () => {
	// use original implementation, which comes with mocks out of the box
	const ReactNative = jest.requireActual('react-native')

	// mock modules/components created by assigning to NativeModules
	ReactNative.NativeModules.RNCWebView = {
		// mock for react-native-webview (android)
		isFileUploadSupported: jest.fn(),
	}

	return ReactNative
})

This should be added as a breaking hint in release-notes of v11.22.0

@rafaelmaeuer Since we use some imports inside our jestSetupFile.js I ended up having to put that code snippet inside that file. But aside from that difference it worked perfectly.

Jest tests are passing without issues now.