URLPattern 路由匹配与安全过滤实践概述URLPattern 提供声明式的 URL 匹配与参数提取,适用于路由匹配、白名单校验与安全过滤,确保客户端与服务端一致的行为。关键参数/概念`new URLPattern({ pathname: '/users/:id' })`: 声明路由模式。`pattern.test(url)`: 判断是否匹配;`pattern.exec(url)`: 提取参数。集成 Navigation API:对 `destination.url` 做白名单与参数校验。实践/示例const userDetail = new URLPattern({ pathname: "/users/:id" });

const userList = new URLPattern({ pathname: "/users" });

navigation.addEventListener("navigate", (event: any) => {

if (!event.canIntercept) return;

const url = new URL(event.destination.url);

if (!(userDetail.test(url) || userList.test(url))) return; // 非目标路由放行

event.intercept({

handler: async () => {

const match = userDetail.exec(url);

const id = match?.pathname.groups?.id;

const endpoint = id ? `/api/users/${id}` : "/api/users";

const data = await fetch(endpoint, { cache: "no-store" }).then((r) => r.json());

renderUsers(data);

},

});

});

验证方法参数正确性:构造不同路径与边界值,验证 `exec` 提取的参数与类型。安全过滤:以黑/白名单对比策略验证拦截与放行路径是否符合预期。注意事项兼容性:URLPattern 在 Chromium 系浏览器支持较好,其他浏览器需降级到正则匹配。性能:匹配规则不宜过度复杂,避免客户端匹配耗时影响导航体验。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部