|
| 1 | +document.addEventListener('DOMContentLoaded', () => { |
| 2 | + const messagesContainer = document.getElementById('messages'); |
| 3 | + |
| 4 | + // Function to add a new message to the container |
| 5 | + function addMessage(message) { |
| 6 | + const messageElement = document.createElement('div'); |
| 7 | + messageElement.className = 'message'; |
| 8 | + |
| 9 | + // Try to stringify objects for better display |
| 10 | + let messageText; |
| 11 | + try { |
| 12 | + messageText = typeof message === 'object' |
| 13 | + ? JSON.stringify(message, null, 2) |
| 14 | + : String(message); |
| 15 | + } catch (error) { |
| 16 | + messageText = 'Unable to display message: ' + error.message; |
| 17 | + } |
| 18 | + |
| 19 | + // Create a pre element for formatted JSON display |
| 20 | + const preElement = document.createElement('pre'); |
| 21 | + preElement.textContent = messageText; |
| 22 | + messageElement.appendChild(preElement); |
| 23 | + |
| 24 | + // Add the message at the top of the container |
| 25 | + messagesContainer.insertBefore(messageElement, messagesContainer.firstChild); |
| 26 | + } |
| 27 | + |
| 28 | + // Listen for messages from the iframe |
| 29 | + window.addEventListener('message', (event) => { |
| 30 | + // Check if the message is from the expected origin |
| 31 | + if (!event.origin.match(/^https?:\/\/(.*\.)?figurl\.org$/)) { |
| 32 | + console.warn('Received message from unexpected origin:', event.origin); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + // Log the raw event for debugging |
| 37 | + console.log('Received message event:', event); |
| 38 | + |
| 39 | + // Add the message data to the display |
| 40 | + addMessage({ |
| 41 | + origin: event.origin, |
| 42 | + data: event.data, |
| 43 | + timestamp: new Date().toISOString() |
| 44 | + }); |
| 45 | + }); |
| 46 | + |
| 47 | + // Add initial message |
| 48 | + addMessage('Listening for messages...'); |
| 49 | +}); |
0 commit comments