Ich konnte Google Translate zwingen, Text zwischen den Tags <code.....> und </code> auf meiner Webseite zu übersetzen, aHTML

HTML-Programmierer
Anonymous
 Ich konnte Google Translate zwingen, Text zwischen den Tags <code.....> und </code> auf meiner Webseite zu übersetzen, a

Post by Anonymous »

Ich konnte Google Translate zwingen, Text zwischen - und -Tags auf meiner Webseite zu übersetzen, indem ich Code durch span ersetzte. Aber wie kann ich span wieder in code zurücksetzen, nachdem Google Translate fertig ist?
Ich habe online gelesen, dass das

Code: Select all

-Tag durch ein  span.setAttribute(attr.name, attr.value));
span.classList.add('translated-span');
span.innerHTML = code.innerHTML;
// Insert new span before the code and remove the code
code.parentNode.insertBefore(span, code);
code.parentNode.removeChild(code);
});
}

// Function to apply the data-original-tag attribute
function applyOriginalTagAttribute() {
// Select all  elements that have a specific class added by Google Translate
// (e.g., 'notranslate' or a specific class you might have added to original  elements)
// Or, more generally, iterate through all  elements and apply a heuristic.
// For this example, we'll assume a class 'original-code' was present on the  elements.
const spans = document.querySelectorAll('span.original-code');

spans.forEach(span => {
// Check if the  element was likely a  element before translation.
// This might involve checking for specific content patterns, or relying on a class
// that was present on the original  element and persisted through translation.
// For a robust solution, you might need to pre-process or add unique identifiers.

// For simplicity, if we assume the original  element had a class 'original-code',
// and this class is retained by the  after translation:
if (span.classList.contains('original-code')) {
span.setAttribute('data-original-tag', 'code');
// You might also remove the 'original-code' class if it's no longer needed on the 
// span.classList.remove('original-code');
}
});
}

// Function to revert  back to 
function revertSpanToCode() {
console.log("Reverting span to code...");
const spans = document.querySelectorAll('span');
spans.forEach(span => {
// 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');
}
})();
HTML

Code: Select all

&#9776;Menu
Bitte posten Sie die gesamte Javascript-Lösung als Antwort, damit ich sie als Antwort auswählen kann (falls sie funktioniert)

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post