PageSourceSearch

https://www.aimen.es/assets/js/CustomGoogleTranslate.js?kc=202609160954

js aimen.es collected 2026-10-03 19:08:11 UTC 12,512 bytes, 293 lines download raw bytes

1let HOST = window.location.origin;
2const TRANSLATE_LANGS_MAP = {
3    es: {
4        gtText: "español",   // texto que se usa en Google Translate en el iframe (en algunos casos habrá que comprobar cuál es)
5        displayText: "Español", // texto que se muestra en el selector
6        confDesignation: "es"  // abreviatura usada como nombre del archivo de configuracion /templates/configs/{confDesignation}.conf
7    },
8    gl: {gtText: "gallego", displayText: "Galego", confDesignation: "gl"},
9    // eu: {gtText: "euskera", displayText: "Euskera"},
10    // ca: {gtText: "catalán", displayText: "Català"},
11    en: {gtText: "inglés", displayText: "English", confDesignation: "en"},
12    // fr: {gtText: "francés", displayText: "Francés"},
13    // "pt-PT": {gtText: "portugués (portugal)", displayText: "Português"}
14};
15
16
17const CustomTranslator = function () {
18    // Google Translate methods
19    function _onClick_simulateCloseGoogleTranslate() {
20        var translateIframe = $('#\\:2\\.container');
21        if (translateIframe.length > 0) {
22            // Get the iframe's document
23            var iframeDocument = translateIframe[0].contentDocument || translateIframe[0].contentWindow.document;
24            // Find and click the close button inside the iframe
25            var closeButton = iframeDocument.querySelector('#\\:2\\.close');
26            if (closeButton) {
27                closeButton.click();
28            }
29        }
30    }
31
32    function getCurrentGoogleTranslateLang() {
33        const match = document.cookie.match(/googtrans=\/[^/]+\/([^;]+)/);
34        return match ? match[1] : 'es';
35    }
36
37    function getCurrentLangName() {
38        const code = getCurrentGoogleTranslateLang();
39        return TRANSLATE_LANGS_MAP[code]?.gtText || code;
40    }
41
42    function getConfLang(content) {
43        const chosenOpt = Object.values(TRANSLATE_LANGS_MAP).find(opt => opt.gtText === content);
44        return chosenOpt ? chosenOpt.confDesignation : '';
45    }
46
47    function getGLangAbbrFromConfLang(confLang) {
48        const entry = Object.entries(TRANSLATE_LANGS_MAP).find(([key, val]) => key === confLang);
49        const gLangAbbr = entry ? entry[1].confDesignation : null;
50        return gLangAbbr;
51    }
52
53    function getLangDisplayableText(content) {
54        const text = Object.values(TRANSLATE_LANGS_MAP).find(opt => opt.gtText === content);
55        return text ? text.displayText : content.toUpperCase();
56    }
57
58    const defaultSelectValues = function () {
59        const defaultLang = __retrievePageLang();
60
61        $(document).on('change', '.google_translate_puppeteer', function () {
62            const chosenOpt = $(this).find('option:selected');
63            const confLang = chosenOpt.data('conf-lang');
64
65            setTimeout(function () {
66                __saveLongTermLangCookie(confLang);
67                __reloadSmartyLngConf(confLang);
68            }, 1000)
69        })
70
71        const defaultLanguagesLoaderObv = new MutationObserver(function (mutationList, observer) {
72            mutationList.forEach(mutation => {
73                const $defaultSelect = $('.google_translate_puppeteer');
74
75                if ($defaultSelect.length > 0) {
76                    observer.disconnect();
77                    $defaultSelect.empty();
78                    Object.entries(TRANSLATE_LANGS_MAP).forEach(([langCode, langAttrbs]) => {
79                            let $option = $('<option>', {
80                                value: langCode,
81                                text: langAttrbs.displayText,
82                                class: "skiptranslate"
83                            });
84                            $option.data('conf-lang', langAttrbs.confDesignation)
85                            if (langCode === defaultLang) {
86                                $option.attr('selected', true);
87                            }
88
89                            $defaultSelect.append($option);
90                        }
91                    )
92                }
93            })
94        });
95        defaultLanguagesLoaderObv.observe(document, {subtree: true, childList: true});
96
97    }
98
99    const __handlePseudoGoogleTranslateSelector = function () {
100        const iframes = document.querySelectorAll('iframe.skiptranslate');
101
102        const initObserver = new MutationObserver((mutations) => {
103            mutations.forEach(mutation => {
104                if (mutation.addedNodes.length > 0) {
105                    mutation.addedNodes.forEach(addedNode => {
106                        if (addedNode.nodeType === Node.ELEMENT_NODE && addedNode.tagName === 'IFRAME') {
107                            const iframe = addedNode;
108                            iframe.addEventListener('load', () => {
109                                try {
110                                    const doc = iframe.contentDocument || iframe.contentWindow.document;
111                                    var $container = $(doc).find('[id=":1.menuBody"]');
112
113                                    if ($container) {
114                                        initObserver.disconnect();
115
116                                        const observer = new MutationObserver((mutationsList) => {
117                                            if ($(mutationsList[1].addedNodes[0]).find('a').length === TRANSLATE_LANGS.length) {
118                                                observer.disconnect();
119
120                                                var $container = $(doc).find('[id=":1.menuBody"]');
121
122                                                mapGoogleTranslateLangs($container);
123                                            }
124                                            ;
125                                        });
126                                        observer.observe(doc.body, {childList: true, subtree: true});
127                                    }
128                                } catch (e) {
129                                    console.warn("No se puede acceder al documento del iframe (probable cross-domain).");
130                                }
131                            })
132                        }
133                    })
134                }
135            })
136        })
137        initObserver.observe(document, {childList: true, subtree: true});
138    }
139
140
141    const mapGoogleTranslateLangs = function (container) {
142        const $actualGoogleTranslateOptions = container.find('a');
143        const $select = $('.google_translate_puppeteer');
144
145
146        if ($actualGoogleTranslateOptions.length > 2) {   // >2 o >1 si no hay suficientes idiomas en la configuracion elegidos
147            $select.empty();
148
149            $actualGoogleTranslateOptions.each((i, a) => {
150                const content = $(a).find('span.text').text();
151
152                let $option;
153                if (content === 'Seleccionar idioma' || content.toLowerCase() === 'español') {
154                    $option = $('<option>', {
155                        value: 'español',
156                        text: getLangDisplayableText('español'),
157                        class: "skiptranslate"
158                    });
159                    $option.data('conf-lang', 'es');
160                } else {
161                    const lowerCContent = content.toLowerCase();
162                    $option = $('<option>', {
163                        value: lowerCContent,
164                        text: getLangDisplayableText(lowerCContent),
165                        class: "skiptranslate"
166                    });
167                    $option.data('conf-lang', getConfLang(lowerCContent))
168                }
169                $select.append($option);
170            })
171            const gLang = getCurrentLangName();
172            $select.val(gLang);
173
174            $select.off('change').on('change', function () {
175                const chosenOpt = $(this).find('option:selected');
176                const selectedValue = chosenOpt.val();
177                let confLang = "es";
178
179                if (selectedValue === 'español') {
180                    _onClick_simulateCloseGoogleTranslate();
181                } else {
182                    const matchingLink = $actualGoogleTranslateOptions
183                        .filter((i, a) => $(a).find('span.text').text().toLowerCase() === selectedValue);
184                    if (matchingLink.length) {
185                        matchingLink[0].click();
186                    }
187                    confLang = chosenOpt.data('conf-lang');
188                }
189
190                const defaultLang = confLang === 'es' ? 'es' : null;
191
192                // TODO: mejorar implementacion de setTimeout
193                setTimeout(function () {
194                    __saveLongTermLangCookie(defaultLang);
195                    __reloadSmartyLngConf(confLang);
196                }, 1000)
197            });
198        }
199    }
200    const __syncroTranslationSelects = function () {
201        $(document).on('change', '.google_translate_puppeteer', function () {
202            const value = $(this).val();
203
204            $('.google_translate_puppeteer').not(this).each(function () {
205                if ($(this).val() !== value) {
206                    $(this).val(value);
207                }
208            });
209        });
210    };
211
212    const __reloadSmartyLngConf = function (confLang) {
213        const url = window.location.href.replace(HOST, "");
214        const pathParts = url.split("/").filter(Boolean);
215
216        if (pathParts.length > 0 && /^[a-z]{2}$/.test(pathParts[0])) {
217            // Si es una abreviatura de idioma
218            pathParts[0] = confLang;
219        } else {
220            pathParts.unshift(confLang);
221        }
222
223        const updatedUrl = HOST + '/' + pathParts.join('/');
224        window.location.href = updatedUrl;
225    }
226
227    const __retrievePageLang = function () {
228        const longLastingLangCookie = document.cookie.match(/lastsessionlang=\/[^/]+\/([^;]+)/);
229        let googLangAbbr = 'es';
230        const urlParts = __retrieveURLLang();
231        const foundLang = urlParts.find(el=>/^[a-z]{2}$/.test(el))
232        if(foundLang){
233            googLangAbbr = getGLangAbbrFromConfLang(foundLang);
234        }else if(longLastingLangCookie !== null && longLastingLangCookie.length > 0) {
235            const lastSessLgCookie = __retrieveLongTermLangCookie(longLastingLangCookie[0]);
236            if (lastSessLgCookie) {
237                googLangAbbr = lastSessLgCookie.split('/')[2];
238            }
239        }
240        return googLangAbbr;
241    }
242
243    const __retrieveURLLang = function () {
244        const url = window.location.href.replace(HOST, "");
245        const urlParts = url.split("/").filter(Boolean);
246
247        if (urlParts === null || urlParts.length === 0) return null;
248
249        return urlParts;
250    }
251
252    const __onLoadPageLoadLang = function () {
253        const googLangAbbr = __retrievePageLang();
254        const host = new URL(HOST).hostname;
255        const domain = `.${host.replace(/^www\./, '')}`;
256
257        document.cookie = `googtrans=/es/${googLangAbbr}; domain=${domain}; path=/`;
258        document.cookie = `googtrans=/es/${googLangAbbr}; path=/`;
259        // document.cookie = `googtrans=/es/${googLangAbbr}; domain=.${host}; path=/`;
260    }
261
262    const __saveLongTermLangCookie = function (googLangAbbr = null) {
263        const googleLgCookie = document.cookie.match(/googtrans=\/[^/]+\/([^;]+)/);
264        if (googLangAbbr === null && googleLgCookie) {
265            googLangAbbr = googleLgCookie[0].split('/')[2];
266        }
267        if (googLangAbbr) {
268            const date = new Date();
269            date.setTime(date.getTime() + (6 * 24 * 60 * 60 * 1000));
270            const expires = "expires=" + date.toUTCString();
271            const host = new URL(HOST).hostname;
272            const domain = `.${host.replace(/^www\./, '')}`;
273            document.cookie = `lastsessionlang=/es/${googLangAbbr}; domain=${domain}; ${expires}; path=/;`;
274        }
275    }
276
277    const __retrieveLongTermLangCookie = function (cookieValue) {
278        const lastSessLgCookie = cookieValue ? cookieValue : document.cookie.match(/lastsessionlang=\/[^/]+\/([^;]+)/)[0];
279
280        return lastSessLgCookie;
281    }
282
283    return {
284        init: function () {
285            defaultSelectValues();
286            __handlePseudoGoogleTranslateSelector();
287            __onLoadPageLoadLang();
288            __syncroTranslationSelects();
289        }
290    }
291}();
292
293CustomTranslator.init();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.