1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/i18n_custom_bindings.h"
8 #include "content/public/renderer/render_frame.h"
9 #include "content/public/renderer/render_thread.h"
10 #include "extensions/common/extension_messages.h"
11 #include "extensions/common/message_bundle.h"
12 #include "extensions/renderer/script_context.h"
14 namespace extensions
{
16 I18NCustomBindings::I18NCustomBindings(ScriptContext
* context
)
17 : ObjectBackedNativeHandler(context
) {
20 base::Bind(&I18NCustomBindings::GetL10nMessage
, base::Unretained(this)));
21 RouteFunction("GetL10nUILanguage",
22 base::Bind(&I18NCustomBindings::GetL10nUILanguage
,
23 base::Unretained(this)));
26 void I18NCustomBindings::GetL10nMessage(
27 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
28 if (args
.Length() != 3 || !args
[0]->IsString()) {
29 NOTREACHED() << "Bad arguments";
33 std::string extension_id
;
34 if (args
[2]->IsNull() || !args
[2]->IsString()) {
37 extension_id
= *v8::String::Utf8Value(args
[2]);
38 if (extension_id
.empty())
42 L10nMessagesMap
* l10n_messages
= GetL10nMessagesMap(extension_id
);
44 content::RenderFrame
* render_frame
= context()->GetRenderFrame();
48 L10nMessagesMap messages
;
49 // A sync call to load message catalogs for current extension.
51 new ExtensionHostMsg_GetMessageBundle(extension_id
, &messages
));
53 // Save messages we got.
54 ExtensionToL10nMessagesMap
& l10n_messages_map
=
55 *GetExtensionToL10nMessagesMap();
56 l10n_messages_map
[extension_id
] = messages
;
58 l10n_messages
= GetL10nMessagesMap(extension_id
);
61 std::string message_name
= *v8::String::Utf8Value(args
[0]);
63 MessageBundle::GetL10nMessage(message_name
, *l10n_messages
);
65 v8::Isolate
* isolate
= args
.GetIsolate();
66 std::vector
<std::string
> substitutions
;
67 if (args
[1]->IsArray()) {
68 // chrome.i18n.getMessage("message_name", ["more", "params"]);
69 v8::Local
<v8::Array
> placeholders
= v8::Local
<v8::Array
>::Cast(args
[1]);
70 uint32_t count
= placeholders
->Length();
73 for (uint32_t i
= 0; i
< count
; ++i
) {
74 substitutions
.push_back(*v8::String::Utf8Value(placeholders
->Get(
75 v8::Integer::New(isolate
, i
))));
77 } else if (args
[1]->IsString()) {
78 // chrome.i18n.getMessage("message_name", "one param");
79 substitutions
.push_back(*v8::String::Utf8Value(args
[1]));
82 args
.GetReturnValue().Set(v8::String::NewFromUtf8(
84 ReplaceStringPlaceholders(message
, substitutions
, NULL
).c_str()));
87 void I18NCustomBindings::GetL10nUILanguage(
88 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
89 args
.GetReturnValue().Set(v8::String::NewFromUtf8(
90 args
.GetIsolate(), content::RenderThread::Get()->GetLocale().c_str()));
93 } // namespace extensions