🐛 fix: 增强 QRCode 库加载时的全局变量类型检查

- 修改 `loadQRCodeLibrary` 函数中全局变量检测逻辑,从 `if (window.qrcode)` 改为 `typeof window.qrcode === 'function'`,防止非函数值污染导致逻辑错误
- 同步更新对 `window.QRCode` 的严格类型检查,确保大写字母变体的加载路径同样具备防护机制
- 优化错误提示信息,当库加载完成但全局变量不是函数时,明确抛出 `'global variable is not a function'` 错误便于排查
- 更新代码注释,说明引入严格类型检查的原因是为了兼容浏览器扩展或其他脚本可能覆盖全局变量的场景
This commit is contained in:
Abner
2026-06-23 23:23:42 +08:00
parent 6379bbef90
commit 782f36e0ed

View File

@@ -115,11 +115,11 @@ function validateQRCodeData(data) {
* @returns {Promise<Object>} qrcode 库对象
*/
export async function loadQRCodeLibrary() {
// 1. 检查全局变量(可能已被 CDN 脚本加载
if (window.qrcode) {
// 1. 检查全局变量(必须是函数,防止浏览器扩展或其他脚本污染 window.qrcode
if (typeof window.qrcode === 'function') {
return window.qrcode;
}
if (window.QRCode) {
if (typeof window.QRCode === 'function') {
return window.QRCode;
}
@@ -183,17 +183,18 @@ function loadSingleCDN(cdnUrl) {
const handleLoad = () => {
cleanup();
// qrcode-generator 包设置 window.qrcode小写
if (window.qrcode) {
// 必须 typeof 检查,防止浏览器扩展污染全局变量为非函数值
if (typeof window.qrcode === 'function') {
resolve(window.qrcode);
return;
}
// 兼容:部分 CDN 可能设置 window.QRCode大写
if (window.QRCode) {
if (typeof window.QRCode === 'function') {
resolve(window.QRCode);
return;
}
script.remove();
reject(new Error('QRCode library loaded but global variable is missing'));
reject(new Error('QRCode library loaded but global variable is not a function'));
};
const handleError = () => {