2020-02-19 20:52:05 +00:00
|
|
|
import { Linking } from 'react-native';
|
2019-06-21 16:39:20 +00:00
|
|
|
import * as WebBrowser from 'expo-web-browser';
|
2020-02-19 20:52:05 +00:00
|
|
|
import parse from 'url-parse';
|
2019-06-21 16:39:20 +00:00
|
|
|
|
2022-06-06 14:17:51 +00:00
|
|
|
import { themes } from '../../constants';
|
|
|
|
import { TSupportedThemes } from '../../../theme';
|
|
|
|
import UserPreferences from '../userPreferences';
|
2023-03-18 15:31:04 +00:00
|
|
|
import ensureSecureProtocol from './ensureSecureProtocol';
|
2019-06-21 16:39:20 +00:00
|
|
|
|
2020-02-19 20:52:05 +00:00
|
|
|
export const DEFAULT_BROWSER_KEY = 'DEFAULT_BROWSER_KEY';
|
|
|
|
|
|
|
|
const scheme = {
|
|
|
|
chrome: 'googlechrome:',
|
|
|
|
chromeSecure: 'googlechromes:',
|
|
|
|
firefox: 'firefox:',
|
|
|
|
brave: 'brave:'
|
|
|
|
};
|
|
|
|
|
2022-01-12 12:54:04 +00:00
|
|
|
const appSchemeURL = (url: string, browser: string): string => {
|
2020-02-19 20:52:05 +00:00
|
|
|
let schemeUrl = url;
|
|
|
|
const parsedUrl = parse(url, true);
|
|
|
|
const { protocol } = parsedUrl;
|
|
|
|
const isSecure = ['https:'].includes(protocol);
|
|
|
|
|
|
|
|
if (browser === 'googlechrome') {
|
|
|
|
if (!isSecure) {
|
|
|
|
schemeUrl = url.replace(protocol, scheme.chrome);
|
|
|
|
} else {
|
|
|
|
schemeUrl = url.replace(protocol, scheme.chromeSecure);
|
|
|
|
}
|
|
|
|
} else if (browser === 'firefox') {
|
2021-09-13 20:41:05 +00:00
|
|
|
schemeUrl = `${scheme.firefox}//open-url?url=${url}`;
|
2020-02-19 20:52:05 +00:00
|
|
|
} else if (browser === 'brave') {
|
2021-09-13 20:41:05 +00:00
|
|
|
schemeUrl = `${scheme.brave}//open-url?url=${url}`;
|
2020-02-19 20:52:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return schemeUrl;
|
|
|
|
};
|
|
|
|
|
2022-04-12 16:27:05 +00:00
|
|
|
const openLink = async (url: string, theme: TSupportedThemes = 'light'): Promise<void> => {
|
2023-03-18 15:31:04 +00:00
|
|
|
url = ensureSecureProtocol(url);
|
2020-02-19 20:52:05 +00:00
|
|
|
try {
|
2022-03-09 19:41:26 +00:00
|
|
|
const browser = UserPreferences.getString(DEFAULT_BROWSER_KEY);
|
2021-07-12 19:19:25 +00:00
|
|
|
if (browser === 'inApp') {
|
2020-02-19 20:52:05 +00:00
|
|
|
await WebBrowser.openBrowserAsync(url, {
|
|
|
|
toolbarColor: themes[theme].headerBackground,
|
|
|
|
controlsColor: themes[theme].headerTintColor,
|
2022-01-12 12:54:04 +00:00
|
|
|
// https://github.com/expo/expo/pull/4923
|
|
|
|
enableBarCollapsing: true,
|
2020-02-19 20:52:05 +00:00
|
|
|
showTitle: true
|
|
|
|
});
|
2021-07-12 19:19:25 +00:00
|
|
|
} else {
|
2022-01-12 12:54:04 +00:00
|
|
|
const schemeUrl = appSchemeURL(url, browser!.replace(':', ''));
|
2021-07-12 19:19:25 +00:00
|
|
|
await Linking.openURL(schemeUrl);
|
2020-02-19 20:52:05 +00:00
|
|
|
}
|
|
|
|
} catch {
|
|
|
|
try {
|
|
|
|
await Linking.openURL(url);
|
|
|
|
} catch {
|
|
|
|
// do nothing
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-06-21 16:39:20 +00:00
|
|
|
|
|
|
|
export default openLink;
|