ui: Remove some unnecessary functions from the API.
[chromium-blink-merge.git] / extensions / renderer / script_injection.cc
blob426c556f1cd2413a93b6122f72ca974272c9ce21
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/script_injection.h"
7 #include <map>
9 #include "base/lazy_instance.h"
10 #include "base/metrics/histogram.h"
11 #include "base/timer/elapsed_timer.h"
12 #include "base/values.h"
13 #include "content/public/renderer/render_view.h"
14 #include "content/public/renderer/v8_value_converter.h"
15 #include "extensions/common/extension.h"
16 #include "extensions/common/extension_messages.h"
17 #include "extensions/common/feature_switch.h"
18 #include "extensions/common/manifest_handlers/csp_info.h"
19 #include "extensions/renderer/dom_activity_logger.h"
20 #include "extensions/renderer/extension_groups.h"
21 #include "extensions/renderer/extensions_renderer_client.h"
22 #include "third_party/WebKit/public/platform/WebString.h"
23 #include "third_party/WebKit/public/web/WebDocument.h"
24 #include "third_party/WebKit/public/web/WebFrame.h"
25 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
26 #include "third_party/WebKit/public/web/WebScriptSource.h"
27 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
28 #include "url/gurl.h"
30 namespace extensions {
32 namespace {
34 typedef std::map<std::string, int> IsolatedWorldMap;
35 base::LazyInstance<IsolatedWorldMap> g_isolated_worlds =
36 LAZY_INSTANCE_INITIALIZER;
38 const int64 kInvalidRequestId = -1;
40 // The id of the next pending injection.
41 int64 g_next_pending_id = 0;
43 bool ShouldNotifyBrowserOfInjections() {
44 return !FeatureSwitch::scripts_require_action()->IsEnabled();
47 // Append all the child frames of |parent_frame| to |frames_vector|.
48 void AppendAllChildFrames(blink::WebFrame* parent_frame,
49 std::vector<blink::WebFrame*>* frames_vector) {
50 DCHECK(parent_frame);
51 for (blink::WebFrame* child_frame = parent_frame->firstChild(); child_frame;
52 child_frame = child_frame->nextSibling()) {
53 frames_vector->push_back(child_frame);
54 AppendAllChildFrames(child_frame, frames_vector);
58 // Gets the isolated world ID to use for the given |extension| in the given
59 // |frame|. If no isolated world has been created for that extension,
60 // one will be created and initialized.
61 int GetIsolatedWorldIdForExtension(const Extension* extension,
62 blink::WebFrame* frame) {
63 static int g_next_isolated_world_id =
64 ExtensionsRendererClient::Get()->GetLowestIsolatedWorldId();
66 IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
68 int id = 0;
69 IsolatedWorldMap::iterator iter = isolated_worlds.find(extension->id());
70 if (iter != isolated_worlds.end()) {
71 id = iter->second;
72 } else {
73 id = g_next_isolated_world_id++;
74 // This map will tend to pile up over time, but realistically, you're never
75 // going to have enough extensions for it to matter.
76 isolated_worlds[extension->id()] = id;
79 // We need to set the isolated world origin and CSP even if it's not a new
80 // world since these are stored per frame, and we might not have used this
81 // isolated world in this frame before.
82 frame->setIsolatedWorldSecurityOrigin(
83 id, blink::WebSecurityOrigin::create(extension->url()));
84 frame->setIsolatedWorldContentSecurityPolicy(
85 id,
86 blink::WebString::fromUTF8(CSPInfo::GetContentSecurityPolicy(extension)));
88 return id;
91 } // namespace
93 // static
94 std::string ScriptInjection::GetExtensionIdForIsolatedWorld(
95 int isolated_world_id) {
96 IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
98 for (IsolatedWorldMap::iterator iter = isolated_worlds.begin();
99 iter != isolated_worlds.end();
100 ++iter) {
101 if (iter->second == isolated_world_id)
102 return iter->first;
104 return std::string();
107 // static
108 void ScriptInjection::RemoveIsolatedWorld(const std::string& extension_id) {
109 g_isolated_worlds.Get().erase(extension_id);
112 ScriptInjection::ScriptInjection(
113 scoped_ptr<ScriptInjector> injector,
114 blink::WebFrame* web_frame,
115 const std::string& extension_id,
116 UserScript::RunLocation run_location,
117 int tab_id)
118 : injector_(injector.Pass()),
119 web_frame_(web_frame),
120 extension_id_(extension_id),
121 run_location_(run_location),
122 tab_id_(tab_id),
123 request_id_(kInvalidRequestId),
124 complete_(false) {
127 ScriptInjection::~ScriptInjection() {
128 if (!complete_)
129 injector_->OnWillNotInject(ScriptInjector::WONT_INJECT);
132 bool ScriptInjection::TryToInject(UserScript::RunLocation current_location,
133 const Extension* extension,
134 ScriptsRunInfo* scripts_run_info) {
135 if (current_location < run_location_)
136 return false; // Wait for the right location.
138 if (request_id_ != kInvalidRequestId)
139 return false; // We're waiting for permission right now, try again later.
141 if (!extension) {
142 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
143 return true; // We're done.
146 switch (injector_->CanExecuteOnFrame(
147 extension, web_frame_, tab_id_, web_frame_->top()->document().url())) {
148 case PermissionsData::ACCESS_DENIED:
149 NotifyWillNotInject(ScriptInjector::NOT_ALLOWED);
150 return true; // We're done.
151 case PermissionsData::ACCESS_WITHHELD:
152 RequestPermission();
153 return false; // Wait around for permission.
154 case PermissionsData::ACCESS_ALLOWED:
155 Inject(extension, scripts_run_info);
156 return true; // We're done!
159 // Some compilers don't realize that we always return from the switch() above.
160 // Make them happy.
161 return false;
164 bool ScriptInjection::OnPermissionGranted(const Extension* extension,
165 ScriptsRunInfo* scripts_run_info) {
166 if (!extension) {
167 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
168 return false;
171 Inject(extension, scripts_run_info);
172 return true;
175 void ScriptInjection::RequestPermission() {
176 content::RenderView* render_view =
177 content::RenderView::FromWebView(web_frame()->top()->view());
179 // If we are just notifying the browser of the injection, then send an
180 // invalid request (which is treated like a notification).
181 request_id_ = ShouldNotifyBrowserOfInjections() ? kInvalidRequestId
182 : g_next_pending_id++;
183 render_view->Send(new ExtensionHostMsg_RequestScriptInjectionPermission(
184 render_view->GetRoutingID(),
185 extension_id_,
186 injector_->script_type(),
187 request_id_));
190 void ScriptInjection::NotifyWillNotInject(
191 ScriptInjector::InjectFailureReason reason) {
192 complete_ = true;
193 injector_->OnWillNotInject(reason);
196 void ScriptInjection::Inject(const Extension* extension,
197 ScriptsRunInfo* scripts_run_info) {
198 DCHECK(extension);
199 DCHECK(scripts_run_info);
200 DCHECK(!complete_);
202 if (ShouldNotifyBrowserOfInjections())
203 RequestPermission();
205 std::vector<blink::WebFrame*> frame_vector;
206 frame_vector.push_back(web_frame_);
207 if (injector_->ShouldExecuteInChildFrames())
208 AppendAllChildFrames(web_frame_, &frame_vector);
210 scoped_ptr<blink::WebScopedUserGesture> gesture;
211 if (injector_->IsUserGesture())
212 gesture.reset(new blink::WebScopedUserGesture());
214 bool inject_js = injector_->ShouldInjectJs(run_location_);
215 bool inject_css = injector_->ShouldInjectCss(run_location_);
216 DCHECK(inject_js || inject_css);
218 scoped_ptr<base::ListValue> execution_results(new base::ListValue());
219 GURL top_url = web_frame_->top()->document().url();
220 for (std::vector<blink::WebFrame*>::iterator iter = frame_vector.begin();
221 iter != frame_vector.end();
222 ++iter) {
223 blink::WebFrame* frame = *iter;
225 // We recheck access here in the renderer for extra safety against races
226 // with navigation, but different frames can have different URLs, and the
227 // extension might only have access to a subset of them.
228 // For child frames, we just skip ones the extension doesn't have access
229 // to and carry on.
230 // Note: we don't consider ACCESS_WITHHELD because there is nowhere to
231 // surface a request for a child frame.
232 // TODO(rdevlin.cronin): We should ask for permission somehow.
233 if (injector_->CanExecuteOnFrame(extension, frame, tab_id_, top_url) ==
234 PermissionsData::ACCESS_DENIED) {
235 DCHECK(frame->parent());
236 continue;
238 if (inject_js)
239 InjectJs(extension, frame, execution_results.get());
240 if (inject_css)
241 InjectCss(frame);
244 complete_ = true;
245 injector_->OnInjectionComplete(execution_results.Pass(),
246 scripts_run_info,
247 run_location_);
250 void ScriptInjection::InjectJs(const Extension* extension,
251 blink::WebFrame* frame,
252 base::ListValue* execution_results) {
253 std::vector<blink::WebScriptSource> sources =
254 injector_->GetJsSources(run_location_);
255 bool in_main_world = injector_->ShouldExecuteInMainWorld();
256 int world_id = in_main_world
257 ? DOMActivityLogger::kMainWorldId
258 : GetIsolatedWorldIdForExtension(extension, frame);
259 bool expects_results = injector_->ExpectsResults();
261 base::ElapsedTimer exec_timer;
262 DOMActivityLogger::AttachToWorld(world_id, extension->id());
263 v8::HandleScope scope(v8::Isolate::GetCurrent());
264 v8::Local<v8::Value> script_value;
265 if (in_main_world) {
266 // We only inject in the main world for javascript: urls.
267 DCHECK_EQ(1u, sources.size());
269 const blink::WebScriptSource& source = sources.front();
270 if (expects_results)
271 script_value = frame->executeScriptAndReturnValue(source);
272 else
273 frame->executeScript(source);
274 } else { // in isolated world
275 scoped_ptr<blink::WebVector<v8::Local<v8::Value> > > results;
276 if (expects_results)
277 results.reset(new blink::WebVector<v8::Local<v8::Value> >());
278 frame->executeScriptInIsolatedWorld(world_id,
279 &sources.front(),
280 sources.size(),
281 EXTENSION_GROUP_CONTENT_SCRIPTS,
282 results.get());
283 if (expects_results && !results->isEmpty())
284 script_value = (*results)[0];
287 UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
289 if (expects_results) {
290 // Right now, we only support returning single results (per frame).
291 scoped_ptr<content::V8ValueConverter> v8_converter(
292 content::V8ValueConverter::create());
293 // It's safe to always use the main world context when converting
294 // here. V8ValueConverterImpl shouldn't actually care about the
295 // context scope, and it switches to v8::Object's creation context
296 // when encountered.
297 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
298 scoped_ptr<base::Value> result(
299 v8_converter->FromV8Value(script_value, context));
300 // Always append an execution result (i.e. no result == null result)
301 // so that |execution_results| lines up with the frames.
302 execution_results->Append(result.get() ? result.release()
303 : base::Value::CreateNullValue());
307 void ScriptInjection::InjectCss(blink::WebFrame* frame) {
308 std::vector<std::string> css_sources =
309 injector_->GetCssSources(run_location_);
310 for (std::vector<std::string>::const_iterator iter = css_sources.begin();
311 iter != css_sources.end();
312 ++iter) {
313 frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
317 } // namespace extensions