1 | import { Linking, NativeModules, Platform } from 'react-native';
|
2 | const { ExponentWebBrowser } = NativeModules;
|
3 | async function openBrowserAsync(url) {
|
4 | return ExponentWebBrowser.openBrowserAsync(url);
|
5 | }
|
6 | function dismissBrowser() {
|
7 | ExponentWebBrowser.dismissBrowser();
|
8 | }
|
9 | async function openAuthSessionAsync(url, redirectUrl) {
|
10 | if (_authSessionIsNativelySupported()) {
|
11 | return ExponentWebBrowser.openAuthSessionAsync(url, redirectUrl);
|
12 | }
|
13 | else {
|
14 | return _openAuthSessionPolyfillAsync(url, redirectUrl);
|
15 | }
|
16 | }
|
17 | function dismissAuthSession() {
|
18 | if (_authSessionIsNativelySupported()) {
|
19 | ExponentWebBrowser.dismissAuthSession();
|
20 | }
|
21 | else {
|
22 | ExponentWebBrowser.dismissBrowser();
|
23 | }
|
24 | }
|
25 |
|
26 | function _authSessionIsNativelySupported() {
|
27 | if (Platform.OS === 'android') {
|
28 | return false;
|
29 | }
|
30 | const versionNumber = parseInt(String(Platform.Version), 10);
|
31 | return versionNumber >= 11;
|
32 | }
|
33 | let _redirectHandler = null;
|
34 | async function _openAuthSessionPolyfillAsync(startUrl, returnUrl) {
|
35 | if (_redirectHandler) {
|
36 | throw new Error(`The WebBrowser's auth session is in an invalid state with a redirect handler set when it should not be`);
|
37 | }
|
38 | try {
|
39 | return await Promise.race([openBrowserAsync(startUrl), _waitForRedirectAsync(returnUrl)]);
|
40 | }
|
41 | finally {
|
42 | dismissBrowser();
|
43 | if (!_redirectHandler) {
|
44 | throw new Error(`The WebBrowser auth session is in an invalid state with no redirect handler when one should be set`);
|
45 | }
|
46 | Linking.removeEventListener('url', _redirectHandler);
|
47 | _redirectHandler = null;
|
48 | }
|
49 | }
|
50 | function _waitForRedirectAsync(returnUrl) {
|
51 | return new Promise(resolve => {
|
52 | _redirectHandler = (event) => {
|
53 | if (event.url.startsWith(returnUrl)) {
|
54 | resolve({ url: event.url, type: 'success' });
|
55 | }
|
56 | };
|
57 | Linking.addEventListener('url', _redirectHandler);
|
58 | });
|
59 | }
|
60 | export default {
|
61 | openBrowserAsync,
|
62 | openAuthSessionAsync,
|
63 | dismissBrowser,
|
64 | dismissAuthSession,
|
65 | };
|
66 |
|
\ | No newline at end of file |