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/utils_native_handler.h"
7 #include "base/strings/stringprintf.h"
8 #include "extensions/renderer/script_context.h"
9 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
11 namespace extensions
{
13 UtilsNativeHandler::UtilsNativeHandler(ScriptContext
* context
)
14 : ObjectBackedNativeHandler(context
) {
15 RouteFunction("createClassWrapper",
16 base::Bind(&UtilsNativeHandler::CreateClassWrapper
,
17 base::Unretained(this)));
20 UtilsNativeHandler::~UtilsNativeHandler() {}
22 void UtilsNativeHandler::CreateClassWrapper(
23 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
24 CHECK_EQ(2, args
.Length());
25 CHECK(args
[0]->IsString());
26 std::string name
= *v8::String::Utf8Value(args
[0]);
27 CHECK(args
[1]->IsObject());
28 v8::Local
<v8::Object
> obj
= args
[1].As
<v8::Object
>();
30 v8::HandleScope
handle_scope(GetIsolate());
31 // TODO(fsamuel): Consider moving the source wrapping to ModuleSystem.
32 v8::Handle
<v8::String
> source
= v8::String::NewFromUtf8(
35 "(function($Object, $Function, privates, cls) {"
37 " return function %s() {\n"
38 " var privateObj = $Object.create(cls.prototype);\n"
39 " $Function.apply(cls, privateObj, arguments);\n"
40 " privateObj.wrapper = this;\n"
41 " privates(this).impl = privateObj;\n"
43 name
.c_str()).c_str());
44 v8::Handle
<v8::Value
> func_as_value
= context()->module_system()->RunString(
45 source
, v8::String::NewFromUtf8(GetIsolate(), name
.c_str()));
46 if (func_as_value
.IsEmpty() || func_as_value
->IsUndefined()) {
47 args
.GetReturnValue().SetUndefined();
51 // TODO(fsamuel): Move privates from ModuleSystem to a shared location.
52 v8::Handle
<v8::Object
> natives(context()->module_system()->NewInstance());
53 CHECK(!natives
.IsEmpty()); // this can happen if v8 has issues
54 v8::Handle
<v8::Function
> func
= func_as_value
.As
<v8::Function
>();
55 v8::Handle
<v8::Value
> func_args
[] = {
56 context()->safe_builtins()->GetObjekt(),
57 context()->safe_builtins()->GetFunction(),
58 natives
->Get(v8::String::NewFromUtf8(
59 GetIsolate(), "privates", v8::String::kInternalizedString
)),
61 v8::Local
<v8::Value
> result
;
63 v8::TryCatch try_catch
;
64 try_catch
.SetCaptureMessage(true);
65 result
= context()->CallFunction(func
, arraysize(func_args
), func_args
);
66 if (try_catch
.HasCaught()) {
67 args
.GetReturnValue().SetUndefined();
71 args
.GetReturnValue().Set(result
);
74 } // namespace extensions