旧版 Android WebView 中 Element.prototype.matches 存在兼容性问题,需通过 polyfill 或构建工具自动转换解决:if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || ... }

旧版 Android WebView(尤其是 Android 4.4–5.1 内置的 Chromium 30–46)中,Element.prototype.matches 方法存在拼写不一致问题:部分版本只支持带浏览器前缀的 matchesSelector 或 webkitMatchesSelector,而现代 JS 代码直接调用 el.matches(selector) 会抛出 TypeError: undefined is not a function,导致脚本中断、页面白屏。
确认是否为 matches 兼容性问题
在 Chrome 远程调试(chrome://inspect)的 Console 中查看是否有如下报错:
TypeError: el.matches is not a function-
Uncaught TypeError: Cannot read property 'matches' of null(常因上一行失败导致后续逻辑崩溃) - 白屏但 DOM 已加载(可用 Elements 面板确认节点存在)
前端侧兼容补丁(推荐)
在 HTML 的 <head> 中或 JS 入口处,**尽早**注入以下 polyfill(务必在任何业务逻辑执行前运行):
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.matchesSelector ||
Element.prototype.webkitMatchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector;
}
若项目使用构建工具(如 Vite、Webpack),可统一注入到 main.js 或 polyfills.js 中,并确保它排在所有业务代码之前。
构建时自动处理(Vue/React 项目适用)
借助 Babel 或构建插件自动转换语法:
- Vite 用户:在
vite.config.ts的legacy插件中补充'es.array.find'和'es.object.assign'等基础 polyfill,同时启用transformObjectAssign等规则 - Babel 用户:添加
@babel/plugin-transform-object-assign及@babel/preset-env并配置targets: { android: '6' },Babel 会自动将el.matches()转为兼容写法
服务端或构建层兜底(防漏)
对关键 H5 页面,可在服务端注入轻量检测脚本,捕获并修复:
(function() {
if (typeof Element !== 'undefined' && !Element.prototype.matches) {
const proto = Element.prototype;
proto.matches = proto.matchesSelector ||
proto.webkitMatchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector || function(selector) {
const elements = this.parentElement.querySelectorAll(selector);
return Array.prototype.indexOf.call(elements, this) !== -1;
};
}
})();
该 fallback 实现不依赖外部库,体积小,适合离线包或小程序 WebView 场景。

















