Android Kitkat环境下Uncaught ReferenceError: WeakMap is not defined错误解决方案咨询
Hey there, let's sort out this error you're hitting with TradingView's widgets on Android KitKat! The core issue here is that KitKat's default system WebView doesn't support ES6 features like WeakMap—and those widget scripts you're loading are relying on it.
Here are three practical solutions to resolve this:
1. Add a WeakMap Polyfill (Quickest Fix)
You can inject a polyfill that adds WeakMap support to the older WebView, before loading any of the TradingView widget scripts. This will mimic the ES6 WeakMap functionality using older JS features.
Here's a standalone polyfill you can embed directly in your HTML (place this script tag above the TradingView widget scripts):
// WeakMap polyfill for browsers that don't support it (like KitKat's WebView) if (typeof WeakMap === 'undefined') { window.WeakMap = (function() { function WeakMap() { this._internalMap = new Map(); this._keyCounter = 0; } WeakMap.prototype.set = function(key, value) { if (typeof key !== 'object' && typeof key !== 'function') { throw new TypeError('Invalid value used as weak map key'); } // Add a unique hidden ID to the key if (!key.__weakmap_key_id__) { Object.defineProperty(key, '__weakmap_key_id__', { value: ++this._keyCounter, enumerable: false, configurable: true }); } this._internalMap.set(key.__weakmap_key_id__, value); }; WeakMap.prototype.get = function(key) { return key.__weakmap_key_id__ ? this._internalMap.get(key.__weakmap_key_id__) : undefined; }; WeakMap.prototype.has = function(key) { return !!key.__weakmap_key_id__ && this._internalMap.has(key.__weakmap_key_id__); }; WeakMap.prototype.delete = function(key) { if (!key.__weakmap_key_id__) return false; const result = this._internalMap.delete(key.__weakmap_key_id__); delete key.__weakmap_key_id__; return result; }; return WeakMap; })(); }
This polyfill follows the ES6 WeakMap spec closely and should work seamlessly with the TradingView scripts.
2. Use Chrome Custom Tabs (Better Long-Term Option)
If you're embedding these widgets in a native Android app, consider switching to Chrome Custom Tabs instead of the default system WebView. Chrome Custom Tabs use the user's installed Chrome browser (version 45+ supports KitKat), which includes full ES6 support—so WeakMap will work natively without a polyfill.
This also gives users a more familiar browsing experience and better performance compared to the old system WebView.
3. Check for an ES5-Compatible TradingView Build
Some services offer legacy builds of their scripts that target ES5 (compatible with older browsers). Reach out to TradingView's support team or check their embed documentation to see if they provide an ES5 version of their widget bundles. If available, using these builds would eliminate the need for polyfills entirely.
内容的提问来源于stack exchange,提问作者Sushmitha Reddy

