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/user_script_scheduler.h"
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "chrome/renderer/chrome_render_process_observer.h"
11 #include "chrome/renderer/extensions/chrome_v8_context.h"
12 #include "chrome/renderer/extensions/dispatcher.h"
13 #include "chrome/renderer/extensions/dom_activity_logger.h"
14 #include "chrome/renderer/extensions/extension_groups.h"
15 #include "chrome/renderer/extensions/extension_helper.h"
16 #include "chrome/renderer/extensions/user_script_slave.h"
17 #include "content/public/renderer/render_view.h"
18 #include "content/public/renderer/v8_value_converter.h"
19 #include "extensions/common/error_utils.h"
20 #include "extensions/common/extension_messages.h"
21 #include "extensions/common/manifest_constants.h"
22 #include "extensions/common/permissions/permissions_data.h"
23 #include "third_party/WebKit/public/platform/WebString.h"
24 #include "third_party/WebKit/public/platform/WebVector.h"
25 #include "third_party/WebKit/public/web/WebDocument.h"
26 #include "third_party/WebKit/public/web/WebFrame.h"
27 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
28 #include "third_party/WebKit/public/web/WebView.h"
29 #include "v8/include/v8.h"
32 // The length of time to wait after the DOM is complete to try and run user
34 const int kUserScriptIdleTimeoutMs = 200;
37 using blink::WebDocument;
38 using blink::WebFrame;
39 using blink::WebString;
40 using blink::WebVector;
43 namespace extensions {
45 UserScriptScheduler::UserScriptScheduler(WebFrame* frame,
46 Dispatcher* dispatcher)
47 : weak_factory_(this),
49 current_location_(UserScript::UNDEFINED),
51 dispatcher_(dispatcher) {
52 for (int i = UserScript::UNDEFINED; i < UserScript::RUN_LOCATION_LAST; ++i) {
53 pending_execution_map_[static_cast<UserScript::RunLocation>(i)] =
54 std::queue<linked_ptr<ExtensionMsg_ExecuteCode_Params> >();
58 UserScriptScheduler::~UserScriptScheduler() {
61 void UserScriptScheduler::ExecuteCode(
62 const ExtensionMsg_ExecuteCode_Params& params) {
63 UserScript::RunLocation run_at =
64 static_cast<UserScript::RunLocation>(params.run_at);
65 if (current_location_ < run_at) {
66 pending_execution_map_[run_at].push(
67 linked_ptr<ExtensionMsg_ExecuteCode_Params>(
68 new ExtensionMsg_ExecuteCode_Params(params)));
72 ExecuteCodeImpl(params);
75 void UserScriptScheduler::DidCreateDocumentElement() {
76 current_location_ = UserScript::DOCUMENT_START;
80 void UserScriptScheduler::DidFinishDocumentLoad() {
81 current_location_ = UserScript::DOCUMENT_END;
83 // Schedule a run for DOCUMENT_IDLE
84 base::MessageLoop::current()->PostDelayedTask(
86 base::Bind(&UserScriptScheduler::IdleTimeout, weak_factory_.GetWeakPtr()),
87 base::TimeDelta::FromMilliseconds(kUserScriptIdleTimeoutMs));
90 void UserScriptScheduler::DidFinishLoad() {
91 current_location_ = UserScript::DOCUMENT_IDLE;
92 // Ensure that running scripts does not keep any progress UI running.
93 base::MessageLoop::current()->PostTask(
95 base::Bind(&UserScriptScheduler::MaybeRun, weak_factory_.GetWeakPtr()));
98 void UserScriptScheduler::DidStartProvisionalLoad() {
99 // The frame is navigating, so reset the state since we'll want to inject
100 // scripts once the load finishes.
101 current_location_ = UserScript::UNDEFINED;
102 has_run_idle_ = false;
103 weak_factory_.InvalidateWeakPtrs();
104 std::map<UserScript::RunLocation, ExecutionQueue>::iterator itr =
105 pending_execution_map_.begin();
106 for (itr = pending_execution_map_.begin();
107 itr != pending_execution_map_.end(); ++itr) {
108 while (!itr->second.empty())
113 void UserScriptScheduler::IdleTimeout() {
114 current_location_ = UserScript::DOCUMENT_IDLE;
118 void UserScriptScheduler::MaybeRun() {
119 if (current_location_ == UserScript::UNDEFINED)
122 if (!has_run_idle_ && current_location_ == UserScript::DOCUMENT_IDLE) {
123 has_run_idle_ = true;
124 dispatcher_->user_script_slave()->InjectScripts(
125 frame_, UserScript::DOCUMENT_IDLE);
128 // Run all tasks from the current time and earlier.
129 for (int i = UserScript::DOCUMENT_START;
130 i <= current_location_; ++i) {
131 UserScript::RunLocation run_time = static_cast<UserScript::RunLocation>(i);
132 while (!pending_execution_map_[run_time].empty()) {
133 linked_ptr<ExtensionMsg_ExecuteCode_Params>& params =
134 pending_execution_map_[run_time].front();
135 ExecuteCodeImpl(*params);
136 pending_execution_map_[run_time].pop();
141 void UserScriptScheduler::ExecuteCodeImpl(
142 const ExtensionMsg_ExecuteCode_Params& params) {
143 const Extension* extension = dispatcher_->extensions()->GetByID(
144 params.extension_id);
145 content::RenderView* render_view =
146 content::RenderView::FromWebView(frame_->view());
147 ExtensionHelper* extension_helper = ExtensionHelper::Get(render_view);
148 base::ListValue execution_results;
150 // Since extension info is sent separately from user script info, they can
151 // be out of sync. We just ignore this situation.
154 new ExtensionHostMsg_ExecuteCodeFinished(render_view->GetRoutingID(),
156 std::string(), // no error
163 std::vector<WebFrame*> frame_vector;
164 frame_vector.push_back(frame_);
165 if (params.all_frames)
166 GetAllChildFrames(frame_, &frame_vector);
170 scoped_ptr<blink::WebScopedUserGesture> gesture;
171 if (params.user_gesture)
172 gesture.reset(new blink::WebScopedUserGesture);
174 for (std::vector<WebFrame*>::iterator frame_it = frame_vector.begin();
175 frame_it != frame_vector.end(); ++frame_it) {
176 WebFrame* child_frame = *frame_it;
177 if (params.is_javascript) {
178 // We recheck access here in the renderer for extra safety against races
181 // But different frames can have different URLs, and the extension might
182 // only have access to a subset of them. For the top frame, we can
183 // immediately send an error and stop because the browser process
184 // considers that an error too.
186 // For child frames, we just skip ones the extension doesn't have access
188 if (!params.is_web_view &&
189 !PermissionsData::CanExecuteScriptOnPage(
191 child_frame->document().url(),
192 frame_->document().url(),
193 extension_helper->tab_id(),
197 if (child_frame->parent()) {
200 error = ErrorUtils::FormatErrorMessage(
201 manifest_errors::kCannotAccessPage,
202 child_frame->document().url().spec());
207 WebScriptSource source(WebString::fromUTF8(params.code), params.file_url);
208 v8::HandleScope scope(v8::Isolate::GetCurrent());
210 scoped_ptr<content::V8ValueConverter> v8_converter(
211 content::V8ValueConverter::create());
212 v8::Local<v8::Value> script_value;
214 if (params.in_main_world) {
215 DOMActivityLogger::AttachToWorld(DOMActivityLogger::kMainWorldId,
217 script_value = child_frame->executeScriptAndReturnValue(source);
219 blink::WebVector<v8::Local<v8::Value> > results;
220 std::vector<WebScriptSource> sources;
221 sources.push_back(source);
222 int isolated_world_id =
223 dispatcher_->user_script_slave()->GetIsolatedWorldIdForExtension(
224 extension, child_frame);
225 DOMActivityLogger::AttachToWorld(isolated_world_id, extension->id());
226 child_frame->executeScriptInIsolatedWorld(
227 isolated_world_id, &sources.front(),
228 sources.size(), EXTENSION_GROUP_CONTENT_SCRIPTS, &results);
229 // We only expect one value back since we only pushed one source
230 if (results.size() == 1 && !results[0].IsEmpty())
231 script_value = results[0];
234 if (params.wants_result && !script_value.IsEmpty()) {
235 // It's safe to always use the main world context when converting here.
236 // V8ValueConverterImpl shouldn't actually care about the context scope,
237 // and it switches to v8::Object's creation context when encountered.
238 v8::Local<v8::Context> context = child_frame->mainWorldScriptContext();
239 base::Value* result = v8_converter->FromV8Value(script_value, context);
240 // Always append an execution result (i.e. no result == null result) so
241 // that |execution_results| lines up with the frames.
242 execution_results.Append(
243 result ? result : base::Value::CreateNullValue());
246 child_frame->document().insertStyleSheet(
247 WebString::fromUTF8(params.code));
251 render_view->Send(new ExtensionHostMsg_ExecuteCodeFinished(
252 render_view->GetRoutingID(),
255 render_view->GetPageId(),
256 UserScriptSlave::GetDataSourceURLForFrame(frame_),
260 bool UserScriptScheduler::GetAllChildFrames(
261 WebFrame* parent_frame,
262 std::vector<WebFrame*>* frames_vector) const {
266 for (WebFrame* child_frame = parent_frame->firstChild(); child_frame;
267 child_frame = child_frame->nextSibling()) {
268 frames_vector->push_back(child_frame);
269 GetAllChildFrames(child_frame, frames_vector);
274 } // namespace extensions