With the AJAX Language API, you can translate and detect the language of blocks of text within a web page using JavaScript.
The API is new, so there might be some issues and slightly less than perfect documentation. Bear with us as we fill in the holes, and join the AJAX APIs developer forum to give feedback and discuss the API.
This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorials available on the Web.
The easiest way to start learning about this API is to see a simple example. The following example detects the language of the given text and then translates it to English.
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var text = document.getElementById("text").innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en",
function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="text">??????????</div>
<div id="translation"></div>
</body>
</html>
You can view this example here or edit and play around with a similar example in the Code Playground.
To include the AJAX Language API in your page, utilize the Google AJAX API loader. The common loader allows you to
load all of the AJAX APIs that you need, including the language API. You need to include both the Google AJAX APIs script tag and call google.load("language",
"1"):
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("language", "1");
</script>
The first script tag loads the google.load function, which lets you load individual Google APIs. google.load("language", "1") loads Version 1 of the Language API. Currently, the AJAX Language API is in Version 1, but new versions may be available in the future. See the versioning discussion below for more information.
The second argument to google.load is the version of the AJAX Language API you are using. Currently the AJAX Language API is in version 1, but new versions might be available in the future.
If a significant update to the API occurs in the future, the version number will change and a notice will be posted on Google Code and the AJAX APIs discussion group. When that happens, support for both versions is expected for at least a month in order to allow you to migrate your code.
OAThe AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but we may inadavertently break some API clients. Please use the AJAX APIs discussion group to report such issues.
A number of examples are available in the Code Playground that you can edit and play around with to better understand how to use this API.
This example shows a simple translation of a JavaScript string:
google.language.translate("Hello world", "en", "es", function(result) {
if (!result.error) {
var container = document.getElementById("translation");
container.innerHTML = result.translation;
}
});
This example shows language detection of a JavaScript string. The language code is returned:
var text = "¿Dónde está el baño?";
google.language.detect(text, function(result) {
if (!result.error) {
var language = 'unknown';
for (l in google.language.Languages) {
if (google.language.Languages[l] == result.language) {
language = l;
break;
}
}
var container = document.getElementById("detection");
container.innerHTML = text + " is: " + language + "";
}
});
Browsers and operating systems may or may not have the support for rendering particular Unicode fonts. You can detect whether the user using your web page has support for rendering the fonts of a given language in a readable way or not using the font rendering support detection API. Please note that this works correctly for Unicode fonts alone. If your web page renders using non-Unicode fonts, this function will not be useful for you. If font rendering support is not present for a given language, there are several solutions available to fix this - please rsxead this article for more information.
This example shows detection of font rendering support:
var result = google.language.isFontRenderingSupported("hi");
var resultStr = "";
if (result == google.language.FontRenderingStatus.SUPPORTED) {
resultStr = "Rendering for " + lang + " is supported.";
} else if (result == google.language.FontRenderingStatus.UNSUPPORTED) {
resultStr = "Rendering for " + lang + " is not supported.";
} else {
resultStr = "Unsupported language " + lang + " for font detection API.";
}
var resultDiv = document.getElementById("displayResultsDiv");
resultDiv.innerHTML += resultStr;
View example (fontdetection.html)
The following example is similar to the basic translation example but shows how to translate the text without knowing the source language. By specifying an empty string as unknown for the source language, the system detects and translates in one call.
google.language.translate("Hello world", "", "es", function(result) {
if (!result.error) {
var container = document.getElementById("translation");
container.innerHTML = result.translation;
}
});
View example (autotranslate.html)
When your application uses the Google AJAX Language APIs, it is important to communicate the Google brand to your users. The google.language.getBranding() method is designed to help with this. The method accepts an HTML DOM element or the corresponding ID, as well as optional options. The branding is attached to the provided element.
// attach a "powered by Google" branding
<div id='branding'> </div>
...
google.language.getBranding('branding');
The branding can be customized using CSS and comes in a 'vertical' and 'horizontal' base formats. An example showing the various formats and CSS customization is below.
Here are two addional samples that allow some interaction. The first does language detection with a pre-canned text string but allows other text as input. It also displays confidence and reliability factors. Also, you can play around with similar examples in the Code Playground.
The second additional sample does translation. However, it also allows interaction similar to the sample above.
The Google AJAX Language API currently supports the following languages. The technology is constantly improving and the team is working hard to expand this list, so please check back often. You can also visit Google Translate to view an up-to-date list of supported languages.
The Google AJAX Language API currently detects all languages listed above. A subset of those languages are translatable and are listed below. Any two languages from the following list can be translated. To test if a language is translatable, utilize google.language.isTranslatable(languageCode);
For Flash developers, and those developers that have a need to access the AJAX Language API from other Non-JavaScript environments,
the API exposes a simple RESTful interface. In all cases, the method supported is GET, and the response format is a
JSON encoded result with embedded status codes. For google.language.translate,
the POST method is available. Applications that use this interface must abide by
all existing terms of use. An area to pay special attention to relates to correctly identifying
yourself in your requests. Applications MUST always include a valid and accurate http referer header
in their requests. In addition, we ask, but not require, that each request contains a valid API
Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order
to correct any problems.
The easiest way to start learning about this interface is to try it out. Using the command line tool curl or wget execute the
following command:
curl -e http://www.my-ajax-site.com \
'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit'
This command performs a Language Translation(/ajax/services/language/translate), for Hello World (q=hello%20world) from
English to Italian (langpair=en%7Cit). The response
has a Content-Type of text/javascript; charset=utf-8. You can see from the response below that the responseData is
identical to the properties described in the Result Objects
documentation.
{"responseData": {
"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200}
In addition to this response format, the protocol also supports a classic JSON-P style callback which is triggered by
specifying a callback argument. When this argument is present
the JSON object is delivered as an argument to the specified callback.
callbackFunction(
{"responseData": {
"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200})
And finally, the protocol supports callback and context arguments. When these URL arguments
are specified, the response is encoded as a direct JavaScript call with a signature of: callback(context, result, status, details, unused).
Note the slight difference in the following command and response.
curl -e http://www.my-ajax-site.com \ 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit&callback=foo&context=bar'
This command performs a Language Translate and is identical to the previous call, BUT has been altered to pass both callback and context. With these
arguments in place, instead of a JSON object being returned, a JavaScript call is returned in the response and the JSON object is passed using the result parameter.
foo('bar', {"translatedText":"Ciao mondo"}, 200, null)
For complete documentation on this interface, please visit the class reference manual.
If you encounter problems with your code:
With the AJAX Language API for Transliteration, you can enable transliteration on any textfield or textarea on your web page. This helps your users type in any language using an English keyboard.
What is transliteration? Transliteration is the process of phonetically converting a word written in one script into another. Transliteration should not be confused with translation, which involves a change in language while preserving meaning. With transliteration, it is the sound of the words that are converted from one alphabet to the other.
This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorials available on the Web. You should also be familiar with transliteration from a user's point of view. See the Indic transliteration or Arabic transliteration pages for how to use transliteration. Please see this article for more details.
This conceptual documentation is not complete and exhaustive; it is designed to let you quickly start exploring and embedding transliteration in your page.
The easiest way to start learning about this API is to see a simple example. The following example enables transliteration in a textarea with language as Hindi, so that users can type in Hindi using an English keyboard. The user can also switch between typing English and Hindi using 'ctrl+g' as a shortcut. For information on selecting a different language, see the API class reference.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
// Load the Google Transliteration API
google.load("elements", "1", {
packages: "transliteration"
});
function onLoad() {
var options = {
sourceLanguage:
google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage:
[google.elements.transliteration.LanguageCode.HINDI],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textbox with id
// 'transliterateTextarea'.
control.makeTransliteratable(['transliterateTextarea']);
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
Type in Hindi (Press Ctrl+g to toggle between English and Hindi)<br>
<textarea id="transliterateTextarea" style="width:600px;height:200px"></textarea>
</body>
</html>
View example in Code Playground
AJAX Transliteration API is packaged under the "elements" module. To include the Google Transliteration API in your page, first you need the Google AJAX APIs script tag:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
This script tag will load the google.load function, which lets you load the individual Google APIs. For loading Google Transliteration API, calls to
google.load look like this:
<script type="text/javascript">
google.load("elements", "1", {
packages: "transliteration"
});
</script>
This loads Version 1 of the Transliteration API. Currently the Transliteration API is in Version 1, but new versions might be available in the future. See the versioning discussion below for more information.
The second argument to google.load is the version of the AJAX Language API you are using. Currently the Transliteration API is in version 1, but new versions might be available in the future.
If a significant update to the API is done in the future, the version number will be changed and a notice posted on Google Code and the AJAX APIs discussion group. When that happens, support both versions is expected for at least a month in order to allow you to migrate your code.
The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but might inadvertently break some API clients. Please use the AJAX APIs discussion group to report such issues.
This example is very similar to the basic example shown in the Introduction section, but it displays a control for switching between English and Hindi typing modes. It also enables transliteration in two textfields.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
// Load the Google Transliteration API
google.load("elements", "1", {
packages: "transliteration"
});
function onLoad() {
var options = {
sourceLanguage: 'en', // or google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage: ['hi'], // or [google.elements.transliteration.LanguageCode.HINDI],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
control.makeTransliteratable(ids);
// Show the transliteration control which can be used to toggle between
// English and Hindi.
control.showControl('translControl');
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
<center>Type in Hindi (Press Ctrl+g to toggle between English and Hindi)</center>
<div id='translControl'></div>
<br>Title : <input type='textbox' id="transl1"/>
<br>Body<br><textarea id="transl2" style="width:600px;height:200px"></textarea>
</body>
</html>
View example (singlelangtransliteration.html)
This example is very similar to the above example, but displays a control in which the destination language can be chosen. In this example,
the destinationLanguage as ['te', 'ta', 'ml'].
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
// Load the Google Transliteration API
google.load("elements", "1", {
packages: "transliteration"
});
function onLoad() {
var options = {
sourceLanguage: 'en',
destinationLanguage: ['hi','kn','ml','ta','te'],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
control.makeTransliteratable(ids);
// Show the transliteration control which can be used to toggle between
// English and Hindi and also choose other destination language.
control.showControl('translControl');
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
<center>Type in Indian languages (Press Ctrl+g to toggle between English and Hindi)</center>
<div id='translControl'></div>
<br>Title : <input type='textbox' id="transl1"/>
<br>Body<br><textarea id="transl2" style="width:600px;height:200px"></textarea>
</body>
</html>
View example (multilangtransliteration.html)
This is an advanced example which shows how to create your own custom control to control the transliteration. It uses a checkbox for toggling between English and Hindi typing modes and a dropdown to change the destination language. It also registers event handlers for various events that can be raised by the TransliterationControl. See the API class reference for details on the possible events.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
// Load the Google Transliteration API
google.load("elements", "1", {
packages: "transliteration"
});
var transliterationControl;
function onLoad() {
var options = {
sourceLanguage: 'en',
destinationLanguage: ['ar','hi','kn','ml','ta','te'],
transliterationEnabled: true,
shortcutKey: 'ctrl+g'
};
// Create an instance on TransliterationControl with the required
// options.
transliterationControl =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
transliterationControl.makeTransliteratable(ids);
// Add the STATE_CHANGED event handler to correcly maintain the state
// of the checkbox.
transliterationControl.addEventListener(
google.elements.transliteration.TransliterationControl.EventType.STATE_CHANGED,
transliterateStateChangeHandler);
// Add the SERVER_UNREACHABLE event handler to display an error message
// if unable to reach the server.
transliterationControl.addEventListener(
google.elements.transliteration.TransliterationControl.EventType.SERVER_UNREACHABLE,
serverUnreachableHandler);
// Add the SERVER_REACHABLE event handler to remove the error message
// once the server becomes reachable.
transliterationControl.addEventListener(
google.elements.transliteration.TransliterationControl.EventType.SERVER_REACHABLE,
serverReachableHandler);
// Set the checkbox to the correct state.
document.getElementById('checkboxId').checked =
transliterationControl.isTransliterationEnabled();
// Populate the language dropdown
var destinationLanguage =
transliterationControl.getLanguagePair().destinationLanguage;
var languageSelect = document.getElementById('languageDropDown');
var supportedDestinationLanguages =
google.elements.transliteration.getDestinationLanguages(
google.elements.transliteration.LanguageCode.ENGLISH);
for (var lang in supportedDestinationLanguages) {
var opt = document.createElement('option');
opt.text = lang;
opt.value = supportedDestinationLanguages[lang];
if (destinationLanguage == opt.value) {
opt.selected = true;
}
try {
languageSelect.add(opt, null);
} catch (ex) {
languageSelect.add(opt);
}
}
}
// Handler for STATE_CHANGED event which makes sure checkbox status
// reflects the transliteration enabled or disabled status.
function transliterateStateChangeHandler(e) {
document.getElementById('checkboxId').checked = e.transliterationEnabled;
}
// Handler for checkbox's click event. Calls toggleTransliteration to toggle
// the transliteration state.
function checkboxClickHandler() {
transliterationControl.toggleTransliteration();
}
// Handler for dropdown option change event. Calls setLanguagePair to
// set the new language.
function languageChangeHandler() {
var dropdown = document.getElementById('languageDropDown');
transliterationControl.setLanguagePair(
google.elements.transliteration.LanguageCode.ENGLISH,
dropdown.options[dropdown.selectedIndex].value);
}
// SERVER_UNREACHABLE event handler which displays the error message.
function serverUnreachableHandler(e) {
document.getElementById("errorDiv").innerHTML =
"Transliteration Server unreachable";
}
// SERVER_UNREACHABLE event handler which clears the error message.
function serverReachableHandler(e) {
document.getElementById("errorDiv").innerHTML = "";
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
<center>Type in Indian languages (Press Ctrl+g to toggle between English and Hindi)</center>
<div id='translControl'>
<input type="checkbox" id="checkboxId" onclick="javascript:checkboxClickHandler()"></input>
Type in <select id="languageDropDown" onchange="javascript:languageChangeHandler()"></select>
</div>
<br>Title : <input type='textbox' id="transl1"/>
<br>Body<br><textarea id="transl2" style="width:600px;height:200px"></textarea>
<br><div id="errorDiv"></div>
</body>
</html>
View example (customtransliteration.html)
The low-level API for transliteration uses the AJAX Language API (and not the elements package that is used by the rest of the transliteration APIs). To include the AJAX Language API in your page, utilize the Google AJAX API loader and follow the instructions specified here.
This example shows a simple transliteration of a JavaScript string:
google.language.transliterate(["Namaste"], "en", "hi", function(result) {
if (!result.error) {
var container = document.getElementById("transliteration");
if (result.transliterations && result.transliterations.length > 0 &&
result.transliterations[0].transliteratedWords.length > 0) {
container.innerHTML = result.transliterations[0].transliteratedWords[0];
}
}
});
View example (transliterate.html)
The Transliteration API currently supports transliteration from the English version of the Latin alphabet to the scripts of the following languages:
The transliteration control that is displayed using the showControl method can be styled to blend into your web page by extending the CSS classes defined in the default CSS file. The default CSS file is loaded automatically on the google.load() call, and it defines the styles for the control and the transliteration suggestions menu that pops out when you click or edit a transliterated word. If you do not want to load the default CSS, set "nocss" to true.
google.load("elements", "1", {packages: "transliteration", "nocss" : true});
The language selection menu, the button indicating the language selected by the user and the suggestion menu are enclosed in div elements marked with specific CSS classes. You can define overriding CSS rules that are applied to these elements in order to style them according to your page. Please refer to this documented transliteration CSS file for details of the default CSS loaded with the transliteration API package. The following is a listing of CSS classes that are useful for customization:
For example, defining goog-transliterate-indic-suggestion-menu's background-color parameter, allows the displayed suggestion menu's background to be changed from the default #F0A000 value to the new value.
For right-to-left writing systems like Arabic, the API, by default, automatically adjusts the direction of the textarea, according to the direction of the writing system being used and the content of the textarea. (The direction of a textarea is set in HTML and JavaScript with direction, which can have the value 'ltr' or 'rtl'. It affects the cursor and textarea alignment.)
View Arabic transliteration example (arabictransliteration.html)
The Transliteration API is supported by Firefox 1.5 and higher on Windows and Linux, and Internet Explorer 6.0 and higher on Windows (preferably Windows XP). The Transliteration API can be loaded without errors in almost every browser, so you can safely load it before checking for compatibility.
Different applications sometimes require different behaviors for users with incompatible browsers. The Transliteration API provides a global method
google.elements.transliteration.isBrowserCompatible() to check compatibility, but it does not have any automatic behavior when it detects an incompatible browser. Most of the examples in this document do not check for browser compatibility, nor do they display an error message for older browsers. Clearly, real applications should do something more friendly with incompatible browsers, but we have omitted such checks to make the examples more readable.
The Transliteration API handles a lot of UTF-8 text and hence it is necessary to set the content-type of your page to UTF-8 by adding this meta tag <meta
http-equiv="Content-Type" content="text/html; charset=utf-8"/>. Without this meta tag, the Transliteration API will not work properly in your web page.
If you encounter problems with your code:
With the AJAX Language API for Virtual Keyboard, you can enable the onscreen keyboard on any textfield or textarea in your webpage. This will help your website users to type in any language using their familiar keyboard layouts.
What is a virtual keyboard? A virtual keyboard is used to translate the input from one keyboard layout to another.
This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorials available on the Web.
This conceptual documentation is not complete and exhaustive; it is designed to let you quickly start exploring and embedding virtual keyboard in your page.
The easiest way to start learning about this API is to see a simple example. The following example enables Virtual Keyboard in a textarea with Russian keyboard layout, so that users can type in Russian by using an English physical keyboard or by using mouse. The user can also hide/show the virtual keyboard by clicking the +/- buttons on the onscreen keyboard. For information on selecting a different layout, see the API class reference
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Onscreen Keyboard API
google.load("elements", "1", {
packages: "keyboard"
});
function onLoad() {
var kbd = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
Type in Russian<br/>
<textarea id="t1" style="width: 600px; height: 200px;"></textarea>
</body>
</html>
You can play around with a similar example in the Code Playground.
AJAX Virtual Keyboard API is packaged under the "elements" module. To include the Google Virtual Keyboard API in your page, first you need the Google AJAX APIs script tag:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
This script tag will load the google.load function, which lets you load the individual Google APIs. For loading Google Virtual Keyboard API, calls to google.load look like this:
<script type="text/javascript">
google.load("elements", "1", {
packages: "keyboard"
});
</script>
This loads Version 1 of the Virtual Keyboard API. Currently the Virtual Keyboard API is in Version 1, but new versions might be available in the future. See the versioning discussion below for more information.
The second argument to google.load is the version of the AJAX Language API you are using. Currently, the Virtual Keyboard API is in version 1, but new versions might be available in the future.
If a significant update to the API is done in the future, the version number will be updated and a notice posted on Google Code and the AJAX APIs discussion group. When that happens, support for both versions is expected for at least a month in order to allow you to migrate your code.
The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but may inadvertently break some API clients. Use the AJAX APIs discussion group to report such issues.
The following example shows how to hide or show the keyboard in your code. When a virtual keyboard is hidden, the user types using the physical keyboard layout.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Onscreen Keyboard API
google.load("elements", "1", {
packages: "keyboard"
});
var kbd; // A Keyboard object.
function onLoad() {
// Create an instance on Keyboard.
kbd = new google.elements.keyboard.Keyboard([
google.elements.keyboard.LayoutCode.POLISH],
['t1']);
}
// If the keyboard is visible, hide it.
// If the keyboard is invisible, show it.
function toggleVisible() {
var button = document.getElementById("btVisible");
if (kbd.isVisible()) {
kbd.setVisible(false);
document.getElementById('btVisible').value = "Show";
} else {
kbd.setVisible(true);
document.getElementById('btVisible').value = "Hide";
}
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
This is a demo for setVisible/isVisible.<br/>
<input type="button" onclick="toggleVisible()" id="btVisible" value="Hide"></input><br/>
<textarea type="text" id="t1" style="width: 600px; height: 200px;"></textarea>
</body>
</html>
You can play around with a similar example in the Code Playground.
The following example is similar to the basic example shown in the Introduction section, but it shows how to switch layout for a virtual keyboard in your code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Onscreen Keyboard API
google.load("elements", "1", {
packages: "keyboard"
});
var kbd; // A Keyboard object.
function onLoad() {
// Create an instance on Keyboard.
kbd = new google.elements.keyboard.Keyboard([
google.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
This is a demo for setLayout/getLayout.<br/>
<script type="text/javascript">
</script>
<input type="button" onclick="kbd.setLayout('ru')" value="Russian" /><br/>
<input type="button" onclick="kbd.setLayout('hi')" value="Hindi" /><br/>
<input type="button" onclick="kbd.setLayout('th')" value="Thai" /><br/>
<input type="button" onclick="kbd.setLayout('ar')" value="Arabic" /><br/>
<input type="button" onclick="kbd.setLayout('pl')" value="Polish" /><br/>
<input type="button" onclick="kbd.setLayout('fa')" value="Persian" /><br/>
<input type="text" id="t1" style="width: 600px"></input>
</body>
</html>
You can play around with a similar example in the Code Playground.
The following example enumerates the supported keyboard layouts, and draws a layout menu on the page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Onscreen Keyboard API
google.load("elements", "1", {
packages: "keyboard"
});
var kbd; // A Keyboard object.
// Draw a list of keyboard layouts in their native languages.
// User can click any of them to switch to that keyboard layout.
function drawMenu() {
html = ["<ul>"];
for (var i in google.elements.keyboard.LayoutCode) {
var code = google.elements.keyboard.LayoutCode[i];
var name = google.elements.keyboard.getLayoutName(code);
html.push("<li><a href='#' onclick='kbd.setLayout(\"", code, "\")'>",
name, "</a></li>");
}
html.push("</ul>");
document.getElementById("menu").innerHTML = html.join('');
}
function onLoad() {
kbd = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);
drawMenu();
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
This is a demo for LayoutCode and getLayoutName.<br/>
<div id="menu"></div><br/>
<textarea id="t1" style="width: 600px; height: 200px;"></textarea>
</body>
</html>
The following example is similar to the basic example shown in the Introduction section. But it has two Keyboard objects to control two groups of text fields each. There are four text fields on the page. Two of them use a Thai virtual keyboard and the other two use an Arabic virtual keyboard.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Onscreen Keyboard API
google.load("elements", "1", {
packages: "keyboard"
});
function onLoad() {
var kbd1 = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.THAI],
['th1', 'th2']);
var kbd2 = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.ARABIC],
['ar1', 'ar2']);
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
Type in Thai and Arabic<br/>
<textarea id="th1" style="width: 300px; height: 80px;"></textarea>
<textarea id="ar1" style="width: 300px; height: 80px;"></textarea>
<textarea id="th2" style="width: 300px; height: 80px;"></textarea>
<textarea id="ar2" style="width: 300px; height: 80px;"></textarea>
</body>
</html>
You can play around with a similar example in the Code Playground.
The Virtual Keyboard API currently supports the following keyboard layouts:
We plan to gradually release more keyboard layouts in the near future. Stay tuned and come back to check this document for up-to-date information.
The Virtual Keyboard API is supported by Firefox 3 and higher on Windows and Linux, and Internet Explorer 6.0 and higher on Windows (preferably Windows XP). The Virtual Keyboard API can be loaded without errors in almost every browser, so you can safely load it before checking for compatibility.
If you encounter problems with your code: