简体   繁体   English

React Native Webview不重置注入的JavaScript

[英]React Native Webview not resetting injected JavaScript

I have to retrieve the html content of the WebView when a certain URL is reached. 当到达某个URL时,我必须检索WebView的html内容。 To do this I inject window.postMessage(document.documentElement.innerHTML); 为此,我注入window.postMessage(document.documentElement.innerHTML); using the injectJavaScript function provided by the WebView component when this URL is reached. 到达此URL时,使用WebView组件提供的injectJavaScript函数。

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. 第一次可以很好地工作,但是在重新启动后再次尝试执行相同的操作时,将不处理重定向,并且在首页上调用注入的JavaScript,就像从未删除过一样。 This behaviour is present on iOS, not on Android. 此行为存在于iOS上,而不存在于Android上。

Anyone encountered the same problem or has a fix for this? 任何人都遇到相同的问题或对此有解决办法?

Use react-native-webview package: 使用react-native-webview包:

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: 您可以传递js代码:

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

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

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