链接到其他应用

了解如何根据另一个应用的 URL 方案处理和打开应用中的 URL。


通过使用目标应用的 URL,可以处理从你的应用链接到其他应用。你可以使用两种方法从你的应用打开此类 URL:

¥Handling linking into other apps from your app is achieved by using the target app's URL. There are two methods you can use to open such URLs from your app:

使用旧版 FileSystem API

¥Using expo-linking API

expo-linking API 提供了对原生链接 API(例如 Web 上的 window.history)的通用抽象,并为你的应用提供了与其他已安装应用交互的实用程序。

¥The expo-linking API provides a universal abstraction over native linking APIs (such as window.history on the web) and offers utilities for your app to interact with other installed apps.

以下示例使用 Linking.openURL 在操作系统的默认浏览器中打开 通用 URL 方案

¥The example below opens a the common URL scheme in the default browser of the operating system using Linking.openURL:

index.tsx
import { Button, View, StyleSheet } from 'react-native';
import * as Linking from 'expo-linking';

export default function Home() {
  return (
    <View style={styles.container}>
      <Button title="Open a URL" onPress={() => Linking.openURL('https://expo.dev/')} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

在 Expo Router 应用中使用 React Server Components

¥Using Expo Router's Link component

如果你的项目使用 Expo 路由,请使用 Link 组件打开 URL。它在原生平台上封装一个 <Text> 组件,在 Web 上封装一个 <a> 元素。它还使用 expo-linking API 来处理 URL 方案。

¥If your project uses Expo Router, use the Link component to open a URL. It wraps a <Text> component on native platforms and an <a> element on the web. It also uses the expo-linking API to handle URL schemes.

以下示例在操作系统的默认浏览器中打开 通用 URL 方案 (HTTPS):

¥The example below opens a common URL scheme (HTTPS) in the default browser of the operating system:

index.tsx
import { Button, View, StyleSheet } from 'react-native';
import { Link } from 'expo-router';

export default function Home() {
  return (
    <View style={styles.container}>
      <Link href="https://expo.dev">Open a URL</Link>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

常见 URL 方案

¥Common URL schemes

有内置的 URL 方案,可在所有平台上提供对核心功能的访问。以下是常用方案列表:

¥There are built-in URL schemes that provide access to core functionality on all platforms. Here is a list of commonly-used schemes:

方案描述示例
https / http打开网络浏览器应用。https://expo.dev
mailto打开邮件应用。mailto:support@expo.dev
tel打开调用应用。tel:+123456789
sms打开短信应用。sms:+123456789
Specify Android intents to handle common URL schemes

对于 Android 11(API 级别 30)及以上版本,你必须在 AndroidManifest.xml 文件中指定应用将处理的意图。你可以通过 创建配置插件 实现这一点。

¥For Android 11 (API level 30) and above, you must specify the intents your app will handle in the AndroidManifest.xml file. You can accomplish this by creating a config plugin.

以下配置插件示例通过定义意图启用到电子邮件和调用应用的链接:

¥The following config plugin example enables linking to email and phone apps by defining the intents:

my-plugin.ts
import { withAndroidManifest, ConfigPlugin } from 'expo/config-plugins';

const withAndroidQueries: ConfigPlugin = config => {
  return withAndroidManifest(config, config => {
    config.modResults.manifest.queries = [
      {
        intent: [
          {
            action: [{ $: { 'android:name': 'android.intent.action.SENDTO' } }],
            data: [{ $: { 'android:scheme': 'mailto' } }],
          },
          {
            action: [{ $: { 'android:name': 'android.intent.action.DIAL' } }],
          },
        ],
      },
    ];

    return config;
  });
};

module.exports = withAndroidQueries;

plugins 属性下创建配置插件 导入自定义配置插件 后:

¥After creating the config plugin, 导入自定义配置插件 under the plugins property:

app.json
{
  "expo": {
    "plugins": [
      "./my-plugin.ts"
      %%placeholder-start%%... %%placeholder-end%%
    ]
  }
}
提示:在 Android 上,你可以使用 expo-intent-launcher 在设备上打开特定的设置屏幕。查看 expo-intent-launcher API 参考 以查看可用意图列表。

自定义 URL 方案

¥Custom URL schemes

如果你知道要打开的应用的自定义方案,则可以使用以下任何方法链接到它:使用 expo-linking API使用 Expo Router 中的 Link

¥If you know the custom scheme for the app you want to open, you can link to it using any of the methods: Using expo-linking API or Using Link from Expo Router.

一些服务提供了有关如何使用其应用的自定义 URL 方案的文档。例如,Uber 深度链接文档 描述了如何直接链接到特定的接送地点和目的地:

¥Some services provide documentation on how to use their app's custom URL schemes. For example, Uber's deep linking documentation describes how to link directly to a specific pickup location and destination:

uber://?client_id=<CLIENT_ID>&action=setPickup&pickup[latitude]=37.775818&pickup[longitude]=-122.418028&pickup[nickname]=UberHQ&pickup[formatted_address]=1455%20Market%20St%2C%20San%20Francisco%2C%20CA%2094103&dropoff[latitude]=37.802374&dropoff[longitude]=-122.405818&dropoff[nickname]=Coit%20Tower&dropoff[formatted_address]=1%20Telegraph%20Hill%20Blvd%2C%20San%20Francisco%2C%20CA%2094133&product_id=a1111c8c-c720-46c3-8534-2fcdd730040d&link_text=View%20team%20roster&partner_deeplink=partner%3A%2F%2Fteam%2F9383

在上面的例子中,如果用户的设备上没有安装 Uber 应用,你的应用可以将他们引导到 Google Play Store 或 Apple App Store 进行安装。我们建议使用 react-native-app-link 库来处理这些场景。

¥In the example above, if the user does not have the Uber app installed on their device, your app can direct them to the Google Play Store or Apple App Store to install it. We recommend using the react-native-app-link library to handle these scenarios.

Specify custom schemes for iOS

在 iOS 上,使用 Linking.canOpenURL 查询其他应用的链接方案需要在 InfoPlist 中进行额外配置。你可以在应用配置中使用 ios.infoPlist 属性来指定你的应用可以查询的方案列表。例如:

¥On iOS, using Linking.canOpenURL to query other apps's linking schemes requires additional configuration in InfoPlist. You can use the ios.infoPlist property in your app config to specify a list of schemes your app is allowed to query. For example:

app.json
{
  "expo": {
    "ios": {
      "infoPlist": {
        "LSApplicationQueriesSchemes": ["uber"]
      }
    }
  }
}

如果你未指定此列表,即使设备已安装目标应用,Linking.canOpenURL 也可能会返回 false

¥If your don't specify this list, Linking.canOpenURL may return false even if the device has the target app installed.

提示:要从 iOS 设备测试上述配置,请使用 使用开发版本。它无法使用 Expo Go 进行测试。

创建 URL

¥Create URLs

你可以使用 Linking.createURL 创建可用于打开或重定向回你的应用的 URL。此方法解析为以下内容:

¥You can use Linking.createURL to create a URL that can be used to open or redirect back to your app. This method resolves to the following:

  • 生产和开发版本:myapp://,其中 myapp 是应用配置中定义的 自定义方案

    ¥Production and development builds: myapp://, where myapp is the custom scheme defined in the app config

  • Expo Go 中的开发:exp://127.0.0.1:8081

    ¥Development in Expo Go: exp://127.0.0.1:8081

使用 Linking.createURL 可帮助你避免硬编码 URL。你可以通过将可选参数传递给此方法来修改返回的 URL。

¥Using Linking.createURL helps you avoid hardcoding URLs. You can modify the returned URL by passing optional parameters to this method.

要将数据传递给你的应用,你可以将其作为路径或查询字符串附加到 URL。Linking.createURL 将自动构建一个工作 URL。例如:

¥To pass data to your app, you can append it as a path or query string to the URL. Linking.createURL will construct a working URL automatically. For example:

Example
const redirectUrl = Linking.createURL('path/into/app', {
  queryParams: { hello: 'world' },
});

这将根据环境解析为以下内容:

¥This will resolve into the following, depending on the environment:

  • 生产和开发版本:myapp://path/into/app?hello=world

    ¥Production and development builds: myapp://path/into/app?hello=world

  • Expo Go 中的开发:exp://127.0.0.1:8081/--/path/into/app?hello=world

    ¥Development in Expo Go: exp://127.0.0.1:8081/--/path/into/app?hello=world

Using Expo Go for testing?

对于需要稳定 URL 的应用(例如,身份验证提供程序重定向),请使用具有自定义方案的开发版本,而不是使用 Expo Go。有关如何创建和测试自定义方案的更多详细信息,请参阅 链接到你的应用

¥For apps that require a stable URL (for example, auth provider redirects), use a development build with a custom scheme instead of using Expo Go. For more details on how to create and test a custom scheme, see Linking into your app.

应用内浏览器

¥In-app browsers

expo-linking API 允许你使用操作系统的默认 Web 浏览器应用打开 URL。你可以使用 expo-web-browser 库在应用内浏览器中打开 URL。例如,应用内浏览器对于安全 authentication 很有用。

¥The expo-linking API allows you to open a URL using the operating system's default web browser app. You can use the expo-web-browser library to open URLs in an in-app browser. For example, an in-app browser is useful for secure authentication.

Example of opening a URL in an in-app browser

以下示例模拟使用 expo-web-browser 在应用内浏览器中打开 URL 的行为,并使用 expo-linking 在默认或首选 Web 浏览器中打开 URL:

¥The example below simulates the behavior of opening a URL in an in-app browser using expo-web-browser and the default or preferred web browser using expo-linking:

WebBrowser compared to Linking
import { Button, View, StyleSheet } from 'react-native';
import * as Linking from 'expo-linking';
import * as WebBrowser from 'expo-web-browser';

export default function Home() {
return (
  <View style={styles.container}>
    <Button
      title="Open URL with the system browser"
      onPress={() => Linking.openURL('https://expo.dev')}
      style={styles.button}
    />
    <Button
      title="Open URL with an in-app browser"
      onPress={() => WebBrowser.openBrowserAsync('https://expo.dev')}
      style={styles.button}
    />
  </View>
);
}

const styles = StyleSheet.create({
container: {
  flex: 1,
  alignItems: 'center',
  justifyContent: 'center',
},
button: {
  marginVertical: 10,
},
});

网络上的其他链接功能

¥Additional link functionality on web

要在 Web 上提供其他链接功能,例如右键单击复制或悬停预览,你可以使用 expo-router 库中的 Link 组件。

¥To provide additional link functionality on the web, such as right-click to copy or hover to preview, you can use a Link component from the expo-router library.

index.tsx
import { Link } from 'expo-router';

export default function Home() {
  return <Link href="https://expo.dev">Go to Expo</Link>;
}

或者,你可以使用 @expo/html-elements 库来使用通用 <A> 元素:

¥Alternatively, you can use the @expo/html-elements library to use a universal <A> element:

index.tsx
import { A } from '@expo/html-elements';

export default function Home() {
  return <A href="https://expo.dev">Go to Expo</A>;
}

<A> 组件在 Web 上渲染 <a>,并在原生平台上渲染使用 expo-linking API 的交互式 <Text>

¥The <A> component renders an <a> on the web and an interactive <Text>that uses the expo-linking API on native platforms.