File size: 1,626 Bytes
526c164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * Script for Hugging Face Spaces parent window
 * This script listens to iframe messages and updates the parent window URL
 * 
 * Usage instructions:
 * 1. Add this script to your Hugging Face Space in app.py or in a Gradio component
 * 2. Or use it in an HTML page that contains your iframe
 */

(function () {
    'use strict';

    // Listen to iframe messages
    window.addEventListener('message', function (event) {

        // Check message type
        if (event.data && event.data.type) {
            switch (event.data.type) {
                case 'urlChange':
                case 'anchorChange':
                case 'HF_SPACE_URL_UPDATE':
                    handleUrlChange(event.data);
                    break;
                default:
                // Unknown message type, ignore
            }
        }
    });

    function handleUrlChange(data) {
        try {
            const hash = data.hash || data.anchorId;

            if (hash) {
                // Update URL with new anchor
                const newUrl = new URL(window.location);
                newUrl.hash = hash;

                // Use replaceState to avoid adding an entry to history
                window.history.replaceState(null, '', newUrl.toString());
            }
        } catch (error) {
            // Silent error when updating URL
        }
    }

    // Utility function to test communication
    window.testIframeCommunication = function () {
        const iframe = document.querySelector('iframe');
        if (iframe) {
            iframe.contentWindow.postMessage({ type: 'test' }, '*');
        }
    };

})();