I injected a piece of JS code into WebView in React-Native. I want to call this js code on my web page (using React), just like using the API in the program, but I failed.
This is my current code:
const WebAPICode = `
function test() {
alert('Hello');
}
`;
export default class PluginView extends Component {
render() {
return (
<View {...this.props}>
<WebView
ref={webView=> this.webView = webView}
originWhitelist={['*']}
source={{ uri: "http://10.0.2.2:3000/" }}
onLoadEnd={()=>this.webView.injectJavaScript(WebAPICode)}
/>
<Text>{WebAPICode}</Text>
</View>
);
}
}
I want to call it in React, but this is obviously the wrong way. I still don't know how to implement it after checking a lot of information.
function App() {
return (
<span onClick={()=>test()}>test</span>
);
}
Just like the setTimeout function, there is no such function in the js standard, but the browser adds it to the window object, window.setTimeout, and I also want to add my own defined function to the webview, just like test.
Inject the test function into this webview instead of writing it in the script tag.
<html lang="en">
<head>
<script>
// The function is defined here, but I want this
// definition to be injected into the browser
function test() {
alert('hello');
}
/**
* This is what I want:
* <WebView injectedJavaScript={`function test() {
* alert('hello');
* }`}/>
* Inject the test function into this webview instead
* of writing it in the script tag.
*/
</script>
</head>
<body>
<script>
test();
</script>
</body>
</html>