I'm trying to use the YouTube player package in my React Native TypeScript mobile app but it's throwing an error and I cannot figure out how to fix this issue. I have researched a lot and installed some packages such as deprecated-react-native-prop-types and metro-react-native-babel-preset but still no luck.
In the Google Cloud Platform, I have enabled the YouTube Embedded Player API product in my project and created an API Key in it.
I'm running my application locally on the Android Studio Emulator and is using all the latest packages. Would that have anything to do with it?
My Code:
<YouTube
apiKey = "API KEY HERE"
videoId = "KVZ-P-ZI6W4"
play = {true}
fullscreen = {false}
loop = {false}
onReady={(e): void => { console.log(e); }}
onChangeState={(): void => { console.log(); }}
onChangeQuality={(): void => { console.log(); }}
onError={(e): void => { console.log(e); }}
style={{ alignSelf: 'stretch', height: 300 }}
/>
Error object return on onError:
{"error": "SERVICE_MISSING", "target": 235}
Error popup:
Get YouTube app:
This app won't run without the YouTube App, which is missing from your device.
Related
I was facing issue in React Native when using react-native-pdf to display pdf in App
logs displayed in console:
Error: ReactNativeBlobUtil request error:
java.lang.IllegalStateException: Use of own trust manager but none
definedjava.lang.IllegalStateException: Use of own trust manager but
none defined]
Open Your code and simply use trustAllCerts props and set its value false
as shown below :
<Pdf
trustAllCerts={false}
source={{
uri: pdfUrl,
cache: true,
}}
onLoadComplete={(numberOfPages, filePath) => {
console.log(`Number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
console.log(`Current page: ${page}`);
}}
onError={error => {
console.log(error);
}}
onPressLink={uri => {
console.log(`Link pressed: ${uri}`);
}}
style={styles.pdf}
/>
I'm trying to download file from a web view. I have used javascript inject to click on submit button.
I'm specifically trying this for offline aadhaar - https://resident.uidai.gov.in/offline-kyc
Reference Code -
<WebView
source={{ uri: "https://resident.uidai.gov.in/offline-kyc" }}
ref={webviewRef}
renderLoading={LoadingIndicatorView}
startInLoadingState={true}
injectedJavaScript={runFirst}
onMessage={onMessage}
renderError={loadError}
// onFileDownload={({ nativeEvent: { downloadUrl } }) => {
// console.log(downloadUrl);
// }}
/>
I have tried with api request by creating/replicating the browser behaviour for api call but it's not working. Any suggestions.
You can try react-native-fs
You can use downloadFile API to download and save the file to the device.
I’ve successfully managed to send a message from React Native (RN) to a WebView.
What I’m struggling with, is getting the message back from the WebView to RN. There’s no errors showing - it’s just that the message never gets through.
Here is the code which I’m using:
React Native Code
<WebView
ref={webview => (this.webview = webview)}
source={{ uri: "http://www.my-web-site"}}
onLoadEnd={() => this.onLoadEnd()}
onMessage={this.onMessage}
cacheEnabled={false}
originWhitelist={['*']}
javaScriptEnabled={true}
/>
onLoadEnd() {
this.webview.postMessage("RN message");
}
onMessage(message) {
console.log("I can’t see this message!");
}
WebView Code
document.addEventListener("message", function (event) {
setTimeout(function(){document.postMessage("WebView message")}, 3000);
}, false);
Please make sure that the data for each receiver is in and use the data that You need.
And always check the prescribed documents to see how to use parameters and grammar before using them.
RN
onLoadEnd() {
this.webview.postMessage("sendmessage");
}
onMessage(event) {
alert(event.nativeEvent.data);
}
WebView Code
document.addEventListener("message", function (event) {
window.postMessage(event.data);
});
React-native version 5.0 or later
window.ReactNativeWebView.postMessage(event.data);
Oh, at last, I finally came across the answer. It was a line of code which I had originally been trying to use to send a message from RN to the WebView. Turns out, it was the code required for sending from the WebView to RN:
WebView Code
document.addEventListener("message", function (event) {
window.ReactNativeWebView.postMessage(event.data);
}, false);
RN Code
<WebView onMessage={event => console.log(event.nativeEvent.data)} />
This works.
React Native
<WebView source={{ ... }}
containerStyle={{ ... }}
onMessage={ e => { console.log(e.nativeEvent.data) } }
/>
WebView
if(window.ReactNativeWebView) {
// send data object to React Native (only string)
window.ReactNativeWebView.postMessage(JSON.stringify(dataObject))
}
If you want to send complete object from webview to react-native android app then you need to stringify your object first
// Reactjs webapp
onClickSendObject = (item) => {
if(window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(JSON.stringify(item))
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
In react-native app use onMessage (for functional component)
<WebView
ref={webview => (this.webview = webview)}
source={{ uri: "give source url i.e your webapp link"}}
onMessage={m => onMessage(m.nativeEvent.data)} // functional component and for class component use (this.onMessage)
cacheEnabled={false}
originWhitelist={['*']}
javaScriptEnabled={true}
/>
// onMessage function
const onMessage = (m) => {
const messageData = JSON.parse(m);
console.log(messageData)
}
(window["ReactNativeWebView"] || window).postMessage('hello motiur dear','*');
I have an Expo app using the Managed workflow. The app needs to check whether an internet connection is available.
I can't import { NetInfo } from 'react-native' because that's deprecated.
I can't use react-native-community/react-native-netinfo because that uses native libraries, and you can't do that with an Expo managed app.
I could eject, in order to use the above, but it doesn't seem like I should need to do that just to check if there's an internet connection.
I can't use navigator.onLine because that global variable doesn't seem to be available.
I could make a trivial HTTP request to Google or my own server or whatever, and see if I get a response, but that only tests a connection to one site, and also it takes time and uses bandwidth.
What should I do?
Expo SDK 34 has already included NetInfo API.
You can check their documentation for SDK 34 here https://docs.expo.io/versions/v34.0.0/sdk/netinfo
Here is the link for documentation for latest version
Use NetInfo of react-native.
Yes, it is deprecated because they are planning on removing it in the next version of react-native in favor of the community version. However, it is completely functional and can still be used for now, just make sure to check for breaking changes when the next versions of Expo SDK are released.
It is likely that Expo will bring it into their managed workflow when react-native removes it, or provide an alternative that won't require ejecting from Expo.
It's really hard to define if a device has internet or not stackoverflow.com/a/189443/7602110, just by having failed XHR requests you can say that you have internet, but isn't that reliable. You would like to check with some reliables websites like google.com, I have come with a work-around but I don't actually recommend it, is up to you.
You can use the Linking.canOpenUrl() method from React Native itself, which will return a Promise object. When it is determined whether or not the given URL can be handled, the promise is resolved and the first parameter is whether or not it can be opened.
Then add a request and if the response status it's 200 you should have internet.
import React, { Component } from 'react';
import { Button, Text, View, StyleSheet, Linking } from 'react-native';
export default class App extends Component {
state = {
connection: false,
url: 'https://google.com',
};
checkInternt = () => {
Linking.canOpenURL(this.state.url).then(connection => {
if (!connection) {
this.setState({ connection: false });
} else {
fetch(this.state.url).then(res =>
this.setState({ connection: res.status !== 200 ? false : true })
);
}
});
};
componentDidMount() {
this.checkInternt();
}
handlePress = () => {
this.setState({
url:
this.state.url === 'https://google.com'
? 'http://someweirdurlthatdoesntwork.com'
: 'https://google.com',
});
this.checkInternt();
};
render() {
return (
<View style={styles.container}>
<Text>
Connection:
<Text style={{ color: this.state.connection ? 'green' : 'red' }}>
{` ${this.state.connection}`}
</Text>
</Text>
<Text>{this.state.url.replace(/\https?:\/\//g, '')}</Text>
<Button onPress={this.handlePress} title="Change server url" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
});
Check the snack: snack.expo.io/#abranhe/check-internet
2022 here, had the same issue before ejecting expo, we used expo-network
import * as Network from 'expo-network';
and use it like so
const networkState = await Network.getNetworkStateAsync();
I hope this helps someone!
it is possible to handle URL change on React Native web view.
I try to handle with onNavigationStateChange listener. But it only once time firing. When the page is load firing onNavigationStateChange. And when I navigate to another page, this event not firing.
Any idea?
With the reference to import { WebView } from 'react-native-webview' you may be using old version of webview please try updating or try following code/method to get current navigation path/url.
In your case onNavigationStateChange is not returning navigated path so you can try using onLoadProgress which return every change in url.
Instead of this
onNavigationStateChange={(state) => {
console.log("current_path",path);
}}
try this
This may get called multiple time please handle your condition accordingly.
onLoadProgress={({ path}) => {
console.log("current_path",path);
}}
This is how my WebView looks like
<WebView
source={{ uri: this.state.url }}
onLoadEnd={() => this.hideSpinner()}
onMessage={onMessage.bind(this)}
ref={WEBVIEW_REF => (this.WebViewRef = WEBVIEW_REF)}
startInLoadingState={true}
javaScriptEnabled={true}
domStorageEnabled={true}
onLoadProgress={({ nativeEvent }) => {
//your code goes here
}}
onNavigationStateChange={(state) => {
//your code goes here
}}
/>
Try upgrading your React Native (and React) version.
It should be fixed. Maybe was an old issue, because right now it's working OK.
Check this link: React Native webview get url
onNavigationStateChange={({ url, canGoBack }) => {
console.log("url>>>>>>>>",url);
}}
I load website link in react native WebView and its has button when i click that it navigate to default mobile browser.
Running application in react native android Current scenario: when i click button in website its navigate to default browser and am not getting the url i tried above suggestions.
Expected scenario: When i click that button in website it should not navigate to default browser and i want that url which is opened in default browser.
my react version: "react-native": "0.64.0",
onLoadProgress = {({ nativeEvent }) => {
//your code goes here
}}
onNavigationStateChange={navState => {
console.log("navState ", navState);
}}