• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using Deep Linking for Application Redirection
2
3In Deep Linking, the system, based on the passed-in URI, searches for the application that meets the conditions from the locally installed applications and starts that application. If multiple applications are matched, a dialog box is displayed for users to select one of them.
4
5## Working Principles
6
7Deep Linking searches for an application based on the URI matching rules in implicit Want mechanism and starts the matching application. For details about the URI matching rules of implicit Want, see [Matching Rules of uri](explicit-implicit-want-mappings.md#matching-rules-of-uri).
8
9
10## Configuring the module.json5 File for the Target Application
11
12To be accessed by other applications, an application must configure the [skills](../quick-start/module-configuration-file.md#skills) field of the [module.json5 file](../quick-start/module-configuration-file.md). The value of **scheme** under **uri** can be customized. It can be any string that does not contain special characters or start with **ohos**.
13
14> **NOTE**
15>
16> The value of **scheme** in Deep Linking cannot be **https**, **http**, or **file**. Otherwise, the default system browser is started.
17
18
19A configuration example is as follows:
20
21```json
22{
23  "module": {
24    // ...
25    "abilities": [
26      {
27        // ...
28        "skills": [
29          {
30            "actions": [
31              // actions cannot be empty. Otherwise, matching the target application fails.
32              "ohos.want.action.viewData"
33            ],
34            "uris": [
35              {
36                // scheme is mandatory and can be customized. The following uses link as an example. Replace it with the actual scheme.
37                "scheme": "link",
38                // host is mandatory. Configure the domain name to be matched.
39                "host": "www.example.com"
40              }
41            ]
42          }
43        ]
44      }
45    ]
46  }
47}
48```
49
50
51## Implementing Application Redirection (Required for the Caller Application)
52
53The following uses three cases to describe how to use [openLink()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextopenlink12) and [startAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to implement application redirection and how to implement application redirection in the [Web component](../reference/apis-arkweb/ts-basic-components-web.md).
54
55### Using openLink to Implement Application Redirection
56
57Pass in the URL of the target application into **link** of [openLink()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextopenlink12), and set **appLinkingOnly** in the **options** field to **false**.
58
59
60The sample code is as follows:
61
62```ts
63import { common, OpenLinkOptions } from '@kit.AbilityKit';
64import { BusinessError } from '@kit.BasicServicesKit';
65import { hilog } from '@kit.PerformanceAnalysisKit';
66
67const TAG: string = '[UIAbilityComponentsOpenLink]';
68const DOMAIN_NUMBER: number = 0xFF00;
69
70@Entry
71@Component
72struct Index {
73  build() {
74    Button('start link', { type: ButtonType.Capsule, stateEffect: true })
75      .width('87%')
76      .height('5%')
77      .margin({ bottom: '12vp' })
78      .onClick(() => {
79        let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
80        let link: string = "link://www.example.com";
81        let openLinkOptions: OpenLinkOptions = {
82          appLinkingOnly: false
83        };
84
85        try {
86          context.openLink(link, openLinkOptions)
87            .then(() => {
88              hilog.info(DOMAIN_NUMBER, TAG, 'open link success.');
89            }).catch((err: BusinessError) => {
90              hilog.error(DOMAIN_NUMBER, TAG, `open link failed. Code is ${err.code}, message is ${err.message}`);
91            });
92        } catch (paramError) {
93          hilog.error(DOMAIN_NUMBER, TAG, `Failed to start link. Code is ${paramError.code}, message is ${paramError.message}`);
94        }
95      })
96  }
97}
98```
99
100### Using startAbility() to Implement Application Redirection
101
102Pass in the target application's link into **want** of [startAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability), which then uses [implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) to trigger application redirection. In addition, you must pass in the **action** and **entity** fields to be matched.
103
104
105The sample code is as follows:
106
107```ts
108import { common, Want } from '@kit.AbilityKit';
109import { BusinessError } from '@kit.BasicServicesKit';
110import { hilog } from '@kit.PerformanceAnalysisKit';
111
112const TAG: string = '[UIAbilityComponentsOpenLink]';
113const DOMAIN_NUMBER: number = 0xFF00;
114
115@Entry
116@Component
117struct Index {
118  build() {
119    Button('start ability', { type: ButtonType.Capsule, stateEffect: true })
120      .width('87%')
121      .height('5%')
122      .margin({ bottom: '12vp' })
123      .onClick(() => {
124        let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
125        let want: Want = {
126            uri: "link://www.example.com"
127        };
128
129        try {
130          context.startAbility(want).then(() => {
131            hilog.info(DOMAIN_NUMBER, TAG, 'start ability success.');
132          }).catch((err: BusinessError) => {
133            hilog.error(DOMAIN_NUMBER, TAG, `start ability failed. Code is ${err.code}, message is ${err.message}`);
134          });
135        } catch (paramError) {
136          hilog.error(DOMAIN_NUMBER, TAG, `Failed to start ability. Code is ${paramError.code}, message is ${paramError.message}`);
137        }
138      })
139  }
140}
141```
142
143### Using the Web Component to Implement Application Redirection
144
145To implement application redirection from a **Web** component in Deep Linking mode, process the defined event in the [onLoadIntercept](../reference/apis-arkweb/ts-basic-components-web.md#onloadintercept10) callback.
146
147The sample code is as follows:
148
149```ts
150// index.ets
151import { webview } from '@kit.ArkWeb';
152import { BusinessError } from '@kit.BasicServicesKit';
153import { common } from '@kit.AbilityKit';
154
155@Entry
156@Component
157struct WebComponent {
158  controller: webview.WebviewController = new webview.WebviewController();
159
160  build() {
161    Column() {
162      Web({ src: $rawfile('index.html'), controller: this.controller })
163        .onLoadIntercept((event) => {
164          const url: string = event.data.getRequestUrl();
165          if (url === 'link://www.example.com') {
166            (getContext() as common.UIAbilityContext).openLink(url)
167              .then(() => {
168                console.log('openLink success');
169              }).catch((err: BusinessError) => {
170                console.error('openLink failed, err:' + JSON.stringify(err));
171              });
172            return true;
173          }
174          // If true is returned, the loading is blocked. Otherwise, the loading is allowed.
175          return false;
176        })
177    }
178  }
179}
180```
181
182Frontend page code:
183```html
184// index.html
185<!DOCTYPE html>
186<html>
187<head>
188    <meta charset="UTF-8">
189</head>
190<body>
191<h1>Hello World</h1>
192<!--Method 1: Bind window.open to implement redirection.-->;
193<button class="doOpenLink" onclick="doOpenLink()">Redirect to application 1</button>
194<!--Method 2: Use a hyperlink for redirection.-->;
195<a href="link://www.example.com">Redirect to application 2</a>
196</body>
197</html>
198<script>
199    function doOpenLink() {
200        window.open("link://www.example.com")
201    }
202</script>
203```
204