简体   繁体   中英

React Native Webview not resetting injected JavaScript

I have to retrieve the html content of the WebView when a certain URL is reached. To do this I inject window.postMessage(document.documentElement.innerHTML); using the injectJavaScript function provided by the WebView component when this URL is reached.

This works fine the first time, but when trying the same thing again after a restart, redirects are not handled and the injectedJavaScript is called at the first page as if it was never removed. This behaviour is present on iOS, not on Android.

Anyone encountered the same problem or has a fix for this?

Use react-native-webview package:

import { WebView } from '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:

const jsCode = `
document.querySelector('button.btn-success').addEventListener("click", function() {  
    window.ReactNativeWebView.postMessage(JSON.stringify({type: "click", message : "ok"}));
}); 
true;
`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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