特性檢測中,判斷某方法是否為瀏覽器原生實現(而非Polyfill/用戶代碼覆蓋)是庫作者的核心需求。本文深度解析isNative多種實現、[native code]字符串特徵、Safari/Opera異常行為、以及惡意偽造繞過檢測的攻防。
var isNative = function(method) {
return !!method && /\{\s*\[native code\]\s*\}/.test(method + "");
// 操作符""隱式調用toString()
};
var isNative = function(object, method) {
return object && method in object &&
typeof object[method] !== 'string' &&
(/\{\s*\[native code\]\s*\}|\s*\[function\]\s*/).test(object[method]);
};
// Safari <= 2.0.4 返回 "[function]" 而非 "[native code]"
window.test = {
toString: function() { return "[function]"; }
};
isNative(window, "test"); // true —— 被繞過!
var isNative = (function() {
// 獲取已知原生方法的 toString "指紋"
var nativeSignature = (window.open + "").replace(/open/g, "");
return function(object, method) {
var m = object ? object[method] : false;
if (!m || typeof m === 'string') return false;
// 對比目標方法 toString 去除方法名後的特徵
var regex = new RegExp(method, 'g');
return nativeSignature === (m + "").replace(regex, "");
};
})();
window.open必為原生,其toString()包含引擎特定標識| 瀏覽器 | 原生方法 toString 特徵 | 備註 |
|---|---|---|
| Chrome/Firefox/Edge/IE | function open() { [native code] } | 標準 |
| Safari (舊版) | function open() { [function] } | 非標準 |
| Opera 9.x | function open() { [source code not available] } | 特殊標識 |
typeof fn === 'function'即可is-native npm包(基於nwmatchers)Proxy、Object.defineProperty攔截toString的高級偽造