Terminal-Based Content Adaptation

Last update:2024-09-03 17:00:36

This example demonstrates how to achieve dynamic content localization using Edge Cloud Apps Function. For instance, if your origin server only provides English content, you can use this function to automatically translate web page content into Chinese, German, and Japanese based on the user’s browser language settings.

Code Example

async function handleRequest(request) {
    const url = new URL(request.url)
    const language = clientLanguage(request)
    const countryStrings = strings[language] || {}
    const response = await fetch(request.url)

    // Use HTMLRewriter for streaming content rewriting
    return new HTMLRewriter()
        .on('[data-i18n-key]', new ElementHandler(countryStrings)) // Find tags with the 'data-i18n-key' attribute
        .transform(response) // Transform the response content
}

// Get the preferred browser language
function clientLanguage(request) {
    // Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
    try {
        const languageHeader = request.headers.get('Accept-Language')
        // Parse the Accept-Language header to get the preferred language
        return languageHeader.split(';')[0].split(',')[0].split('-')[0] 
    } catch (e) {
        // If the language preference cannot be obtained, default to Chinese
        return 'zh' 
    }
}

// Handle element content replacement
class ElementHandler {
    constructor(countryStrings) {
      this.countryStrings = countryStrings
    }
  
    element(element) {
      const i18nKey = element.getAttribute('data-i18n-key')
      if (i18nKey) {
        const translation = this.countryStrings[i18nKey]
        if (translation) {
          element.setInnerContent(translation) // Replace the tag content
        }
      }
    }
  }

// Translation text configuration
const strings = {
    de: {
      title: 'Beispielseite',
      headline: 'Beispielseite',
      subtitle:
        'Dies ist meine Beispielseite. Abhängig davon, wo auf der Welt Sie diese Site besuchen, wird dieser Text in die entsprechende Sprache übersetzt.',
      disclaimer:
        'Haftungsausschluss: Die anfänglichen Übersetzungen stammen von Google Translate, daher sind sie möglicherweise nicht perfekt!',
      tutorial:
        'Das Tutorial für dieses Projekt finden Sie in der CDNetworks ECA-Dokumentation.',
      copyright: 'Design von HTML5 UP.',
    },
    ja: {
      title: 'サンプルサイト',
      headline: 'サンプルサイト',
      subtitle:
        'これは私の例のサイトです。 このサイトにアクセスする世界の場所に応じて、このテキストは対応する言語に翻訳されます。',
      disclaimer:
        '免責事項:最初の翻訳はGoogle翻訳からのものですので、完璧ではないかもしれません!',
      tutorial:
        'CDNetworks ECAのドキュメントでこのプロジェクトのチュートリアルを見つけてください。',
      copyright: 'HTML5 UPによる設計。',
    },
    zh: {
        title: '示例站点',
        headline: '示例站点',
        subtitle:
          '这是我的示例站点。根据您访问本网站的地点,本文将被翻译成相应的语言。',
        disclaimer:
          '免责声明:最初的翻译来自谷歌翻译,所以他们可能不完美!',
        tutorial:
          '在CDNetworks ECA文档中找到这个项目的教程。',
        copyright: '由HTML5 UP设计。',
      },
  }
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
}) 

Note

  • The origin server needs to pre-add the data-i18n-key custom attribute to HTML tags that require translation. For example: <title data-i18n-key="title">...</title>.
  • The Edge Cloud Apps Function uses the HTMLRewriter API to perform stream rewriting of tag content with this attribute. Stream rewriting means that the function can receive web page content, perform translation rewriting, and output the content to the user simultaneously, effectively shortening the overall response time and improving user experience.
Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!