Skip to content

Commit c11f705

Browse files
committed
fix: resolve QRCode library loading issue in stream-qr display
- Add proper library loading checks and fallback CDN - Implement error handling for QRCode generation - Add timeout and retry logic for library loading - Improve error messages and debugging logs - Fix undefined QR code display issue
1 parent 55c2f76 commit c11f705

File tree

1 file changed

+178
-115
lines changed

1 file changed

+178
-115
lines changed

utilities/stream-qr/display.html

Lines changed: 178 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -10,137 +10,200 @@
1010
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
1111
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
1212
})(window,document,'script','dataLayer','GTM-TPQNM8CC');</script>
13-
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/qrcode.min.js"></script>
13+
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/qrcode.min.js" onerror="loadQRCodeFallback()"></script>
1414
<link rel="stylesheet" href="../stream-popup/css/main.css">
1515
<link rel="stylesheet" href="./css/main.css">
16-
</head>
17-
<body>
18-
<h1 style="display: none;">QR-коды</h1>
19-
<div id="container">
20-
21-
</div>
22-
2316
<script>
24-
// Получаем параметры из URL
25-
const urlParams = new URLSearchParams(window.location.search);
26-
const direction = urlParams.get('direction');
27-
const refreshRate = urlParams.get('refreshRate');
28-
29-
console.log('Направление:', direction);
30-
console.log('Время обновления:', refreshRate);
31-
32-
// Добавляем мета-тег для автоматического обновления страницы
33-
if (refreshRate) {
34-
const metaTag = document.createElement('meta');
35-
metaTag.httpEquiv = 'refresh';
36-
metaTag.content = refreshRate;
37-
document.head.appendChild(metaTag);
38-
console.log('Мета-тег добавлен:', metaTag);
17+
// Функция для загрузки альтернативной версии QRCode
18+
function loadQRCodeFallback() {
19+
console.log('Попытка загрузки альтернативной версии QRCode...');
20+
const script = document.createElement('script');
21+
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcode/1.5.3/qrcode.min.js';
22+
script.onload = function() {
23+
console.log('QRCode загружен через альтернативный CDN');
24+
initQRDisplay();
25+
};
26+
script.onerror = function() {
27+
console.error('Не удалось загрузить QRCode');
28+
showError('Не удалось загрузить библиотеку QRCode');
29+
};
30+
document.head.appendChild(script);
3931
}
4032

41-
const blocks = [];
42-
urlParams.forEach((value, key) => {
43-
if (key.startsWith('block')) {
44-
try {
45-
const blockData = JSON.parse(decodeURIComponent(value));
46-
blocks.push(blockData);
47-
} catch (error) {
48-
console.error('Ошибка при парсинге блока:', error);
49-
}
33+
function showError(message) {
34+
const container = document.getElementById('container');
35+
if (container) {
36+
container.innerHTML = `<div style="color: red; text-align: center; padding: 20px;">${message}</div>`;
5037
}
51-
});
52-
console.log('Блоки:', blocks);
53-
54-
// Показываем блоки для выбранного направления
55-
const container = document.getElementById('container');
56-
if (!container) {
57-
console.error('Контейнер не найден!');
58-
} else {
59-
console.log('Контейнер найден:', container);
6038
}
6139

62-
// Генерация стилей для анимаций
63-
function generateStyles(blocks, direction) {
64-
let styles = '';
65-
let totalDelay = 0;
40+
function initQRDisplay() {
41+
// Проверяем, загрузилась ли библиотека QRCode
42+
if (typeof QRCode === 'undefined') {
43+
console.error('Библиотека QRCode не загружена!');
44+
showError('Ошибка: Библиотека QRCode не загружена');
45+
return;
46+
}
6647

67-
blocks.forEach((block, index) => {
68-
const delayIn = totalDelay + parseInt(block.delay);
69-
const delayOut = delayIn + 5;
70-
71-
styles += `
72-
.block-${index}.${direction} {
73-
animation:
74-
slideIn${capitalizeFirstLetter(direction)} 1s forwards ${delayIn}s,
75-
shake 5s infinite alternate ${delayIn}s,
76-
slideOut${capitalizeFirstLetter(direction)} 1s forwards ${delayOut}s;
77-
opacity: 1;
78-
visibility: visible;
79-
}
80-
`;
48+
// Получаем параметры из URL
49+
const urlParams = new URLSearchParams(window.location.search);
50+
const direction = urlParams.get('direction');
51+
const refreshRate = urlParams.get('refreshRate');
52+
53+
console.log('Направление:', direction);
54+
console.log('Время обновления:', refreshRate);
8155

82-
totalDelay = delayOut + 1;
56+
// Добавляем мета-тег для автоматического обновления страницы
57+
if (refreshRate) {
58+
const metaTag = document.createElement('meta');
59+
metaTag.httpEquiv = 'refresh';
60+
metaTag.content = refreshRate;
61+
document.head.appendChild(metaTag);
62+
console.log('Мета-тег добавлен:', metaTag);
63+
}
64+
65+
const blocks = [];
66+
urlParams.forEach((value, key) => {
67+
if (key.startsWith('block')) {
68+
try {
69+
const blockData = JSON.parse(decodeURIComponent(value));
70+
blocks.push(blockData);
71+
} catch (error) {
72+
console.error('Ошибка при парсинге блока:', error);
73+
}
74+
}
8375
});
76+
console.log('Блоки:', blocks);
8477

85-
return styles;
86-
}
78+
// Показываем блоки для выбранного направления
79+
const container = document.getElementById('container');
80+
if (!container) {
81+
console.error('Контейнер не найден!');
82+
return;
83+
} else {
84+
console.log('Контейнер найден:', container);
85+
}
8786

88-
// Вспомогательная функция для капитализации первой буквы
89-
function capitalizeFirstLetter(string) {
90-
return string.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('');
91-
}
87+
// Генерация стилей для анимаций
88+
function generateStyles(blocks, direction) {
89+
let styles = '';
90+
let totalDelay = 0;
91+
92+
blocks.forEach((block, index) => {
93+
const delayIn = totalDelay + parseInt(block.delay);
94+
const delayOut = delayIn + 5;
9295

93-
const styleTag = document.createElement('style');
94-
styleTag.textContent = generateStyles(blocks, direction);
95-
document.head.appendChild(styleTag);
96-
97-
// Отображение блоков с QR-кодами
98-
blocks.forEach((block, index) => {
99-
const div = document.createElement('div');
100-
div.className = `block block-${index} ${direction}`;
101-
div.style.backgroundColor = decodeURIComponent(block.color);
102-
103-
// Создаем контейнер для QR-кода
104-
const qrContainer = document.createElement('div');
105-
qrContainer.className = 'qr-code-container';
106-
107-
// Создаем canvas для QR-кода
108-
const canvas = document.createElement('canvas');
109-
const qrSize = parseInt(decodeURIComponent(block.qrSize)) || 60;
110-
const qrColor = decodeURIComponent(block.qrColor) || '#000000';
111-
const url = decodeURIComponent(block.url);
112-
113-
canvas.width = qrSize;
114-
canvas.height = qrSize;
115-
116-
// Генерируем QR-код
117-
QRCode.toCanvas(canvas, url, {
118-
width: qrSize,
119-
margin: 1,
120-
color: {
121-
dark: qrColor,
122-
light: '#FFFFFF'
96+
styles += `
97+
.block-${index}.${direction} {
98+
animation:
99+
slideIn${capitalizeFirstLetter(direction)} 1s forwards ${delayIn}s,
100+
shake 5s infinite alternate ${delayIn}s,
101+
slideOut${capitalizeFirstLetter(direction)} 1s forwards ${delayOut}s;
102+
opacity: 1;
103+
visibility: visible;
104+
}
105+
`;
106+
107+
totalDelay = delayOut + 1;
108+
});
109+
110+
return styles;
111+
}
112+
113+
// Вспомогательная функция для капитализации первой буквы
114+
function capitalizeFirstLetter(string) {
115+
return string.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('');
116+
}
117+
118+
const styleTag = document.createElement('style');
119+
styleTag.textContent = generateStyles(blocks, direction);
120+
document.head.appendChild(styleTag);
121+
122+
// Отображение блоков с QR-кодами
123+
blocks.forEach((block, index) => {
124+
try {
125+
const div = document.createElement('div');
126+
div.className = `block block-${index} ${direction}`;
127+
div.style.backgroundColor = decodeURIComponent(block.color);
128+
129+
// Создаем контейнер для QR-кода
130+
const qrContainer = document.createElement('div');
131+
qrContainer.className = 'qr-code-container';
132+
133+
// Создаем canvas для QR-кода
134+
const canvas = document.createElement('canvas');
135+
const qrSize = parseInt(decodeURIComponent(block.qrSize)) || 60;
136+
const qrColor = decodeURIComponent(block.qrColor) || '#000000';
137+
const url = decodeURIComponent(block.url);
138+
139+
canvas.width = qrSize;
140+
canvas.height = qrSize;
141+
142+
// Генерируем QR-код
143+
QRCode.toCanvas(canvas, url, {
144+
width: qrSize,
145+
margin: 1,
146+
color: {
147+
dark: qrColor,
148+
light: '#FFFFFF'
149+
}
150+
}).then(() => {
151+
console.log(`QR-код ${index} сгенерирован для URL: ${url}`);
152+
}).catch((error) => {
153+
console.error(`Ошибка генерации QR-кода ${index}:`, error);
154+
});
155+
156+
qrContainer.appendChild(canvas);
157+
158+
// Создаем описание
159+
const description = document.createElement('p');
160+
description.textContent = decodeURIComponent(block.description);
161+
description.style.position = 'absolute';
162+
description.style.fontFamily = "'Teko', sans-serif";
163+
description.style.margin = '55px 0 0 0';
164+
description.style.width = '100%';
165+
166+
// Создаем основной контейнер
167+
const mainContainer = document.createElement('div');
168+
mainContainer.className = 'qr-block';
169+
mainContainer.appendChild(qrContainer);
170+
mainContainer.appendChild(description);
171+
172+
div.appendChild(mainContainer);
173+
container.appendChild(div);
174+
} catch (error) {
175+
console.error(`Ошибка при создании блока ${index}:`, error);
123176
}
124177
});
125-
126-
qrContainer.appendChild(canvas);
127-
128-
// Создаем описание
129-
const description = document.createElement('p');
130-
description.textContent = decodeURIComponent(block.description);
131-
description.style.position = 'absolute';
132-
description.style.fontFamily = "'Teko', sans-serif";
133-
description.style.margin = '55px 0 0 0';
134-
description.style.width = '100%';
135-
136-
// Создаем основной контейнер
137-
const mainContainer = document.createElement('div');
138-
mainContainer.className = 'qr-block';
139-
mainContainer.appendChild(qrContainer);
140-
mainContainer.appendChild(description);
141-
142-
div.appendChild(mainContainer);
143-
container.appendChild(div);
178+
}
179+
</script>
180+
</head>
181+
<body>
182+
<h1 style="display: none;">QR-коды</h1>
183+
<div id="container">
184+
185+
</div>
186+
187+
<script>
188+
// Ждем загрузки DOM и библиотеки QRCode
189+
document.addEventListener('DOMContentLoaded', function() {
190+
// Проверяем, загрузилась ли библиотека QRCode
191+
if (typeof QRCode !== 'undefined') {
192+
console.log('QRCode уже загружен');
193+
initQRDisplay();
194+
} else {
195+
console.log('QRCode еще не загружен, ждем...');
196+
// Ждем немного и проверяем снова
197+
setTimeout(function() {
198+
if (typeof QRCode !== 'undefined') {
199+
console.log('QRCode загружен после ожидания');
200+
initQRDisplay();
201+
} else {
202+
console.log('QRCode не загружен, пробуем альтернативный способ');
203+
loadQRCodeFallback();
204+
}
205+
}, 1000);
206+
}
144207
});
145208
</script>
146209
</body>

0 commit comments

Comments
 (0)