UNPKG

1.68 kBPlain TextView Raw
1/*
2 * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5 * the License. A copy of the License is located at
6 *
7 * http://aws.amazon.com/apache2.0/
8 *
9 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11 * and limitations under the License.
12 */
13import { ConsoleLogger as Logger } from '@aws-amplify/core';
14const logger = new Logger('urlListener');
15
16let handler;
17
18export default async callback => {
19 if (handler) {
20 return;
21 }
22
23 let Linking: any;
24 let AppState: any;
25 let subscription;
26 try {
27 ({ Linking, AppState } = require('react-native'));
28 } catch (error) {
29 /* Keep webpack happy */
30 }
31
32 handler =
33 handler ||
34 (({ url, ...rest }: { url: string }) => {
35 logger.debug('urlListener', { url, ...rest });
36 callback({ url });
37 });
38
39 // Handles backward compatibility. removeEventListener is only available on RN versions before 0.65.
40 if (Linking.removeEventListener === typeof 'function') {
41 Linking.removeEventListener('url', handler);
42 Linking.addEventListener('url', handler);
43 } else {
44 // remove() method is only available on RN v0.65+.
45 subscription?.remove?.();
46 subscription = Linking.addEventListener('url', handler);
47 }
48 AppState.addEventListener('change', async newAppState => {
49 if (newAppState === 'active') {
50 const initialUrl = await Linking.getInitialURL();
51 handler({ url: initialUrl });
52 }
53 });
54};