Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Webview call React Native function

Is that possible create a function inside the WebView component, trigger React Native function?

like image 638
ChokYeeFan Avatar asked Aug 19 '16 09:08

ChokYeeFan


1 Answers

It's possible but I'm not sure if it's the only way to do this.

Basically you can set an onNavigationStateChange event handler, and embed function call information in navigation url, here's an example of the concept.

In React Native context

render() {

    return <WebView onNavigationStateChange={this._onURLChanged.bind(this)} />
}

_onURLChanged(e) {

    // allow normal the natvigation
    if(!e.url.startsWith('native://'))
        return true
    var payload = JSON.parse(e.url.replace('native://', ''))
    switch(e.functionName) {
        case 'toast' :
            native_toast(e.data)
        break
        case 'camera' :
            native_take_picture(e.data)
        break
    }
    // return false to prevent webview navitate to the location of e.url
    return false

}

To invoke native method, use this just trigger webview's navigation event and embed the function call information in URL.

window.location = 'native://' + JSON.stringify({ 
    functionName : 'toast', data : 'show toast text' 
})
like image 108
Xeijp Avatar answered Sep 21 '22 13:09

Xeijp