0

We were using google translate API in our SharePoint Online classic view site. Now we are moving to modern site. I need to implement same in SPFx extension.

Below is code to that is working in classic view:

<div id="google_translate_element"></div>

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Now I am using same in my SPFx extension as below:

public onInit(): Promise<void> {
    Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);    
    SPComponentLoader.loadScript('https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit');

    this.context.placeholderProvider.changedEvent.add(this, this._renderPlaceHolders);
    this.googleTranslateElementInit();
     return Promise.resolve<void>();
  }


  private googleTranslateElementInit() {
    //Getting error here can not find name "google"
    new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
  }
  private _onDispose(): void {
    console.log('[HelloWorldApplicationCustomizer._onDispose] Disposed custom top and bottom placeholders.');
  }
  private _renderPlaceHolders(): void {
    console.log("HelloWorldApplicationCustomizer._renderPlaceHolders()");
    console.log(
        "Available placeholders: ",
        this.context.placeholderProvider.placeholderNames
            .map(name => PlaceholderName[name])
            .join(", ")
    );    

    // Handling the bottom placeholder
    if (!this._bottomPlaceholder) {
        this._bottomPlaceholder = this.context.placeholderProvider.tryCreateContent(
            PlaceholderName.Bottom,
            { onDispose: this._onDispose }
        );

        // The extension should not assume that the expected placeholder is available.
        if (!this._bottomPlaceholder) {
            console.error("The expected placeholder (Bottom) was not found.");
            return;
        }

        if (this.properties) {
            let bottomString: string = this.properties.bottom;
            if (!bottomString) {
                bottomString = "Language Translate";
            }

            if (this._bottomPlaceholder.domElement) {                
                this._bottomPlaceholder.domElement.innerHTML = `                
                ${bottomString}<div id="google_translate_element"></div>
                `;

            }
        }
    }
}

I am facing issue in below code in googleTranslateElementInit() method - can not find name 'google'

new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');

I am not sure how to get this resolved? I have tried this link. But didn't fix my issue.

How to fix this issue? Is there any other API that we can use for translation?

1

Translator API expects global function available (you pass the name of this function via cb= query parameter).

To make it work, you should create this globally available function, i.e. attach it to window object:

public onInit(): Promise<void> {

    window['googleTranslateElementInit'] = () => {
      // tslint:disable-next-line:no-unused-expression
      new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
    };

    return SPComponentLoader.loadScript('https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit', {
      globalExportsName: 'google'
    });
  }  

I haven't found TypeScript definitions for translate api, so I had to add declare var google; on top of the file to make TS compilation happy.

Also, you should provide globalExportsName because SPFx somehow tries to validate it as a module and throws an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.