Cordova移动端应用本地化字符串调用异常问题求助
Hey there, let's tackle this issue where your {#skip#} placeholder isn't getting replaced with the correct localized string in your Cordova app. Here are some step-by-step troubleshooting and fix ideas:
1. Add a proper string replacement function (and run it at the right time)
You've got your kStrings object set up correctly, but there's no logic to actually swap those {#key#} placeholders with real strings. Let's build that first:
// Ensure kStrings is accessible globally (or pass it to the function if using modules) const kStrings = { fr: { skip: "passer" }, en: { skip: "skip" } }; function replaceLocalizedStrings() { // Get your active language (pull this from localStorage, user settings, or default to 'en') const currentLang = "en"; // Scan all elements with plain text content for {#key#} patterns document.querySelectorAll('body *').forEach(element => { // Target only elements with a single text node (avoid nested elements) if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) { const originalText = element.textContent; // Replace placeholders with matching strings from kStrings element.textContent = originalText.replace( /\{#(\w+)#\}/g, (match, key) => kStrings[currentLang][key] || match // Keep placeholder if key is missing ); } }); }
Now the critical part: run this function at the right moment. In Cordova, always wait for the deviceready event (Cordova APIs aren't ready before that) plus ensure the DOM is fully loaded:
document.addEventListener('deviceready', () => { if (document.readyState === 'complete') { replaceLocalizedStrings(); } else { document.addEventListener('DOMContentLoaded', replaceLocalizedStrings); } });
2. Fix the placeholder reappearing after link clicks
If the text reverts to {#skip#} when you click the link, the DOM element is likely being re-rendered (e.g., dynamic content updates, partial page refreshes, or a click handler resetting the text).
- If your link triggers dynamic content changes, call
replaceLocalizedStrings()again after the content finishes updating. - Double-check your click event handlers to make sure they aren't accidentally overwriting the link's text content.
3. Verify kStrings is accessible
If the replacement function can't reach kStrings, it'll leave the placeholder untouched. Confirm:
kStringsis declared in the global scope (not trapped inside a closure or module unless you export/import it properly)strings.jsloads before the replacement function runs (check your script order inindex.html)
4. Optional: Use a mature i18n library
Writing custom replacement logic works for simple cases, but libraries like i18next (with Cordova support) handle edge cases (plurals, dynamic values, language switching) out of the box. It'll save you time as your app's localization needs grow.
内容的提问来源于stack exchange,提问作者Rockers23

