I am building an app using react-native. I am using react native's Linking API to open my website link in the metamask app installed on my phone. The Linking.opneURl(url) works fine if metamask app is installed on the device. The problem is that if Metamask is not installed on the device it opens the link in the browser.
What I want to do is to apply a check that if the Metamsk app is not installed on the device the user will be asked to install the app otherwise it should open normally in the metamask app. So far I have used the linking API and the react-native-check-app but I didn't get the result I wanted.
Please refer to this section in the official documentation. Extracted from the documentation:
Determine whether or not an installed app can handle a given URL. The method returns 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.
You then could go on to practical usage like this:
const isInstalled = await Linking.canOpenURL("yourUrl");
You need to open your link from mobile application through metamask mobile application browser. The way we know for now you can linking url to metamask with Linking which is built-in feature react native. After click button then choice of metamask will open metamask-auth.ilamanov.repl.co as http://metamask-auth.ilamanov.repl.co at metamask browser. After click connect wallet you can choose metamask mobile application and after browsing it self your dApp link it can auth with metamask.
import React, { useCallback } from "react";
import { Alert, Button, Linking, StyleSheet, View } from "react-native";
const yourDappLink = "metamask-auth.ilamanov.repl.co" // change or create yourself
const supportedURL = "https://metamask.app.link/dapp/"+yourDappLink;
const OpenURLButton = ({ url, children }) => {
const handlePress = useCallback(async () => {
// Checking if the link is supported for links with custom URL scheme.
const supported = await Linking.canOpenURL(url);
if (supported) {
// Opening the link with some app, if the URL scheme is "http" the web link should be opened
// by some browser in the mobile
await Linking.openURL(url);
} else {
Alert.alert(`Don't know how to open this URL: ${url}`);
}
}, [url]);
return <Button title={children} onPress={handlePress} />;
};
const App = () => {
return (
<View style={styles.container}>
<OpenURLButton url={supportedURL}>Connect Wallet</OpenURLButton>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: "center", alignItems: "center" },
});
export default App;
Related
I have a credit card addition system with 3DS security enabled.
To achieve that, I have to open a browser to the bank 3DS system.
As the user has the possibility to close the opened browser tab, I have to be able to detect this event and reset the loading state.
I did it that way:
client.service('credit-cards')
.patch(creditCardRef.current._id, {
registrationId: creditCardRef.current.registrationId,
registrationData: registrationDataRef.current,
registrationIpAddress: ipAddressRef.current,
// #ts-expect-error Unable to set the type of the parsed query.
registrationBrowserInfo: {
...parsedUrl.query,
acceptHeader: headersRef.current.accept,
},
secureModeRedirectUrl: Linking.createURL('paybox-3ds', {
queryParams: { creditCardId: creditCardRef.current._id },
}),
})
.then(ResultHelpers.toOne)
.then((result) => WebBrowser.openBrowserAsync(result.secureModeUrl, {
// #see https://github.com/expo/expo/issues/8072#issuecomment-621173298
showInRecents: true,
}))
.then((browserResult: WebBrowser.WebBrowserResult): void => {
// On IOS check if the user manually closed the browser using "Done" browser button
if (browserResult.type === 'cancel') {
setLoading(false);
}
})
.catch((error) => {
handleCreditCardRegistrationError(error);
});
This is working, but only for iOS. Indeed, the official documentation says:
The promise behaves differently based on the platform.
On Android promise resolves with {type: 'opened'} if we were able to
open browser.
On iOS: If the user closed the web browser, the Promise resolves with
{ type: 'cancel' }.
What is my alternative for Android?
I already created a web-view android app from my website.
I added Web Share API code to my website to load share button on android browser (It works fine) but when I visit my website through the android app, share button doesn't work (Nothing happens when I press the button).
Any idea to solve the problem? Is it possible?
Web Share API Code
<button id="btn-share">Share</button>
<script>
window.addEventListener('load', function() {
if(!navigator.share) {
document.querySelector('.share-container').innerHTML = 'Web Share API not supported in this browser';
return;
}
document.getElementById('btn-share').addEventListener('click', function() {
navigator.share({
title: 'Check out this web share API demo',
text: 'Its really cool',
url: 'https://mobiforge.github.io/web-share-api.html',
});
});
});
</script>
Navigator.share API not supports in WebView. You can use it only in mobile browsers except Firefox.
Web share is not yet support for browser but you can use fall back method.
if (navigator.share) {
navigator.share({
title: 'harish tech',
text: 'Check out harishtech.com.',
url: 'https://harishtech.com', })
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
}else{
// Your fall back code here
}
For more info check out the link share like native app
I'd like for users to be able to share a link (e.g. app.com/SKFLA - this is primarily because deep links on their own aren't clickable) via Facebook etc. When clicked, this redirects to a deep link app://SKFLA. If the app is installed, this opens the app - this is all working fine so far. But if the app isn't installed, I'd like to open the app store on the relevant page. Is this achievable? Thanks!
You need UNIVERSAL LINKS
Please check
IOS https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html
Android
https://developer.android.com/training/app-links/
It might also require some extra server-side setup.
Not sure about native behavior.
We used third-party service like https://branch.io/deepviews/.
There is a bunch of similar services.
If someone is still stuck in this issue and needs easiest solution, you will love node-deeplink
1.) If app is installed: Calling an app through deep linking will always call componentDidMount of root component. So you can attach a listener there. Like:
Linking.getInitialURL()
.then(url => {
if (url) {
this.handleOpenURL({ url });
}
})
.catch(console.error);
Linking.addEventListener('url', this.handleOpenURL);
handleOpenURL(event) {
if (event) {
console.log('event = ', event);
const url = event.url;
const route = url.replace(/.*?:\/\//g, '');
console.log('route = ', route);
if(route.match(/\/([^\/]+)\/?$/)) {
const id = route.match(/\/([^\/]+)\/?$/)[1];
const routeName = route.split('/')[0];
if (routeName === 'privatealbum') {
Actions.privateAlbum({ albumId: id });
}
}
}
}
2.) If app is not installed: Just set up a route in your server and node-deeplink package will handle the bridging between web browser to app store when a app is not installed in your mobile.
By this, both the cases will be handled without any struggle
I have a button and I want to open a facebook page in the facebook app. I can use this solution to open the link in a browser but I'm looking for a better solution that opens faecbook app and my desire page. Is this generally possible? How?
This may not be possible on Android but to do so you follow essentially the same instructions for linking, you just need to swap out http with fb (or the appropriate app id). This SO answer has a bit more information on what may or may not be possible.
Assuming it is possible, to open the facebook app to a profile it would look something like this
const pageId = 'abc123'
Linking.openURL(`fb://profile/${pageId}`)
.catch(err => console.error('An error occurred', err));
Notice that rather than using http I'm using fb
Same as solution of #Spencer answered, but using page instead profile to open fanpage.
<Button
title="Go to Facebook page"
onPress={() => {
const FANPAGE_ID = 'xxxxxxxxxxxxxxxxx'
const FANPAGE_URL_FOR_APP = `fb://page/${FANPAGE_ID}`
const FANPAGE_URL_FOR_BROWSER = `https://fb.com/${FANPAGE_ID}`
Linking.canOpenURL(FANPAGE_URL_FOR_APP)
.then((supported) => {
if (!supported) {
Linking.openURL(FANPAGE_URL_FOR_BROWSER)
} else {
Linking.openURL(FANPAGE_URL_FOR_APP)
})
.catch(err => console.error('An error occurred', err))
}}
/>
Note: You MUST use fanpage ID, not fanpage slug name. If you don't know how to get id, just open your fanpage in browser, view source and find page_id param.
A mix of answers from #Spencer and #Thành worked for me on iOS.
So I settled for just attempting to open the Facebook app link, and then if that fails I fall back to the web browser link, like so:
import { Linking } from "react-native";
const openFacebookLink = facebookId => {
const FANPAGE_URL_FOR_APP = `fb://profile/${facebookId}`;
const FANPAGE_URL_FOR_BROWSER = `https://fb.com/${facebookId}`;
Linking.canOpenURL(FANPAGE_URL_FOR_APP)
.then(appSupported => {
if (appSupported) {
console.log(`Can handle native url: ${FANPAGE_URL_FOR_APP}`);
return Linking.openURL(FANPAGE_URL_FOR_APP);
} else {
console.log(
`Can't handle native url ${FANPAGE_URL_FOR_APP} defaulting to web URL ${FANPAGE_URL_FOR_BROWSER}`
);
return Linking.canOpenURL(FANPAGE_URL_FOR_BROWSER).then(
webSupported => {
if (webSupported) {
console.log(`Can handle web url: ${FANPAGE_URL_FOR_BROWSER}`);
return Linking.openURL(FANPAGE_URL_FOR_BROWSER);
}
return null;
}
);
}
})
.catch(err => console.error("An error occurred", err));
};
Note: the appSupported variable here will always return false until you've edited/added the LSApplicationQueriesSchemes value in your info.plist file. You'll find this file in the ios/yourappname sub-folder of your project. Here are the lines that I added to mine:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fb</string>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
NB: if you're using Create React Native App and/or Expo then you won't be able to edit this file. I abandoned Expo for this reason.
That works on iOS for me, but Android opens it in the browser every time. I've read that Android handles this stuff completely differently to iOS, so I'm not sure if there's any easy solution there.
How to open other apps (Gmail, Camera) from ReactNative. How can I pass data from current scene to other app?
I found this npm library react-native-app-link which can open other apps. This is based on deep linking, if you have any deep links then this library can help. This doesn't open apps just by giving the android package name or ios app id.
https://github.com/FiberJW/react-native-app-link
you can mange opening other apps using Linking
Code sample for opening the dialer
const urlToOpen = 'tel:1234567890';
Linking.openURL(urlToOpen);
You can refer to the official doc here, it just predefines some applications, which can be opened.
However, if the question is about to open just about any application, I hope there is no solution till now.
react-native-app-link has some redundant config (e.g. appStoreLocale parameter), so I wrote my own realization using their code:
import { Alert, Platform, ToastAndroid } from 'react-native';
const isIos = Platform.OS === 'ios';
const showNotification = (text) => isIos
? Alert.alert(text)
: ToastAndroid.show(text, ToastAndroid.SHORT);
const openApp = ({ url, appStoreId, playMarketId, name }) => {
Linking.openURL(url).catch(err => {
if (err.code === 'EUNSPECIFIED') {
Linking.openURL(
isIos
? `https://apps.apple.com/app/id${appStoreId}`
: `https://play.google.com/store/apps/details?id=${playMarketId}`,
);
} else {
showNotification(`Can't open ${name} app`);
}
});
};
It tries to open the app by the specified link, and if the user doesn't have such one, it opens its page in AppStore or Play Market.