URLPattern API 实战:浏览器原生路由匹配与模式解析

技术架构(更新于 2026年6月16日)

URLPattern API 概述

URLPattern 是浏览器原生提供的 URL 模式匹配接口,灵感来自 Express 路由语法,但功能更强大——支持协议、主机、端口、路径、查询参数和哈希的独立模式匹配。

const pattern = new URLPattern({ pathname: '/api/users/:id' });
const result = pattern.exec('https://example.com/api/users/42');
console.log(result.pathname.groups.id);

模式语法详解

基础语法:通配符与命名组

语法 含义 示例 匹配
* 通配符,匹配任意字符串 /api/* /api/anything
:name 命名捕获组 /users/:id /users/42{id: "42"}
:name+ 命名组匹配多段路径 /files/:path+ /files/a/b/c{path: "a/b/c"}
(.*) 正则分组 /old/(.*) /old/page{0: "page"}

正则约束命名组

const pattern = new URLPattern({
  pathname: '/products/:id(\\d+)'
});

pattern.test('https://shop.com/products/123');
pattern.test('https://shop.com/products/abc');

完整 URL 各组件模式

const apiPattern = new URLPattern({
  protocol: 'https',
  hostname: ':sub.example.com',
  pathname: '/v:version/:resource/:id?',
  search: 'sort=:sort&*'
});

const match = apiPattern.exec({
  protocol: 'https',
  hostname: 'api.example.com',
  pathname: '/v2/users/42',
  search: 'sort=name&page=1'
});

if (match) {
  console.log(match.hostname.groups.sub);
  console.log(match.pathname.groups.version);
  console.log(match.pathname.groups.resource);
  console.log(match.pathname.groups.id);
  console.log(match.search.groups.sort);
}

Service Worker 路由拦截

URLPattern 与 Service Worker 的结合是浏览器原生路由层的核心场景。

基于 URLPattern 的 SW 路由分发

self.addEventListener('fetch', (event) => {
  const routes = [
    { pattern: new URLPattern({ pathname: '/api/*' }), handler: handleApi },
    { pattern: new URLPattern({ pathname: '/static/*' }), handler: handleStatic },
    { pattern: new URLPattern({ pathname: '/pages/:slug' }), handler: handlePage },
  ];

  for (const { pattern, handler } of routes) {
    const result = pattern.exec(event.request.url);
    if (result) {
      event.respondWith(handler(event, result));
      return;
    }
  }
});

async function handleApi(event, match) {
  const cache = await caches.open('api-cache');
  const cached = await cache.match(event.request);
  if (cached) return cached;

  const response = await fetch(event.request);
  await cache.put(event.request, response.clone());
  return response;
}

使用 Chrome Route API(实验性)

if ('routes' in self.registration) {
  self.registration.routes.add(
    new URLPattern({ pathname: '/api/*' }),
    new CacheFirstStrategy({ cacheName: 'api-cache' })
  );
}

客户端路由匹配

SPA 路由器实现

class Router {
  constructor() {
    this.routes = [];
    window.addEventListener('popstate', () => this.resolve());
  }

  add(pattern, handler) {
    this.routes.push({
      pattern: new URLPattern({ pathname: pattern }),
      handler
    });
    return this;
  }

  resolve(pathname = location.pathname) {
    for (const { pattern, handler } of this.routes) {
      const result = pattern.exec({ pathname });
      if (result) {
        handler(result.pathname.groups);
        return;
      }
    }
    console.warn(`No route matched: ${pathname}`);
  }

  navigate(path) {
    history.pushState(null, '', path);
    this.resolve(path);
  }
}

const router = new Router();
router
  .add('/dashboard', (params) => renderDashboard())
  .add('/users/:id', (params) => renderUser(params.id))
  .add('/posts/:slug/comments/:commentId?', (params) => renderComment(params))
  .add('/*', () => renderNotFound());

router.resolve();

模式匹配 vs 传统方案对比

特性 URLPattern API RegExp path-to-regexp Express
浏览器原生
URL 组件拆分 ✅ 协议/主机/路径/查询 部分
命名捕获组 ❌ (ES2025前)
正则约束 :id(\\d+)
类型安全结果 ✅ groups 对象
性能 原生 C++ 实现 JS 引擎优化 JS 解析 JS 解析

实用模式集合

const patterns = {
  apiV1: new URLPattern({ pathname: '/api/v1/:resource/:id?' }),
  apiV2: new URLPattern({ pathname: '/api/v2/:resource/:id?' }),
  userAssets: new URLPattern({ pathname: '/users/:userId/:type(img|doc|pdf)/*' }),
  localePage: new URLPattern({ pathname: '/:locale(zh-CN|en|ja)/:page*' }),
  searchWithFilter: new URLPattern({ pathname: '/search', search: 'q=:query&filter=:filter?' }),
};

function matchRoute(url) {
  for (const [name, pattern] of Object.entries(patterns)) {
    const result = pattern.exec(url);
    if (result) return { name, groups: result.pathname.groups, search: result.search.groups };
  }
  return null;
}

浏览器兼容与 Polyfill

浏览器 支持状态 备注
Chrome 95+ 完整支持
Edge 95+ 完整支持
Firefox ⚠️ 需 polyfill
Safari 17+ 完整支持
npm install urlpattern-polyfill
import { URLPattern } from 'urlpattern-polyfill';
if (!globalThis.URLPattern) {
  globalThis.URLPattern = URLPattern;
}

最佳实践总结

  1. 优先使用命名组而非索引访问,提升可读性与可维护性
  2. 对动态段施加正则约束,避免无效匹配进入处理逻辑
  3. SW 路由按优先级排列,API 路由优先于通配兜底
  4. 利用 URL 组件独立匹配,协议与主机模式可锁定安全来源
  5. 渐进增强:检测 API 可用性,不可用时回退至 RegExp 方案

URLPattern API 将路由匹配从框架依赖中解放出来,成为浏览器基础设施的一部分。结合 Service Worker,它为离线优先架构提供了原生路由层支撑。

本站提供浏览器本地工具,免注册即可试用 →

#URLPattern#路由匹配#Service Worker#Web API#模式匹配