Try to inject js like this way:
const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`;
return (
<View style={styles.container}>
<WebView
ref={ref => {
this.webview = ref;
}}
source={{ uri: this.state.webViewUrl }}
originWhitelist={['*']}
injectedJavaScript={jsCode}
/>
</View>
);
}
for more options take a look: Medium: Injecting JavaScript into React Native Webview
Answer from Idan on Stack OverflowTry to inject js like this way:
const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`;
return (
<View style={styles.container}>
<WebView
ref={ref => {
this.webview = ref;
}}
source={{ uri: this.state.webViewUrl }}
originWhitelist={['*']}
injectedJavaScript={jsCode}
/>
</View>
);
}
for more options take a look: Medium: Injecting JavaScript into React Native Webview
A few things off the top of my head:
- In your package.json, react-native version should be
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",(Expo SDK 37 is already based on 0.61.4, but with Expo-specific mods). Getting expo-stripe-checkout working as before in previous versions may be as simple as this. The SDK 37 announcement blog post gives more info on the SDK upgrade process, namely:- Run
expo upgradein your project directory (requires the latest version of expo-cli, you can update withnpm i -g expo-cli). - Make sure to check the changelog for other breaking changes!
- ...
- Run
- If that doesn't help to get
expo-checkout-stripeworking again (fix your React Native version anyway, you're bound to have more issues with Expo if you don't), try one or both of the following with your webview:- Use
injectJavaScriptas per (Guide > Communicating between JS and Native > The injectJavaScript method)[https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method"]. In your case, that would be something likethis.webview.injectJavaScript(jsCode) - Spitballing even more than the previous suggestions, but possibly try wrapping your webview's script tags in html/head/body tags. More due diligence/eliminating variables than anything else.
- Use
I hope one of these suggestions at least gets you on the right path.
Injecting javascript prior to document load
React Native Webview how to use injectJavascript - Stack Overflow
javascript - injectedJavaScript is not working in Webview of react native - Stack Overflow
javascript - React Native Webview - injectJavascript not working - Stack Overflow
Confused, how do I get a string/state from my react native state, and make sure it's inside the javascript injection:
const [token, setToken] = useState("My RN token");And the execution of the webview:
<WebView
source={{html:home}}
javaScriptEnabled={true}
injectedJavaScript={`alert(${token})`}
/>The string interpolation doesn't work. What should I do if I'm trying to pass data from react native into the javascript string that's executed by the webview?
webviewRef.current.injectJavaScript("alert('myToken From React Native')");
Just for some more clarification the alerts were just testing to see if I can interpolate my RN states and their values into the webview code, what I would like to know is, how do I get my client token that I generated from my server, into the injectedJavascript code, for executing a braintree drop in ui:
<WebView
source={{html:home}}
javaScriptEnabled={true}
injectedJavaScript={`
//code executed inside injected Javascript
//my token is inside my RN state, how do you use it here?
braintree.dropin.create({
authorization: 'MY_TOKEN_FROM SERVER',
container: '#dropin-container'
}, function (createErr, instance) {
})
`
}
/>
If you simply want to set global variable, you can use injectedJavaScript prop which will inject your js code into the web page when the view loads. Where you can simply pass js code as string.
And if you want to set global variable from any function then you can do the following: First of all take ref of webview.
<WebView
ref={ref => (this.webview = ref)}
...
/>
then whenever you want to inject js code, do the following:
this.webview.injectJavaScript('window.testMessage = "hello world"; void(0);');
Have a look at link for reference.
https://snack.expo.io/Hke6dJFAW
Please try this:
<WebView
ref={c => this._webview = c}
javaScriptEnabled={true}
injectedJavaScript={`window.testMessage = "hello world"`}
/>
injectedJavaScript is the prop that injects JS into the web view, once, when it loads. This is what you seem to want.
How injectJavascript is used on the other hand? it's by calling it on the ref of the webview to inject more JS programmatically on the fly.
In this case it could look something like this for example:
this.webview.injectJavascript(`window.reactComponent.forceUpdate();true;`)
Add onMessage method does work.
import React, { Component } from 'react';
import { Platform,
StyleSheet,
Text,
View,
WebView
} from 'react-native';
export default class App extends Component<{}> {
render() {
return
<WebView
javaScriptEnabled={true}
injectedJavaScript={'alert("hello")'}
source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }}
onMessage={(event) => {
console.log('event: ', event)
}}
/>;
}
}
Well, you have more than one issue here. First one is your web view needs to be wrapped in a containing View component with flex: 1. Second, injectedJavascript only accepts a string - not a function. Third, it seems you are attempting to use hello as a variable without defining it, or if it is a string than your syntax needs to be something like this: injectedJavascript={'alert("hello")'}. Furthermore, injectedJavascript is already fired when the view loads so you are all good there if that's what you are intending to do. You can inject javascript when the web view starts loading though, using a combination of the props, onLoadStart and injectJavascript, but the implementation is quite different, so that's a different question. Try this code:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
WebView
} from 'react-native';
export default class App extends Component {
render() {
let yourAlert = 'alert("hello")'
return (
<View style={{flex: 1}}>
<WebView
javaScriptEnabled={true}
domStorageEnabled={true}
injectedJavaScript={yourAlert}
source={{ uri: "https://www.google.com" }} style={{ marginTop: 20 }} />
</View>
)
}
}
You should include onMessage={(event) => {}} in the WebView
https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md
An onMessage event is required as well to inject the JavaScript code into the WebView.
<WebView
source={{ uri: "https://www.google.com/" }}
renderLoading={LoadingIndicatorView}
startInLoadingState={true}
javaScriptEnabled={true}
injectedJavaScript={runFirst}
onMessage={(event) => {}}
/>
try
injectedJavaScriptBeforeContentLoaded={injectedJavascript}
https://github.com/react-native-webview/react-native-webview/blob/4d8a76f3691479ef22b55e05c07921af99332395/docs/Guide.md#loading-local-html-files
Look at the official document of the webview and see how to use it. Always refer to official documents when writing modules.
You can use this
const WebAPICode = `alert('Hello')`;
...
<WebView
ref={webView=> this.webView = webView}
originWhitelist={['*']}
source={{ uri: "http://10.0.2.2:3000/" }}
javaScriptEnabled={true}
injectedJavaScript={WebAPICode}
/>
If you have this function on your web, you can call it.
<html>
<head>
<script language="javascript">
function test()
{
alert('Hello');
}
</script>
</head>
<body>
...
const WebAPICode = `test()`;
...
<WebView
ref={webView=> this.webView = webView}
originWhitelist={['*']}
source={{ uri: "http://10.0.2.2:3000/" }}
javaScriptEnabled={true}
injectedJavaScript={WebAPICode}
/>
To execute the data shown in the comments, you have to do this.
Your webview page do this
var data = {name: "getname"}
window.ReactNativeWebView.postMessage(data);
handleMessage(e) {
//여러 데이터가 리스트 형식으로 올때
let parsedata = JSON.parse(e.nativeEvent.data);
message = parsedata.name
if(message == "get name") {
const data = { name: "John" }
this.webview.postMessage(JSON.stringify(data));
}
}
<WebView
ref={webview => (this.webview = webview)}
onMessage={mssage => this.handleMessage(mssage)}
}
Receive webview page
document.addEventListener("message", function(event) {
console.log("Received post message", event);
test(event.data);
}, false);
You can call postMessage from webview and set your webview onMessage props like this.
onMessage={event => { console.log(event) } }
In your webview html:
window.ReactNativeWebView.postMessage("Your Message");