简体   繁体   English

如何在WebView中的注入的javascript中运行React本机代码?

[英]How to run react native code inside injected javascript in webview?

I have a react native function that downloads video by the help of "rn-fetch-blob" and save to document directory which is working fine. 我有一个react native函数,可以通过“ rn-fetch-blob”下载视频并保存到工作正常的文档目录中。

I want to achieve this functionality by the help of webview as it runs in code in separate thread. 我想借助webview来实现此功能,因为它在单独的线程中的代码中运行。

Below is my code: 下面是我的代码:

    downloadVideo() {
        let videoPathToDownload = 'http://XXXXXXXXXXX/0fgqhjcr6my.mp4';
        RNFetchBlob
            .config({
                fileCache: true,
                appendExt: 'mp4'
            })
            .fetch('GET', videoPathToDownload)
            .then((res) => {
                console.log('The file saved to ', res.path())
            })
    }


    render() {
        return (
            <View style={{flex: 1}}>
            <WebView
                javaScriptEnabled={true}
                domStorageEnabled={true}
                injectedJavaScript={}
                source={{ uri: "https://www.google.com" }} 
                style={{ marginTop: 20  }} 
             />
            </View>
        );
    }

I want to call the downloadVideo() function from webview inside injectedJS or by any means possible. 我想从InjectionJS内的webview调用downloadVideo()函数,或通过任何可能的方法调用。

Please Help. 请帮忙。

Use react native WebView: 使用react native WebView:

<WebView
    ref={(ref) => { this.webview = ref; }}
    source={{ uri: this.state.webViewUrl }}
    originWhitelist={['*']}
    javaScriptEnabledAndroid={true}
    injectedJavaScript={jsCode}
    onMessage={this._onMessage} // only if you want connection back
/>

and you can pass js code: 您可以传递js代码:

const jsCode = `
    document.querySelector('button').addEventListener("click", function() {  
        alert('Hello Web')
    }); 
    true;
    `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM