Ultima attività 1745295964

Revisione 1aaa30397ce0cb7b22867a86ba997b4e05d98b6f

discord_msg_webhook.user.js Raw
1// ==UserScript==
2// @name Discord Message to Webhook
3// @description Combined tool for viewing JSON data of Discord messages and bulk deletion
4// @version 1.0.0
5// @author Original scripts by various authors, combined version
6// @match https://*.discord.com/app
7// @match https://*.discord.com/channels/*
8// @match https://*.discord.com/login
9// @license MIT
10// @grant none
11// ==/UserScript==
12
13(function () {
14 'use strict';
15
16 // --- Configuration ---
17 const VERSION = "1.0.1";
18 const PREFIX = '';
19 let logFn = null;
20 const ui = {};
21 let observerThrottle = null;
22
23 // --- CSS ---
24 const themeCss = `
25/* JSON Viewer Box */
26#discord-message-json-display {
27 position: fixed;
28 top: 50px;
29 right: 50px;
30 width: 450px;
31 height: 300px;
32 background-color: var(--background-secondary);
33 border: 1px solid var(--background-tertiary);
34 border-radius: 5px;
35 z-index: 1000;
36 overflow: hidden;
37 display: flex;
38 flex-direction: column;
39 font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
40 font-size: 12px;
41 color: var(--text-normal);
42 box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.2);
43 resize: both;
44 overflow: auto;
45 min-width: 250px;
46 min-height: 150px;
47}
48#discord-message-json-display .header {
49 padding: 10px;
50 background-color: var(--background-tertiary);
51 cursor: grab;
52 font-weight: bold;
53 border-bottom: 1px solid var(--background-tertiary);
54 display: flex;
55 justify-content: space-between;
56 align-items: center;
57 user-select: none;
58}
59#discord-message-json-content {
60 flex-grow: 1;
61 padding: 10px;
62 margin: 0;
63 overflow: auto;
64 white-space: pre-wrap;
65 word-wrap: break-word;
66 background-color: var(--background-primary);
67}
68#discord-message-json-display::-webkit-resizer {
69 background-color: var(--brand-experiment);
70}
71.format-toggle-container {
72 display: flex;
73 align-items: center;
74 font-weight: normal;
75 font-size: 10px;
76 margin-right: 10px;
77 cursor: pointer;
78}
79.format-toggle-container input {
80 margin-right: 5px;
81 cursor: pointer;
82}
83
84/* Custom JSON syntax highlighting */
85.json-string { color: #a8ff60; }
86.json-number { color: #d8a0df; }
87.json-boolean { color: #b285fe; }
88.json-null { color: #70a0d8; }
89.json-key { color: #f08d49; }
90.json-punctuation { color: #7a82da; }
91`;
92
93 // --- HTML Elements ---
94 // SVG Data for the JSON icon
95 const jsonSvgIcon = `<svg width="18px" height="18px" viewBox="-10 -5 1034 1034" xmlns="http://www.w3.org/2000/svg">
96 <path fill="currentColor" d="M482 226h-1l-10 2q-33 4 -64.5 18.5t-55.5 38.5q-41 37 -57 91q-9 30 -8 63t12 63q17 45 52 78l13 12l-83 135q-26 -1 -45 7q-30 13 -45 40q-7 15 -9 31t2 32q8 30 33 48q15 10 33 14.5t36 2t34.5 -12.5t27.5 -25q12 -17 14.5 -39t-5.5 -41q-1 -5 -7 -14l-3 -6l118 -192 q6 -9 8 -14l-10 -3q-9 -2 -13 -4q-23 -10 -41.5 -27.5t-28.5 -39.5q-17 -36 -9 -75q4 -23 17 -43t31 -34q37 -27 82 -27q27 -1 52.5 9.5t44.5 30.5q17 16 26.5 38.5t10.5 45.5q0 17 -6 42l70 19l8 1q14 -43 7 -86q-4 -33 -19.5 -63.5t-39.5 -53.5q-42 -42 -103 -56 q-6 -2 -18 -4l-14 -2h-37zM500 350q-17 0 -34 7t-30.5 20.5t-19.5 31.5q-8 20 -4 44q3 18 14 34t28 25q24 15 56 13q3 4 5 8l112 191q3 6 6 9q27 -26 58.5 -35.5t65 -3.5t58.5 26q32 25 43.5 61.5t0.5 73.5q-8 28 -28.5 50t-48.5 33q-31 13 -66.5 8.5t-63.5 -24.5 q-4 -3 -13 -10l-5 -6q-4 3 -11 10l-47 46q23 23 52 38.5t61 21.5l22 4h39l28 -5q64 -13 110 -60q22 -22 36.5 -50.5t19.5 -59.5q5 -36 -2 -71.5t-25 -64.5t-44 -51t-57 -35q-34 -14 -70.5 -16t-71.5 7l-17 5l-81 -137q13 -19 16 -37q5 -32 -13 -60q-16 -25 -44 -35 q-17 -6 -35 -6zM218 614q-58 13 -100 53q-47 44 -61 105l-4 24v37l2 11q2 13 4 20q7 31 24.5 59t42.5 49q50 41 115 49q38 4 76 -4.5t70 -28.5q53 -34 78 -91q7 -17 14 -45q6 -1 18 0l125 2q14 0 20 1q11 20 25 31t31.5 16t35.5 4q28 -3 50 -20q27 -21 32 -54 q2 -17 -1.5 -33t-13.5 -30q-16 -22 -41 -32q-17 -7 -35.5 -6.5t-35.5 7.5q-28 12 -43 37l-3 6q-14 0 -42 -1l-113 -1q-15 -1 -43 -1l-50 -1l3 17q8 43 -13 81q-14 27 -40 45t-57 22q-35 6 -70 -7.5t-57 -42.5q-28 -35 -27 -79q1 -37 23 -69q13 -19 32 -32t41 -19l9 -3z"/>
97</svg>`;
98
99 // --- JSON Viewer Variables ---
100 let jsonDisplayBox = null;
101 let isDragging = false;
102 let dragOffsetX, dragOffsetY;
103 let isScriptActive = true;
104 let currentMessage = null;
105 let isWebhookFormat = false;
106
107 // --- Utility Functions ---
108 const $ = s => document.querySelector(s);
109
110 const log = {
111 debug() { return logFn ? logFn('debug', arguments) : console.debug.apply(console, arguments); },
112 info() { return logFn ? logFn('info', arguments) : console.info.apply(console, arguments); },
113 verb() { return logFn ? logFn('verb', arguments) : console.log.apply(console, arguments); },
114 warn() { return logFn ? logFn('warn', arguments) : console.warn.apply(console, arguments); },
115 error() { return logFn ? logFn('error', arguments) : console.error.apply(console, arguments); },
116 success() { return logFn ? logFn('success', arguments) : console.info.apply(console, arguments); }
117 };
118
119 function hslaToHex(hsla) {
120 // Handle the specific calc variable case by replacing it with 100%
121 const processedHsla = hsla.replace(/calc\(var\(--saturation-factor,\s*1\)\s*\*\s*100%\)/g, '100%');
122
123 // Parse the HSLA values
124 const parts = processedHsla.match(/hsla?\((\d+),\s*(\d+(\.\d+)?%),\s*(\d+(\.\d+)?%),\s*(\d?(\.\d+)?)\)/);
125 if (!parts) {
126 // If parsing fails, return a default color or handle the error
127 console.error("Failed to parse HSLA string:", hsla);
128 return null; // Or return a default hex color like 0
129 }
130
131 const h = parseInt(parts[1], 10);
132 const s = parseFloat(parts[2]) / 100;
133 const l = parseFloat(parts[4]) / 100;
134 const a = parseFloat(parts[7] !== undefined ? parts[7] : 1); // Default alpha to 1 if not present
135
136 // Convert HSL to RGB
137 let r, g, b;
138
139 if (s === 0) {
140 r = g = b = l; // Achromatic
141 } else {
142 const hue2rgb = (p, q, t) => {
143 if (t < 0) t += 1;
144 if (t > 1) t -= 1;
145 if (t < 1 / 6) return p + (q - p) * 6 * t;
146 if (t < 1 / 2) return q;
147 if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
148 return p;
149 };
150
151 const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
152 const p = 2 * l - q;
153
154 r = hue2rgb(p, q, h / 360 + 1 / 3);
155 g = hue2rgb(p, q, h / 360);
156 b = hue2rgb(p, q, h / 360 - 1 / 3);
157 }
158
159 // Convert RGB to Hex
160 const toHex = x => {
161 const hex = Math.round(x * 255).toString(16);
162 return hex.length === 1 ? '0' + hex : hex;
163 };
164
165 const hex = `${toHex(r)}${toHex(g)}${toHex(b)}`;
166
167 // Handle Alpha (optional, as webhook colors are typically RGB hex)
168 // If you need to include alpha in the hex (RRGGBBAA), uncomment the following:
169 /*
170 const toHexAlpha = x => {
171 const hexA = Math.round(x * 255).toString(16);
172 return hexA.length === 1 ? '0' + hexA : hexA;
173 };
174 return parseInt(hex + toHexAlpha(a), 16);
175 */
176
177 return parseInt(hex, 16);
178 }
179
180 const setLogFn = (fn) => logFn = fn;
181
182 function createElm(html) {
183 const temp = document.createElement('div');
184 temp.innerHTML = html;
185 return temp.removeChild(temp.firstElementChild);
186 }
187
188 function insertCss(css) {
189 const style = document.createElement('style');
190 style.innerHTML = css;
191 document.head.appendChild(style);
192 return style;
193 }
194
195 // --- React Instance Finders ---
196 function findReactInstance(element) {
197 for (const key in element) {
198 if (key.startsWith('__reactFiber$') || key.startsWith('__reactProps$')) {
199 return element[key];
200 }
201 }
202 return null;
203 }
204
205 function getMessageFromReactInstance(reactInstance) {
206 if (!reactInstance) return null;
207
208 let current = reactInstance;
209 while (current) {
210 if (current.memoizedProps && current.memoizedProps.message) {
211 return current.memoizedProps.message;
212 }
213 current = current.return;
214 }
215 return null;
216 }
217
218 // --- JSON Conversion Function ---
219 function convertMessageToWebhookJson(message) {
220 if (!message) return null;
221
222 const webhookJson = {};
223
224 // Basic message properties
225 if (message.content) {
226 webhookJson.content = message.content;
227 }
228 // console.log(message);
229 // Username and Avatar
230 if (message.author) {
231 webhookJson.username = message.author.username;
232 if (message.author.avatar) {
233 const avatarHash = message.author.avatar;
234 const userId = message.author.id;
235 const isGif = avatarHash.startsWith('a_');
236 webhookJson.avatar_url = `https://cdn.discordapp.com/avatars/${userId}/${avatarHash}.${isGif ? 'gif' : 'png'}`;
237 } else {
238 // Default avatar if none is set
239 const discriminator = message.author.discriminator;
240 let defaultAvatarId;
241 if (discriminator === '0') {
242 defaultAvatarId = (BigInt(message.author.id) >> 22n) % 6n;
243 webhookJson.avatar_url = `https://cdn.discordapp.com/assets/${defaultAvatarId}.png`;
244 } else {
245 defaultAvatarId = parseInt(discriminator) % 5;
246 webhookJson.avatar_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarId}.png`;
247 }
248 }
249 }
250
251 // Embeds
252 if (message.embeds) {
253
254 webhookJson.embeds = message.embeds.map(embed => {
255 const webhookEmbed = {};
256 // console.log(embed);
257 if (embed.rawTitle) webhookEmbed.title = embed.rawTitle;
258 if (embed.title) webhookEmbed.title = embed.title;
259 if (embed.rawDescription) webhookEmbed.description = embed.rawDescription;
260 if (embed.description) webhookEmbed.description = embed.description;
261 if (embed.url) webhookEmbed.url = embed.url;
262
263 // Color
264 // Original snippet with the added HSLA handling
265 if (embed.color !== undefined) {
266 if (typeof embed.color === 'string') {
267 try {
268 // Check if the color string is an HSLA value
269 if (embed.color.startsWith('hsl')) {
270 const hexColor = hslaToHex(embed.color);
271 if (hexColor !== null) {
272 webhookEmbed.color = hexColor;
273 } else {
274 // Handle the case where HSLA parsing failed
275 console.error("Could not convert HSLA color to hex:", embed.color);
276 // Optionally set a default color or leave it undefined
277 webhookEmbed.color = 0; // Example: set to black
278 }
279 } else {
280 // Assume it's a hex string if not HSLA
281 webhookEmbed.color = parseInt(embed.color.replace('#', ''), 16);
282 }
283 } catch (e) {
284 console.error("Failed to process embed color string:", embed.color, e);
285 }
286 } else if (typeof embed.color === 'number') {
287 webhookEmbed.color = embed.color;
288 }
289 }
290
291 if (embed.timestamp) webhookEmbed.timestamp = embed.timestamp;
292
293 if (embed.footer) {
294 const webhookFooter = {};
295 if (embed.footer.text) webhookFooter.text = embed.footer.text;
296 if (embed.footer.icon_url) webhookFooter.icon_url = embed.footer.icon_url;
297 if (Object.keys(webhookFooter).length > 0) webhookEmbed.footer = webhookFooter;
298 }
299
300 if (embed.image) {
301 const webhookImage = {};
302 if (embed.image.url) webhookImage.url = embed.image.url;
303 if (Object.keys(webhookImage).length > 0) webhookEmbed.image = webhookImage;
304 }
305
306 if (embed.thumbnail) {
307 const webhookThumbnail = {};
308 if (embed.thumbnail.url) webhookThumbnail.url = embed.thumbnail.url;
309 if (Object.keys(webhookThumbnail).length > 0) webhookEmbed.thumbnail = webhookThumbnail;
310 }
311
312 if (embed.author) {
313 const webhookAuthor = {};
314 if (embed.author.name) webhookAuthor.name = embed.author.name;
315 if (embed.author.url) webhookAuthor.url = embed.author.url;
316 if (embed.author.icon_url) webhookAuthor.icon_url = embed.author.icon_url;
317 if (Object.keys(webhookAuthor).length > 0) webhookEmbed.author = webhookAuthor;
318 }
319
320 if (embed.fields && embed.fields.length > 0) {
321 webhookEmbed.fields = embed.fields.map(field => {
322 const webhookField = {};
323 if (field.name) webhookField.name = field.name;
324 if (field.value) webhookField.value = field.value;
325 if (field.inline !== undefined) webhookField.inline = field.inline;
326 return webhookField;
327 });
328 }
329
330 return webhookEmbed;
331 }).filter(embed => Object.keys(embed).length > 0);
332 }
333
334 return webhookJson;
335 }
336
337 // --- JSON Viewer Functions ---
338 function createJsonDisplayBox() {
339 jsonDisplayBox = document.createElement('div');
340 jsonDisplayBox.id = 'discord-message-json-display';
341 jsonDisplayBox.style.display = 'none'; // Initially hidden
342
343 const header = document.createElement('div');
344 header.className = 'header';
345 // Create a text node as the first child
346 header.appendChild(document.createTextNode('Discord Message JSON Data'));
347
348 const controls = document.createElement('div');
349 controls.style.cssText = 'display: flex; align-items: center;';
350
351 // Webhook Toggle
352 const webhookToggleLabel = document.createElement('label');
353 webhookToggleLabel.style.cssText = 'font-weight: normal; font-size: 10px; margin-right: 10px; display: flex; align-items: center; cursor: pointer;';
354 webhookToggleLabel.textContent = 'Webhook Format';
355
356 const webhookToggle = document.createElement('input');
357 webhookToggle.type = 'checkbox';
358 webhookToggle.style.cssText = 'margin-right: 5px; cursor: pointer;';
359 webhookToggle.addEventListener('change', function() {
360 isWebhookFormat = this.checked;
361 if (currentMessage) {
362 // Only update content, not the entire structure
363 const jsonToDisplay = isWebhookFormat ? convertMessageToWebhookJson(currentMessage) : currentMessage;
364 const jsonString = jsonToDisplay ? JSON.stringify(jsonToDisplay, null, 2) : 'Could not retrieve message data.';
365 const contentElement = document.getElementById('discord-message-json-content');
366 contentElement.textContent = jsonString;
367
368 // Apply our own highlighting
369 highlightJsonContent();
370 }
371 // Update header text but preserve the DOM structure
372 const headerText = document.querySelector('#discord-message-json-display .header');
373 const headerTitle = headerText.childNodes[0];
374 headerTitle.textContent = isWebhookFormat ? 'Discord Webhook JSON Data' : 'Discord Message JSON Data';
375 });
376
377 webhookToggleLabel.prepend(webhookToggle);
378 controls.appendChild(webhookToggleLabel);
379
380 // Copy Button
381 const copyButton = document.createElement('div');
382 copyButton.style.cssText = 'font-weight: normal; font-size: 10px; margin-right: 10px; cursor: pointer; display: flex; align-items: center;';
383 copyButton.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/></svg>';
384 copyButton.innerHTML += '<span style="margin-left: 4px;">Copy</span>';
385
386 copyButton.onclick = () => {
387 const jsonContent = document.getElementById('discord-message-json-content');
388
389 // Get the plain text content, not the highlighted HTML
390 let textToCopy = '';
391 if (currentMessage) {
392 const jsonToDisplay = isWebhookFormat ? convertMessageToWebhookJson(currentMessage) : currentMessage;
393 textToCopy = JSON.stringify(jsonToDisplay, null, 2);
394 } else {
395 textToCopy = jsonContent.textContent;
396 }
397
398 // Copy to clipboard
399 navigator.clipboard.writeText(textToCopy)
400 .then(() => {
401 // Visual feedback
402 const originalText = copyButton.querySelector('span').textContent;
403 copyButton.querySelector('span').textContent = 'Copied!';
404 setTimeout(() => {
405 copyButton.querySelector('span').textContent = originalText;
406 }, 1000);
407 })
408 .catch(err => {
409 console.error('Failed to copy JSON: ', err);
410 });
411 };
412
413 controls.appendChild(copyButton);
414
415 const closeButton = document.createElement('span');
416 closeButton.style.cssText = 'margin-left: 10px; cursor: pointer; font-size: 16px; color: var(--interactive-normal);';
417 closeButton.textContent = '✕';
418 closeButton.onclick = () => {
419 jsonDisplayBox.style.display = 'none';
420 };
421
422 controls.appendChild(closeButton);
423 header.appendChild(controls);
424 jsonDisplayBox.appendChild(header);
425
426 const content = document.createElement('pre');
427 content.id = 'discord-message-json-content';
428 jsonDisplayBox.appendChild(content);
429
430 document.body.appendChild(jsonDisplayBox);
431
432 // Make the box draggable
433 header.addEventListener('mousedown', (e) => {
434 if (e.button !== 0) return;
435 isDragging = true;
436 dragOffsetX = e.clientX - jsonDisplayBox.getBoundingClientRect().left;
437 dragOffsetY = e.clientY - jsonDisplayBox.getBoundingClientRect().top;
438 jsonDisplayBox.style.cursor = 'grabbing';
439 document.body.style.userSelect = 'none';
440 });
441
442 document.addEventListener('mousemove', (e) => {
443 if (!isDragging) return;
444 jsonDisplayBox.style.left = (e.clientX - dragOffsetX) + 'px';
445 jsonDisplayBox.style.top = (e.clientY - dragOffsetY) + 'px';
446 });
447
448 document.addEventListener('mouseup', () => {
449 isDragging = false;
450 if (jsonDisplayBox) jsonDisplayBox.style.cursor = '';
451 document.body.style.userSelect = '';
452 });
453 }
454
455 function highlightJsonContent() {
456 const codeElement = document.getElementById('discord-message-json-content');
457 if (!codeElement) return;
458
459 // Get the text content
460 const text = codeElement.textContent;
461
462 // JSON syntax highlighting with colons preserved
463 let highlighted = text.replace(
464 /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
465 function (match) {
466 let cls = 'json-number';
467 if (/^"/.test(match)) {
468 if (/:$/.test(match)) {
469 cls = 'json-key';
470 // Don't remove the colon
471 } else {
472 cls = 'json-string';
473 }
474 } else if (/true|false/.test(match)) {
475 cls = 'json-boolean';
476 } else if (/null/.test(match)) {
477 cls = 'json-null';
478 }
479
480 return `<span class="${cls}">${match}</span>`;
481 }
482 );
483
484 // Also highlight brackets and punctuation (but not colons as they're already handled)
485 highlighted = highlighted.replace(/[{}\[\],]/g, function(match) {
486 return `<span class="json-punctuation">${match}</span>`;
487 });
488
489 codeElement.innerHTML = highlighted;
490 }
491
492 function displayMessageJson(message) {
493 if (!jsonDisplayBox) {
494 createJsonDisplayBox();
495 }
496
497 currentMessage = message;
498
499 let jsonToDisplay = null;
500 if (currentMessage) {
501 if (isWebhookFormat) {
502 jsonToDisplay = convertMessageToWebhookJson(currentMessage);
503 } else {
504 jsonToDisplay = currentMessage;
505 }
506 }
507
508 const jsonString = jsonToDisplay ? JSON.stringify(jsonToDisplay, null, 2) : 'Could not retrieve message data.';
509 const contentElement = document.getElementById('discord-message-json-content');
510 contentElement.textContent = jsonString;
511
512 // Apply our custom syntax highlighting
513 highlightJsonContent();
514
515 jsonDisplayBox.style.display = 'flex';
516 }
517
518 // Handle message clicks for JSON viewing
519 function handleMessageClick(event) {
520 if (!isScriptActive) return;
521
522 const target = event.target;
523 const messageElement = target.closest('[id^="message-"]');
524
525 if (messageElement) {
526 // Skip if clicking interactive elements
527 const interactiveElements = target.closest('a, button, .markup-2BOw-j');
528 if (interactiveElements && !interactiveElements.classList.contains('embedWrapper-lXp9gn')) {
529 return;
530 }
531
532 const reactInstance = findReactInstance(messageElement);
533 if (reactInstance) {
534 const message = getMessageFromReactInstance(reactInstance);
535 if (message) {
536 displayMessageJson(message);
537 return;
538 }
539 }
540
541 // log.warn("Could not find React instance for message element.");
542 if (jsonDisplayBox && document.getElementById('discord-message-json-content')) {
543 document.getElementById('discord-message-json-content').textContent = 'Could not retrieve message data.';
544 currentMessage = null;
545 }
546 }
547 }
548
549 // --- Button Creation and Mounting ---
550 let jsonViewerBtn = null;
551
552 function createJsonViewerButton() {
553 // Create button container
554 jsonViewerBtn = document.createElement('div');
555 jsonViewerBtn.id = 'json-viewer-btn';
556 jsonViewerBtn.setAttribute('role', 'button');
557 jsonViewerBtn.setAttribute('aria-label', 'View Message JSON');
558 jsonViewerBtn.setAttribute('tabindex', '0');
559 jsonViewerBtn.title = 'View Message JSON';
560 jsonViewerBtn.style.cssText = `
561 position: relative;
562 width: auto;
563 height: 24px;
564 margin: 0 8px;
565 cursor: pointer;
566 color: var(--interactive-normal);
567 flex: 0 0 auto;
568 display: flex;
569 align-items: center;
570 justify-content: center;
571 `;
572 jsonViewerBtn.innerHTML = jsonSvgIcon;
573
574 // Add click handler
575 jsonViewerBtn.onclick = () => {
576 if (jsonDisplayBox) {
577 jsonDisplayBox.style.display = jsonDisplayBox.style.display === 'none' ? 'flex' : 'none';
578 } else {
579 createJsonDisplayBox();
580 jsonDisplayBox.style.display = 'flex';
581 }
582 };
583
584 // Add hover effects
585 jsonViewerBtn.onmouseover = () => {
586 jsonViewerBtn.style.color = 'var(--interactive-hover)';
587 };
588
589 jsonViewerBtn.onmouseout = () => {
590 jsonViewerBtn.style.color = 'var(--interactive-normal)';
591 };
592
593 return jsonViewerBtn;
594 }
595
596 function mountJsonViewerButton() {
597 const toolbar = document.querySelector('#app-mount [class^=toolbar]');
598 if (toolbar) {
599 // Check if button already exists
600 if (!document.getElementById('json-viewer-btn')) {
601 if (!jsonViewerBtn) {
602 jsonViewerBtn = createJsonViewerButton();
603 }
604 toolbar.appendChild(jsonViewerBtn);
605 console.log('Mounted JSON Viewer button');
606 }
607 }
608 }
609
610 function initJsonViewer() {
611 // Insert CSS
612 insertCss(themeCss);
613
614 // Create button
615 createJsonViewerButton();
616
617 // Create display box (initially hidden)
618 createJsonDisplayBox();
619
620 // Mount button
621 mountJsonViewerButton();
622
623 // Add message click listener
624 document.addEventListener('click', handleMessageClick, true);
625
626 // Setup observer to re-mount button if needed
627 const discordElm = document.querySelector('#app-mount');
628 if (discordElm) {
629 const observer = new MutationObserver(() => {
630 if (observerThrottle) return;
631 observerThrottle = setTimeout(() => {
632 observerThrottle = null;
633 if (!document.body.contains(jsonViewerBtn)) {
634 mountJsonViewerButton();
635 }
636 }, 3000);
637 });
638
639 observer.observe(discordElm, { childList: true, subtree: true });
640 }
641
642 console.log('JSON Viewer initialized successfully');
643 }
644
645 // Initialize when the page loads
646 if (document.readyState === 'loading') {
647 window.addEventListener('DOMContentLoaded', initJsonViewer);
648 } else {
649 initJsonViewer();
650 }
651})();
652