и тегами на моей веб-странице, но как снова вернуть диапазон в код после завершения работы Google Translate?
Я читал в Интернете, что тег {
// Ensure we only target spans that were part of our replacement logic if possible,
// or ensure no other spans on the page are accidentally affected.
// A better approach might be to add a specific class during the initial replacement.
// For this general example, we assume we want to revert all spans back to codes (which might be too broad).
// A safer way is using a specific marker class or ID.
// Assuming we add a class 'translated-span' during replacement:
if (span.classList.contains('translated-span')) {
const code = document.createElement('code');
Array.from(span.attributes).forEach(attr => code.setAttribute(attr.name, attr.value));
code.innerHTML = span.innerHTML;
span.parentNode.insertBefore(code, span);
span.parentNode.removeChild(span);
}
});
}
// Use MutationObserver to detect Google Translate completion
const observerCallback = (mutationsList, observer) => {
const htmlEl = document.documentElement;
const isTranslated = htmlEl.classList.contains('translated-ltr') || htmlEl.classList.contains('translated-rtl');
if (isTranslated) {
// Page has been translated
console.log("Google Translate detected. Applying span replacements.");
replaceCodeWithSpan();
// You might want to disconnect the observer once done if you don't need further dynamic updates
// observer.disconnect();
} else {
// Translation was likely reverted to original language
console.log("Google Translate reverted or not active. Reverting code replacements if any.");
revertSpanToCode();
}
};
// Configuration for the observer: watch for attribute changes on the element
const observerConfig = { attributes: true, attributeFilter: ['class'], childList: false, characterData: false };
const observer = new MutationObserver(observerCallback);
// --- Your existing Google Translate Element initialization code should be here ---
// This part should be after the definition of the functions above.
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en', // Set your original page language
layout: google.translate.TranslateElement.InlineLayout.VERTICAL // Change this line
}, 'google_translate_element');
setTimeout(revertSpanToCode, 1000); // Adjust delay as needed
}
// --------------------------------------------------------------------------------
// Start observing the element for class changes (which the translator does)
observer.observe(document.documentElement, observerConfig);
/**
* Executes immediately when the page loads.
* Checks if the page was just refreshed via our logic, and cleans up the storage flag.
*/
(function checkAndClearRefreshFlag() {
if (localStorage.getItem('hasRefreshed') === 'true') {
// The page just reloaded as intended; clear the flag.
localStorage.removeItem('hasRefreshed');
console.log('Page was refreshed once and the flag has been cleared.');
}
})();
/**
* Your function that processes data before the refresh.
* Replace the console log with your actual translation logic.
*/
function revertTranslation() {
var translatedSpans = document.querySelectorAll('span[data-original-tag="code"]');
translatedSpans.forEach(function(span) {
var originalTag = span.getAttribute('data-original-tag');
var code = document.createElement(originalTag);
code.innerHTML = span.innerHTML;
span.parentNode.replaceChild(code, span); // Replace span with original code tag
});
}
(function()
if (sessionStorage.getItem('isGTReloaded') !== 'yes') {
sessionStorage.setItem('isGTReloaded', 'yes');
location.reload();
} else {
sessionStorage.removeItem('isGTReloaded');
}
})();
Мне удалось заставить Google Translate переводить текст между [code] и тегами на моей веб-странице, но как снова вернуть диапазон в код после завершения работы Google Translate? Я читал в Интернете, что тег { // Ensure we only target spans that were part of our replacement logic if possible, // or ensure no other spans on the page are accidentally affected. // A better approach might be to add a specific class during the initial replacement.
// For this general example, we assume we want to revert all spans back to codes (which might be too broad). // A safer way is using a specific marker class or ID. // Assuming we add a class 'translated-span' during replacement: if (span.classList.contains('translated-span')) { const code = document.createElement('code'); Array.from(span.attributes).forEach(attr => code.setAttribute(attr.name, attr.value)); code.innerHTML = span.innerHTML; span.parentNode.insertBefore(code, span); span.parentNode.removeChild(span); } }); }
// Use MutationObserver to detect Google Translate completion const observerCallback = (mutationsList, observer) => { const htmlEl = document.documentElement; const isTranslated = htmlEl.classList.contains('translated-ltr') || htmlEl.classList.contains('translated-rtl');
if (isTranslated) { // Page has been translated console.log("Google Translate detected. Applying span replacements."); replaceCodeWithSpan(); // You might want to disconnect the observer once done if you don't need further dynamic updates // observer.disconnect(); } else { // Translation was likely reverted to original language console.log("Google Translate reverted or not active. Reverting code replacements if any."); revertSpanToCode(); } };
// Configuration for the observer: watch for attribute changes on the element const observerConfig = { attributes: true, attributeFilter: ['class'], childList: false, characterData: false }; const observer = new MutationObserver(observerCallback);
// --- Your existing Google Translate Element initialization code should be here --- // This part should be after the definition of the functions above. function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en', // Set your original page language layout: google.translate.TranslateElement.InlineLayout.VERTICAL // Change this line }, 'google_translate_element'); setTimeout(revertSpanToCode, 1000); // Adjust delay as needed } // --------------------------------------------------------------------------------
// Start observing the element for class changes (which the translator does) observer.observe(document.documentElement, observerConfig); /** * Executes immediately when the page loads. * Checks if the page was just refreshed via our logic, and cleans up the storage flag. */ (function checkAndClearRefreshFlag() { if (localStorage.getItem('hasRefreshed') === 'true') { // The page just reloaded as intended; clear the flag. localStorage.removeItem('hasRefreshed'); console.log('Page was refreshed once and the flag has been cleared.'); } })();
/** * Your function that processes data before the refresh. * Replace the console log with your actual translation logic. */ function revertTranslation() { var translatedSpans = document.querySelectorAll('span[data-original-tag="code"]'); translatedSpans.forEach(function(span) { var originalTag = span.getAttribute('data-original-tag'); var code = document.createElement(originalTag); code.innerHTML = span.innerHTML; span.parentNode.replaceChild(code, span); // Replace span with original code tag }); } (function() if (sessionStorage.getItem('isGTReloaded') !== 'yes') { sessionStorage.setItem('isGTReloaded', 'yes'); location.reload(); } else { sessionStorage.removeItem('isGTReloaded'); } })(); [/code] [b]HTML[/b] [code]☰Menu[/code]
Пожалуйста, опубликуйте все решение Javascript в качестве ответа, чтобы я мог выбрать его в качестве ответа (если оно работает)