Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute JavaScript inside WebView source

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?

like image 881
jln-dk Avatar asked May 18 '16 15:05

jln-dk


1 Answers

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.

like image 89
halilb Avatar answered Sep 23 '22 16:09

halilb