1 // Copyright (c) 2012 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 "chrome/renderer/extensions/i18n_custom_bindings.h"
8 #include "chrome/common/extensions/extension_messages.h"
9 #include "chrome/common/extensions/message_bundle.h"
10 #include "content/public/renderer/render_view.h"
11 #include "grit/renderer_resources.h"
12 #include "v8/include/v8.h"
14 namespace extensions
{
16 I18NCustomBindings::I18NCustomBindings(Dispatcher
* dispatcher
,
17 v8::Handle
<v8::Context
> context
)
18 : ChromeV8Extension(dispatcher
, context
) {
19 RouteFunction("GetL10nMessage",
20 base::Bind(&I18NCustomBindings::GetL10nMessage
, base::Unretained(this)));
23 v8::Handle
<v8::Value
> I18NCustomBindings::GetL10nMessage(
24 const v8::Arguments
& args
) {
25 if (args
.Length() != 3 || !args
[0]->IsString()) {
26 NOTREACHED() << "Bad arguments";
27 return v8::Undefined();
30 std::string extension_id
;
31 if (args
[2]->IsNull() || !args
[2]->IsString()) {
32 return v8::Undefined();
34 extension_id
= *v8::String::Utf8Value(args
[2]->ToString());
35 if (extension_id
.empty())
36 return v8::Undefined();
39 L10nMessagesMap
* l10n_messages
= GetL10nMessagesMap(extension_id
);
41 // Get the current RenderView so that we can send a routed IPC message
42 // from the correct source.
43 content::RenderView
* renderview
= GetRenderView();
45 return v8::Undefined();
47 L10nMessagesMap messages
;
48 // A sync call to load message catalogs for current extension.
49 renderview
->Send(new ExtensionHostMsg_GetMessageBundle(
50 extension_id
, &messages
));
52 // Save messages we got.
53 ExtensionToL10nMessagesMap
& l10n_messages_map
=
54 *GetExtensionToL10nMessagesMap();
55 l10n_messages_map
[extension_id
] = messages
;
57 l10n_messages
= GetL10nMessagesMap(extension_id
);
60 std::string message_name
= *v8::String::AsciiValue(args
[0]);
62 MessageBundle::GetL10nMessage(message_name
, *l10n_messages
);
64 std::vector
<std::string
> substitutions
;
65 if (args
[1]->IsArray()) {
66 // chrome.i18n.getMessage("message_name", ["more", "params"]);
67 v8::Local
<v8::Array
> placeholders
= v8::Local
<v8::Array
>::Cast(args
[1]);
68 uint32_t count
= placeholders
->Length();
70 return v8::Undefined();
71 for (uint32_t i
= 0; i
< count
; ++i
) {
72 substitutions
.push_back(
73 *v8::String::Utf8Value(
74 placeholders
->Get(v8::Integer::New(i
))->ToString()));
76 } else if (args
[1]->IsString()) {
77 // chrome.i18n.getMessage("message_name", "one param");
78 substitutions
.push_back(*v8::String::Utf8Value(args
[1]->ToString()));
81 return v8::String::New(ReplaceStringPlaceholders(
82 message
, substitutions
, NULL
).c_str());
85 } // namespace extension