最終更新 1745295964

修正履歴 e4f39c87e90b9b88b784bf390bd1b9b58629787e

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