
回复
作为一个曾在应用跳转中被规则困住的开发者,今天要揭秘Deep Linking的灵活玩法!第一次用自定义scheme实现跨应用跳转时,同事以为我改了系统底层,其实只是掌握了这把「万能钥匙」的使用技巧~
想象你有一串万能钥匙:
myapp://
)myapp://product?id=123
)特点 | 传统跳转 | Deep Linking |
---|---|---|
协议定义 | 系统固定 | 自定义(如shop:// ) |
参数支持 | 简单传递 | 复杂参数结构 |
未安装处理 | 无法跳转 | 可跳转浏览器或下载页 |
// module.json5中配钥匙模
{
"module": {
"abilities": [
{
"skills": [
{
"uris": [
{
"scheme": "food", // 自定义协议名(钥匙形状)
"host": "map", // 域名(锁类型)
"path": "/location" // 路径(锁孔位置)
}
]
}
]
}
]
}
}
// 构造开门钥匙(Deep Linking链接)
const link = "food://map/location?lat=39.9&lng=116.4&address=王府井";
参数 | 作用 | 示例 |
---|---|---|
scheme | 协议名称(钥匙形状) | “food” |
host | 域名(锁类型) | “map” |
path | 路径(锁孔位置) | “/location” |
pathStartWith | 路径前缀匹配 | “/api/” |
pathRegex | 路径正则匹配 | “/product/\d+” |
{
"uris": [
{
"scheme": "shop",
"host": "product",
"pathRegex": "/detail/\\d+" // 匹配/product/detail/123等路径
}
]
}
匹配链接示例:
shop://product/detail/123
→ 匹配成功
shop://product/detail/abc
→ 匹配失败
import { common } from '@ohos.app.ability.common';
// 用钥匙开地图应用
const context = this.getContext(this) as common.UIAbilityContext;
const link = "geo://map/location?lat=37.77&lng=122.42";
context.openLink(link, { appLinkingOnly: false }); // 允许Deep Linking
import { common } from '@ohos.app.ability.common';
// 带参数开商品详情页
const want = {
action: 'ohos.want.action.viewData',
uri: "shop://product/detail/123",
parameters: { from: 'cart' } // 额外参数
};
context.startAbility(want);
import { webview } from '@ohos.arkweb';
// 网页中识别Deep Linking并跳转
this.controller.onLoadIntercept((event) => {
const url = event.data.getRequestUrl();
if (url.startsWith("shop://")) {
context.openLink(url); // 跳转到对应应用
return true; // 阻止网页加载
}
});
// 构造带坐标的Deep Linking
const shopLink = "geo://map/location?lat=39.9&lng=116.4&shopName=海底捞";
// 跳转地图应用
context.openLink(shopLink, { appLinkingOnly: false });
// 生成带商品ID的分享链接
const shareLink = `shop://product/detail/123?from=social&userId=567`;
// 分享到微信
shareToWeChat(shareLink);
// 接收方处理
onCreate(want) {
const productId = url.URL.parseURL(want.uri).params.get('id');
loadProductDetail(productId);
}
com.example.shop
)map
✅ 安全命名:com.example.map
token=加密后字符串
)context.openLink(link, {
appLinkingOnly: false,
openInBrowser: true, // 没安装时开浏览器
browserUrl: "https://shop.com/product/123" // 自定义浏览器打开地址
});
对比项 | Deep Linking | App Linking |
---|---|---|
协议类型 | 自定义scheme | HTTPS标准协议 |
安全性 | 易被仿冒 | 域名校验+HTTPS加密 |
适用场景 | 企业内部跳转 | 对外分享、广告引流 |
未安装处理 | 需自定义处理 | 自动跳转应用市场 |
记得第一次用Deep Linking做社交分享时,自定义share://
协议被同事吐槽像「黑魔法」~ 现在用这套方案实现了商品链接在各应用间无缝跳转,用户说「像有魔法一样方便」~