最稳的子页面取参方式是new URL(location.href).searchParams.get(),无需正则、不依赖layui、兼容现代浏览器,自动处理编码解码,跨域iframe下URL参数仍可用,但禁止访问window.parent。
子页面直接用 new URL(location.href).searchParams.get() 最稳
不用写正则、不依赖 layui 模块、无兼容性问题,现代浏览器全支持。只要 iframe 页面是同域的,这行代码就能直接拿到 url 里任意参数。
-
location.href包含完整地址,searchParams是原生 API,自动处理编码解码(比如中文、空格、+ 号) - 例如弹窗打开的是
/edit.html?id=123&name=%E5%BC%A0%E4%B8%89,new URL(location.href).searchParams.get('name')返回的就是 “张三”,不是乱码 - 别用老式
window.location.search+substr(1).split('&')手动解析——容易漏掉编码、错判分隔符、对空值没防护
layui.router() 在子页面里基本没用
layui.router() 是主页面上下文里的工具,只在 layui.use 回调中初始化,且依赖当前页面的路由配置。iframe 子页没加载 layui 全局模块,调用 layui.router() 会报 Cannot read property 'router' of undefined 或返回空对象。
- 即使子页也引入了 layui,
router默认解析的是子页自身 URL,但它的search属性只在主页面调用时才被正确注入(官方文档没说明这点,实测不可靠) - 强行在子页写
layui.use(['router'], ...)不解决问题:router 模块不导出独立解析能力,它只是封装了 location 的读取逻辑,而子页的location就是它自己的地址 —— 这和你手动用new URL没本质区别,还多一层依赖
拼参时要注意 encodeURIComponent()
父页面拼 URL 参数必须编码,否则子页拿不到原始值。常见翻车点:参数含中文、斜杠、问号、& 符号。
- 错误写法:
content: '/child.html?title=' + title + '&type=' + type→ 如果title = "用户/角色管理",URL 变成/child.html?title=用户/角色管理&type=1,searchParams.get('type')会返回undefined - 正确写法:
content: '/child.html?title=' + encodeURIComponent(title) + '&type=' + encodeURIComponent(type) - 如果参数来自表单输入或后端数据,一律先
encodeURIComponent,别信“看起来没问题”
跨域 iframe 下 URL 参数仍可用,但别碰 window.parent
URL 参数走的是地址栏,不受同源策略限制,所以哪怕子页是 https://api.example.com/xxx,只要能加载成功,new URL(location.href).searchParams.get() 照常工作。
- 但此时子页访问
window.parent会触发Blocked a frame with origin "https://api.example.com" from accessing a cross-origin frame错误 - 别在子页里写
parent.xxx或top.xxx,也别试图用postMessage向父页传参后再让父页回传——纯属绕远路,URL 参数就是为这事设计的 - 真正要交互时(比如选完数据关窗),用
postMessage单向发给父页,父页监听即可,不要反向依赖
router,原生 URL API 足够干净可靠。











