1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/extensions/miscellaneous_bindings.h"
#include <map>
#include <string>
#include "base/basictypes.h"
#include "base/lazy_instance.h"
#include "chrome/common/extensions/extension_message_bundle.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/chrome_v8_context.h"
#include "chrome/renderer/extensions/chrome_v8_context_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_dispatcher.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "v8/include/v8.h"
// Message passing API example (in a content script):
// var extension =
// new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
// var port = extension.connect();
// port.postMessage('Can you hear me now?');
// port.onmessage.addListener(function(msg, port) {
// alert('response=' + msg);
// port.postMessage('I got your reponse');
// });
using content::RenderThread;
namespace {
struct ExtensionData {
struct PortData {
int ref_count; // how many contexts have a handle to this port
bool disconnected; // true if this port was forcefully disconnected
PortData() : ref_count(0), disconnected(false) {}
};
std::map<int, PortData> ports; // port ID -> data
};
static base::LazyInstance<ExtensionData> g_extension_data =
LAZY_INSTANCE_INITIALIZER;
static bool HasPortData(int port_id) {
return g_extension_data.Get().ports.find(port_id) !=
g_extension_data.Get().ports.end();
}
static ExtensionData::PortData& GetPortData(int port_id) {
return g_extension_data.Get().ports[port_id];
}
static void ClearPortData(int port_id) {
g_extension_data.Get().ports.erase(port_id);
}
const char kPortClosedError[] = "Attempting to use a disconnected port object";
class ExtensionImpl : public ChromeV8Extension {
public:
explicit ExtensionImpl(ExtensionDispatcher* dispatcher)
: ChromeV8Extension(dispatcher) {
RouteStaticFunction("CloseChannel", &CloseChannel);
RouteStaticFunction("PortAddRef", &PortAddRef);
RouteStaticFunction("PortRelease", &PortRelease);
RouteStaticFunction("PostMessage", &PostMessage);
}
~ExtensionImpl() {}
// Sends a message along the given channel.
static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args) {
content::RenderView* renderview = GetCurrentRenderView();
if (!renderview)
return v8::Undefined();
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsString()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New(kPortClosedError)));
}
std::string message = *v8::String::Utf8Value(args[1]->ToString());
renderview->Send(new ExtensionHostMsg_PostMessage(
renderview->GetRoutingID(), port_id, message));
}
return v8::Undefined();
}
// Forcefully disconnects a port.
static v8::Handle<v8::Value> CloseChannel(const v8::Arguments& args) {
if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsBoolean()) {
int port_id = args[0]->Int32Value();
if (!HasPortData(port_id)) {
return v8::Undefined();
}
// Send via the RenderThread because the RenderView might be closing.
bool notify_browser = args[1]->BooleanValue();
if (notify_browser)
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id));
ClearPortData(port_id);
}
return v8::Undefined();
}
// A new port has been created for a context. This occurs both when script
// opens a connection, and when a connection is opened to this script.
static v8::Handle<v8::Value> PortAddRef(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
++GetPortData(port_id).ref_count;
}
return v8::Undefined();
}
// The frame a port lived in has been destroyed. When there are no more
// frames with a reference to a given port, we will disconnect it and notify
// the other end of the channel.
static v8::Handle<v8::Value> PortRelease(const v8::Arguments& args) {
if (args.Length() >= 1 && args[0]->IsInt32()) {
int port_id = args[0]->Int32Value();
if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
// Send via the RenderThread because the RenderView might be closing.
content::RenderThread::Get()->Send(
new ExtensionHostMsg_CloseChannel(port_id));
ClearPortData(port_id);
}
}
return v8::Undefined();
}
};
} // namespace
namespace extensions {
ChromeV8Extension* MiscellaneousBindings::Get(ExtensionDispatcher* dispatcher) {
return new ExtensionImpl(dispatcher);
}
void MiscellaneousBindings::DeliverMessage(
const ChromeV8ContextSet::ContextSet& contexts,
int target_port_id,
const std::string& message,
content::RenderView* restrict_to_render_view) {
v8::HandleScope handle_scope;
for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
it != contexts.end(); ++it) {
if (restrict_to_render_view &&
restrict_to_render_view != (*it)->GetRenderView()) {
continue;
}
// Check to see whether the context has this port before bothering to create
// the message.
v8::Handle<v8::Value> port_id_handle = v8::Integer::New(target_port_id);
v8::Handle<v8::Value> has_port;
if (!(*it)->CallChromeHiddenMethod("Port.hasPort", 1, &port_id_handle,
&has_port)) {
continue;
}
CHECK(!has_port.IsEmpty());
if (!has_port->BooleanValue())
continue;
std::vector<v8::Handle<v8::Value> > arguments;
arguments.push_back(v8::String::New(message.c_str(), message.size()));
arguments.push_back(port_id_handle);
CHECK((*it)->CallChromeHiddenMethod("Port.dispatchOnMessage",
arguments.size(),
&arguments[0],
NULL));
}
}
} // namespace extension
|