11

Anyone knows how (if possible) to execute JS "inside" a WebView in React Native?

The scenario: I have this remote logon page (website) displayed in my WebView, and this website has a sequence of events that happens corresponding to the user activity. All events fire one callback each, which the WebView must listen on (not an issue).
Within each callback there is a reference to a JavaScript function, that must be called inside the WebView (that's the issue!).
So from my React Native app, I need to call this JavaScript function, that's placed on the website page (source) that's loaded in my WebView.

What I have: I listen for the callbacks with onShouldStartLoadWithRequest and manipulate the behaviour of the WebView with this and it works great.
Regarding JavaScript execution I have tried the method getWebViewHandle but that didn't do it, at least not from my seat.
I looked at injectedJavaScript property too, but the problem is that I don't know what JavaScript to execute before the callbacks are fired.

Anyone knows how to solve this?

2 Answers 2

10

November 2018 Update

Webview component now supports injectJavaScript and injectedJavaScript props.

Example:

<WebView
  source={{ uri: 'https://github.com/facebook/react-native' }}
  injectedJavaScript="window.alert('first message')"
  injectJavaScript={() => {
    return "window.alert('second message')";
  }}
/>

Original answer

Calling javascript methods inside a Webview is possible with iOS and Android native components. But required API for javascript execution is currently not provided by react-native. You can see the discussion in this github issue.

However, there is a 3rd party module that's providing bi-directional communication between your app and a Webview. You can start using it after integrating some native code into your project.

Sign up to request clarification or add additional context in comments.

1 Comment

As of Nov 2018, there are parameters available on the Webview React Native component to inject javascript inside the pages.
1

There is now a good article covering how to communicate with content within a React Native Webview using injectJavascript API as well as onMessage/postMessage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.