Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google Translate with CKEditor?

I've successfully create javascript code to use Google AJAX Language API to translate plain text. Now I want to tranlate text in an instance of CKEditor, how to accomplish this?

like image 393
remo Avatar asked Oct 17 '25 19:10

remo


1 Answers

First, I wouldn't recommend using the Google AJAX Language API, as it is deprecated as of December. You can use the Microsoft Translator instead, though the API isn't as nice.

Effectively, all you need to do is get the text from the editor, translate it, and stick it back in.

Get the text from the editor:

There's a bunch of different ways to do this, but you can use:

CKEDITOR.instances.editor1.getData()

Where editor1 is the ID of your editor. If you're using jQuery, you can do:

$('#editor1').val()

Translate it, and stick it back in:

This is as simple as calling the google API, and in the callback setting the editor's content:

 google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
            if (response.translation) {
                CKEDITOR.instances.editor1.setData(response.translation);
            }
        });

or using jQuery:

 google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
            if (response.translation) {
                $('#editor1').val(response.translation);
            }
        });

Put it all together into a function

var translate = function(editor, translateFrom, translateTo) {
    var textToTranslate = editor.getData();

    google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
            if (response.translation) {
                editor.setData(response.translation);
            }
        });
};
like image 113
steve_c Avatar answered Oct 20 '25 07:10

steve_c