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/messaging_bindings.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/lazy_instance.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/values.h"
16 #include "chrome/common/extensions/extension_messages.h"
17 #include "chrome/common/extensions/message_bundle.h"
18 #include "chrome/common/url_constants.h"
19 #include "chrome/renderer/extensions/chrome_v8_context.h"
20 #include "chrome/renderer/extensions/chrome_v8_context_set.h"
21 #include "chrome/renderer/extensions/chrome_v8_extension.h"
22 #include "chrome/renderer/extensions/dispatcher.h"
23 #include "chrome/renderer/extensions/event_bindings.h"
24 #include "chrome/renderer/extensions/scoped_persistent.h"
25 #include "content/public/renderer/render_thread.h"
26 #include "content/public/renderer/render_view.h"
27 #include "content/public/renderer/v8_value_converter.h"
28 #include "grit/renderer_resources.h"
29 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
30 #include "v8/include/v8.h"
32 // Message passing API example (in a content script):
34 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
35 // var port = runtime.connect();
36 // port.postMessage('Can you hear me now?');
37 // port.onmessage.addListener(function(msg, port) {
38 // alert('response=' + msg);
39 // port.postMessage('I got your reponse');
42 using content::RenderThread
;
43 using content::V8ValueConverter
;
47 struct ExtensionData
{
49 int ref_count
; // how many contexts have a handle to this port
50 PortData() : ref_count(0) {}
52 std::map
<int, PortData
> ports
; // port ID -> data
55 static base::LazyInstance
<ExtensionData
> g_extension_data
=
56 LAZY_INSTANCE_INITIALIZER
;
58 static bool HasPortData(int port_id
) {
59 return g_extension_data
.Get().ports
.find(port_id
) !=
60 g_extension_data
.Get().ports
.end();
63 static ExtensionData::PortData
& GetPortData(int port_id
) {
64 return g_extension_data
.Get().ports
[port_id
];
67 static void ClearPortData(int port_id
) {
68 g_extension_data
.Get().ports
.erase(port_id
);
71 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
72 const char kReceivingEndDoesntExistError
[] =
73 "Could not establish connection. Receiving end does not exist.";
75 class ExtensionImpl
: public extensions::ChromeV8Extension
{
77 explicit ExtensionImpl(extensions::Dispatcher
* dispatcher
,
78 extensions::ChromeV8Context
* context
)
79 : extensions::ChromeV8Extension(dispatcher
, context
) {
80 RouteFunction("CloseChannel",
81 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
82 RouteFunction("PortAddRef",
83 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
84 RouteFunction("PortRelease",
85 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
86 RouteFunction("PostMessage",
87 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
88 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
89 RouteFunction("BindToGC",
90 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
93 virtual ~ExtensionImpl() {}
95 // Sends a message along the given channel.
96 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
97 content::RenderView
* renderview
= GetRenderView();
101 // Arguments are (int32 port_id, string message).
102 CHECK(args
.Length() == 2 &&
103 args
[0]->IsInt32() &&
104 args
[1]->IsString());
106 int port_id
= args
[0]->Int32Value();
107 if (!HasPortData(port_id
)) {
108 v8::ThrowException(v8::Exception::Error(
109 v8::String::New(kPortClosedError
)));
113 renderview
->Send(new ExtensionHostMsg_PostMessage(
114 renderview
->GetRoutingID(), port_id
, *v8::String::AsciiValue(args
[1])));
117 // Forcefully disconnects a port.
118 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
119 // Arguments are (int32 port_id, boolean notify_browser).
120 CHECK_EQ(2, args
.Length());
121 CHECK(args
[0]->IsInt32());
122 CHECK(args
[1]->IsBoolean());
124 int port_id
= args
[0]->Int32Value();
125 if (!HasPortData(port_id
))
128 // Send via the RenderThread because the RenderView might be closing.
129 bool notify_browser
= args
[1]->BooleanValue();
130 if (notify_browser
) {
131 content::RenderThread::Get()->Send(
132 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
135 ClearPortData(port_id
);
138 // A new port has been created for a context. This occurs both when script
139 // opens a connection, and when a connection is opened to this script.
140 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
141 // Arguments are (int32 port_id).
142 CHECK_EQ(1, args
.Length());
143 CHECK(args
[0]->IsInt32());
145 int port_id
= args
[0]->Int32Value();
146 ++GetPortData(port_id
).ref_count
;
149 // The frame a port lived in has been destroyed. When there are no more
150 // frames with a reference to a given port, we will disconnect it and notify
151 // the other end of the channel.
152 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
153 // Arguments are (int32 port_id).
154 CHECK_EQ(1, args
.Length());
155 CHECK(args
[0]->IsInt32());
157 int port_id
= args
[0]->Int32Value();
158 if (HasPortData(port_id
) && --GetPortData(port_id
).ref_count
== 0) {
159 // Send via the RenderThread because the RenderView might be closing.
160 content::RenderThread::Get()->Send(
161 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
162 ClearPortData(port_id
);
166 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
167 // not be executed re-entrantly to avoid running JS in an unexpected state.
170 static void Bind(v8::Handle
<v8::Object
> object
,
171 v8::Handle
<v8::Function
> callback
,
172 v8::Isolate
* isolate
) {
173 GCCallback
* cb
= new GCCallback(object
, callback
, isolate
);
174 cb
->object_
.MakeWeak(cb
, NearDeathCallback
);
178 static void NearDeathCallback(v8::Isolate
* isolate
,
179 v8::Persistent
<v8::Object
>* object
,
181 // v8 says we need to explicitly reset weak handles from their callbacks.
182 // It's not implicit as one might expect.
183 self
->object_
.reset();
184 base::MessageLoop::current()->PostTask(FROM_HERE
,
185 base::Bind(&GCCallback::RunCallback
, base::Owned(self
)));
188 GCCallback(v8::Handle
<v8::Object
> object
,
189 v8::Handle
<v8::Function
> callback
,
190 v8::Isolate
* isolate
)
191 : object_(object
), callback_(callback
), isolate_(isolate
) {}
194 v8::HandleScope
handle_scope(isolate_
);
195 v8::Handle
<v8::Function
> callback
= callback_
.NewHandle(isolate_
);
196 v8::Handle
<v8::Context
> context
= callback
->CreationContext();
197 if (context
.IsEmpty())
199 v8::Context::Scope
context_scope(context
);
200 WebKit::WebScopedMicrotaskSuppression suppression
;
201 callback
->Call(context
->Global(), 0, NULL
);
204 extensions::ScopedPersistent
<v8::Object
> object_
;
205 extensions::ScopedPersistent
<v8::Function
> callback_
;
206 v8::Isolate
* isolate_
;
208 DISALLOW_COPY_AND_ASSIGN(GCCallback
);
211 // void BindToGC(object, callback)
213 // Binds |callback| to be invoked *sometime after* |object| is garbage
214 // collected. We don't call the method re-entrantly so as to avoid executing
215 // JS in some bizarro undefined mid-GC state.
216 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
217 CHECK(args
.Length() == 2 && args
[0]->IsObject() && args
[1]->IsFunction());
218 GCCallback::Bind(args
[0].As
<v8::Object
>(),
219 args
[1].As
<v8::Function
>(),
226 namespace extensions
{
228 ChromeV8Extension
* MessagingBindings::Get(
229 Dispatcher
* dispatcher
,
230 ChromeV8Context
* context
) {
231 return new ExtensionImpl(dispatcher
, context
);
235 void MessagingBindings::DispatchOnConnect(
236 const ChromeV8ContextSet::ContextSet
& contexts
,
238 const std::string
& channel_name
,
239 const base::DictionaryValue
& source_tab
,
240 const std::string
& source_extension_id
,
241 const std::string
& target_extension_id
,
242 const GURL
& source_url
,
243 content::RenderView
* restrict_to_render_view
) {
244 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
246 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
248 bool port_created
= false;
249 std::string source_url_spec
= source_url
.spec();
251 // TODO(kalman): pass in the full ChromeV8ContextSet; call ForEach.
252 for (ChromeV8ContextSet::ContextSet::const_iterator it
= contexts
.begin();
253 it
!= contexts
.end(); ++it
) {
254 if (restrict_to_render_view
&&
255 restrict_to_render_view
!= (*it
)->GetRenderView()) {
259 // TODO(kalman): remove when ContextSet::ForEach is available.
260 if ((*it
)->v8_context().IsEmpty())
263 v8::Handle
<v8::Value
> tab
= v8::Null();
264 if (!source_tab
.empty())
265 tab
= converter
->ToV8Value(&source_tab
, (*it
)->v8_context());
267 v8::Handle
<v8::Value
> arguments
[] = {
268 v8::Integer::New(target_port_id
),
269 v8::String::New(channel_name
.c_str(), channel_name
.size()),
271 v8::String::New(source_extension_id
.c_str(), source_extension_id
.size()),
272 v8::String::New(target_extension_id
.c_str(), target_extension_id
.size()),
273 v8::String::New(source_url_spec
.c_str(), source_url_spec
.size())
276 v8::Handle
<v8::Value
> retval
= (*it
)->module_system()->CallModuleMethod(
279 arraysize(arguments
), arguments
);
281 if (retval
.IsEmpty()) {
282 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
286 CHECK(retval
->IsBoolean());
287 port_created
|= retval
->BooleanValue();
290 // If we didn't create a port, notify the other end of the channel (treat it
293 content::RenderThread::Get()->Send(
294 new ExtensionHostMsg_CloseChannel(
295 target_port_id
, kReceivingEndDoesntExistError
));
300 void MessagingBindings::DeliverMessage(
301 const ChromeV8ContextSet::ContextSet
& contexts
,
303 const std::string
& message
,
304 content::RenderView
* restrict_to_render_view
) {
305 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
307 // TODO(kalman): pass in the full ChromeV8ContextSet; call ForEach.
308 for (ChromeV8ContextSet::ContextSet::const_iterator it
= contexts
.begin();
309 it
!= contexts
.end(); ++it
) {
310 if (restrict_to_render_view
&&
311 restrict_to_render_view
!= (*it
)->GetRenderView()) {
315 // TODO(kalman): remove when ContextSet::ForEach is available.
316 if ((*it
)->v8_context().IsEmpty())
319 // Check to see whether the context has this port before bothering to create
321 v8::Handle
<v8::Value
> port_id_handle
= v8::Integer::New(target_port_id
);
322 v8::Handle
<v8::Value
> has_port
= (*it
)->module_system()->CallModuleMethod(
327 CHECK(!has_port
.IsEmpty());
328 if (!has_port
->BooleanValue())
331 std::vector
<v8::Handle
<v8::Value
> > arguments
;
332 arguments
.push_back(v8::String::New(message
.c_str(), message
.size()));
333 arguments
.push_back(port_id_handle
);
334 (*it
)->module_system()->CallModuleMethod("messaging",
341 void MessagingBindings::DispatchOnDisconnect(
342 const ChromeV8ContextSet::ContextSet
& contexts
,
344 const std::string
& error_message
,
345 content::RenderView
* restrict_to_render_view
) {
346 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
348 // TODO(kalman): pass in the full ChromeV8ContextSet; call ForEach.
349 for (ChromeV8ContextSet::ContextSet::const_iterator it
= contexts
.begin();
350 it
!= contexts
.end(); ++it
) {
351 if (restrict_to_render_view
&&
352 restrict_to_render_view
!= (*it
)->GetRenderView()) {
356 // TODO(kalman): remove when ContextSet::ForEach is available.
357 if ((*it
)->v8_context().IsEmpty())
360 std::vector
<v8::Handle
<v8::Value
> > arguments
;
361 arguments
.push_back(v8::Integer::New(port_id
));
362 if (!error_message
.empty()) {
363 arguments
.push_back(v8::String::New(error_message
.c_str()));
365 arguments
.push_back(v8::Null());
367 (*it
)->module_system()->CallModuleMethod("messaging",
368 "dispatchOnDisconnect",
373 } // namespace extensions