Roll src/third_party/WebKit 395ff9e:18c0088 (svn 192995:192997)
[chromium-blink-merge.git] / extensions / renderer / script_context.cc
blob84a1ce621cc49561c9eafa8f04ed5b8655942929
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_context.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "base/values.h"
12 #include "content/public/child/v8_value_converter.h"
13 #include "content/public/common/url_constants.h"
14 #include "content/public/renderer/render_frame.h"
15 #include "content/public/renderer/render_view.h"
16 #include "extensions/common/constants.h"
17 #include "extensions/common/extension.h"
18 #include "extensions/common/extension_api.h"
19 #include "extensions/common/extension_set.h"
20 #include "extensions/common/extension_urls.h"
21 #include "extensions/common/features/base_feature_provider.h"
22 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
23 #include "extensions/common/permissions/permissions_data.h"
24 #include "gin/per_context_data.h"
25 #include "third_party/WebKit/public/web/WebDataSource.h"
26 #include "third_party/WebKit/public/web/WebDocument.h"
27 #include "third_party/WebKit/public/web/WebFrame.h"
28 #include "third_party/WebKit/public/web/WebLocalFrame.h"
29 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
30 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
31 #include "third_party/WebKit/public/web/WebView.h"
32 #include "v8/include/v8.h"
34 using content::V8ValueConverter;
36 namespace extensions {
38 namespace {
40 std::string GetContextTypeDescriptionString(Feature::Context context_type) {
41 switch (context_type) {
42 case Feature::UNSPECIFIED_CONTEXT:
43 return "UNSPECIFIED";
44 case Feature::BLESSED_EXTENSION_CONTEXT:
45 return "BLESSED_EXTENSION";
46 case Feature::UNBLESSED_EXTENSION_CONTEXT:
47 return "UNBLESSED_EXTENSION";
48 case Feature::CONTENT_SCRIPT_CONTEXT:
49 return "CONTENT_SCRIPT";
50 case Feature::WEB_PAGE_CONTEXT:
51 return "WEB_PAGE";
52 case Feature::BLESSED_WEB_PAGE_CONTEXT:
53 return "BLESSED_WEB_PAGE";
54 case Feature::WEBUI_CONTEXT:
55 return "WEBUI";
57 NOTREACHED();
58 return std::string();
61 } // namespace
63 // A gin::Runner that delegates to its ScriptContext.
64 class ScriptContext::Runner : public gin::Runner {
65 public:
66 explicit Runner(ScriptContext* context);
68 // gin::Runner overrides.
69 void Run(const std::string& source,
70 const std::string& resource_name) override;
71 v8::Handle<v8::Value> Call(v8::Handle<v8::Function> function,
72 v8::Handle<v8::Value> receiver,
73 int argc,
74 v8::Handle<v8::Value> argv[]) override;
75 gin::ContextHolder* GetContextHolder() override;
77 private:
78 ScriptContext* context_;
81 ScriptContext::ScriptContext(const v8::Handle<v8::Context>& v8_context,
82 blink::WebLocalFrame* web_frame,
83 const Extension* extension,
84 Feature::Context context_type,
85 const Extension* effective_extension,
86 Feature::Context effective_context_type)
87 : v8_context_(v8_context->GetIsolate(), v8_context),
88 web_frame_(web_frame),
89 extension_(extension),
90 context_type_(context_type),
91 effective_extension_(effective_extension),
92 effective_context_type_(effective_context_type),
93 safe_builtins_(this),
94 isolate_(v8_context->GetIsolate()),
95 url_(web_frame_ ? GetDataSourceURLForFrame(web_frame_) : GURL()),
96 runner_(new Runner(this)) {
97 VLOG(1) << "Created context:\n"
98 << " extension id: " << GetExtensionID() << "\n"
99 << " frame: " << web_frame_ << "\n"
100 << " URL: " << GetURL() << "\n"
101 << " context type: " << GetContextTypeDescription() << "\n"
102 << " effective extension id: "
103 << (effective_extension_.get() ? effective_extension_->id() : "")
104 << " effective context type: "
105 << GetEffectiveContextTypeDescription();
106 gin::PerContextData* gin_data = gin::PerContextData::From(v8_context);
107 CHECK(gin_data); // may fail if the v8::Context hasn't been registered yet
108 gin_data->set_runner(runner_.get());
111 ScriptContext::~ScriptContext() {
112 VLOG(1) << "Destroyed context for extension\n"
113 << " extension id: " << GetExtensionID() << "\n"
114 << " effective extension id: "
115 << (effective_extension_.get() ? effective_extension_->id() : "");
116 Invalidate();
119 // static
120 bool ScriptContext::IsSandboxedPage(const ExtensionSet& extensions,
121 const GURL& url) {
122 // TODO(kalman): This is checking for the wrong thing, it should be checking
123 // if the frame's security origin is unique. The extension sandbox directive
124 // is checked for in extensions/common/manifest_handlers/csp_info.cc.
125 if (url.SchemeIs(kExtensionScheme)) {
126 const Extension* extension = extensions.GetByID(url.host());
127 if (extension) {
128 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
131 return false;
134 void ScriptContext::Invalidate() {
135 if (!is_valid())
136 return;
137 if (module_system_)
138 module_system_->Invalidate();
139 web_frame_ = NULL;
140 v8_context_.Reset();
141 runner_.reset();
144 const std::string& ScriptContext::GetExtensionID() const {
145 return extension_.get() ? extension_->id() : base::EmptyString();
148 content::RenderView* ScriptContext::GetRenderView() const {
149 if (web_frame_ && web_frame_->view())
150 return content::RenderView::FromWebView(web_frame_->view());
151 return NULL;
154 content::RenderFrame* ScriptContext::GetRenderFrame() const {
155 if (web_frame_)
156 return content::RenderFrame::FromWebFrame(web_frame_);
157 return NULL;
160 v8::Local<v8::Value> ScriptContext::CallFunction(
161 v8::Handle<v8::Function> function,
162 int argc,
163 v8::Handle<v8::Value> argv[]) const {
164 v8::EscapableHandleScope handle_scope(isolate());
165 v8::Context::Scope scope(v8_context());
167 blink::WebScopedMicrotaskSuppression suppression;
168 if (!is_valid()) {
169 return handle_scope.Escape(
170 v8::Local<v8::Primitive>(v8::Undefined(isolate())));
173 v8::Handle<v8::Object> global = v8_context()->Global();
174 if (!web_frame_)
175 return handle_scope.Escape(function->Call(global, argc, argv));
176 return handle_scope.Escape(
177 v8::Local<v8::Value>(web_frame_->callFunctionEvenIfScriptDisabled(
178 function, global, argc, argv)));
181 Feature::Availability ScriptContext::GetAvailability(
182 const std::string& api_name) {
183 // Hack: Hosted apps should have the availability of messaging APIs based on
184 // the URL of the page (which might have access depending on some extension
185 // with externally_connectable), not whether the app has access to messaging
186 // (which it won't).
187 const Extension* extension = extension_.get();
188 if (extension && extension->is_hosted_app() &&
189 (api_name == "runtime.connect" || api_name == "runtime.sendMessage")) {
190 extension = NULL;
192 return ExtensionAPI::GetSharedInstance()->IsAvailable(
193 api_name, extension, context_type_, GetURL());
196 void ScriptContext::DispatchEvent(const char* event_name,
197 v8::Handle<v8::Array> args) const {
198 v8::HandleScope handle_scope(isolate());
199 v8::Context::Scope context_scope(v8_context());
201 v8::Handle<v8::Value> argv[] = {
202 v8::String::NewFromUtf8(isolate(), event_name), args};
203 module_system_->CallModuleMethod(
204 kEventBindings, "dispatchEvent", arraysize(argv), argv);
207 void ScriptContext::DispatchOnUnloadEvent() {
208 v8::HandleScope handle_scope(isolate());
209 v8::Context::Scope context_scope(v8_context());
210 module_system_->CallModuleMethod("unload_event", "dispatch");
213 std::string ScriptContext::GetContextTypeDescription() {
214 return GetContextTypeDescriptionString(context_type_);
217 std::string ScriptContext::GetEffectiveContextTypeDescription() {
218 return GetContextTypeDescriptionString(effective_context_type_);
221 GURL ScriptContext::GetURL() const {
222 return url_;
225 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature& api) {
226 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
227 api, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
230 // static
231 GURL ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame* frame) {
232 // Normally we would use frame->document().url() to determine the document's
233 // URL, but to decide whether to inject a content script, we use the URL from
234 // the data source. This "quirk" helps prevents content scripts from
235 // inadvertently adding DOM elements to the compose iframe in Gmail because
236 // the compose iframe's dataSource URL is about:blank, but the document URL
237 // changes to match the parent document after Gmail document.writes into
238 // it to create the editor.
239 // http://code.google.com/p/chromium/issues/detail?id=86742
240 blink::WebDataSource* data_source = frame->provisionalDataSource()
241 ? frame->provisionalDataSource()
242 : frame->dataSource();
243 return data_source ? GURL(data_source->request().url()) : GURL();
246 // static
247 GURL ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame* frame,
248 const GURL& document_url,
249 bool match_about_blank) {
250 // Common scenario. If |match_about_blank| is false (as is the case in most
251 // extensions), or if the frame is not an about:-page, just return
252 // |document_url| (supposedly the URL of the frame).
253 if (!match_about_blank || !document_url.SchemeIs(url::kAboutScheme))
254 return document_url;
256 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
257 // origin from their parent frame/window. So, traverse the frame/window
258 // hierarchy to find the closest non-about:-page and return its URL.
259 const blink::WebFrame* parent = frame;
260 do {
261 parent = parent->parent() ? parent->parent() : parent->opener();
262 } while (parent != NULL && !parent->document().isNull() &&
263 GURL(parent->document().url()).SchemeIs(url::kAboutScheme));
265 if (parent && !parent->document().isNull()) {
266 // Only return the parent URL if the frame can access it.
267 const blink::WebDocument& parent_document = parent->document();
268 if (frame->document().securityOrigin().canAccess(
269 parent_document.securityOrigin()))
270 return parent_document.url();
272 return document_url;
275 ScriptContext* ScriptContext::GetContext() { return this; }
277 void ScriptContext::OnResponseReceived(const std::string& name,
278 int request_id,
279 bool success,
280 const base::ListValue& response,
281 const std::string& error) {
282 v8::HandleScope handle_scope(isolate());
284 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
285 v8::Handle<v8::Value> argv[] = {
286 v8::Integer::New(isolate(), request_id),
287 v8::String::NewFromUtf8(isolate(), name.c_str()),
288 v8::Boolean::New(isolate(), success),
289 converter->ToV8Value(&response,
290 v8::Local<v8::Context>::New(isolate(), v8_context_)),
291 v8::String::NewFromUtf8(isolate(), error.c_str())};
293 v8::Handle<v8::Value> retval = module_system()->CallModuleMethod(
294 "sendRequest", "handleResponse", arraysize(argv), argv);
296 // In debug, the js will validate the callback parameters and return a
297 // string if a validation error has occured.
298 DCHECK(retval.IsEmpty() || retval->IsUndefined())
299 << *v8::String::Utf8Value(retval);
302 void ScriptContext::SetContentCapabilities(
303 const APIPermissionSet& permissions) {
304 content_capabilities_ = permissions;
307 bool ScriptContext::HasAPIPermission(APIPermission::ID permission) const {
308 if (effective_extension_.get()) {
309 return effective_extension_->permissions_data()->HasAPIPermission(
310 permission);
311 } else if (context_type() == Feature::WEB_PAGE_CONTEXT) {
312 // Only web page contexts may be granted content capabilities. Other
313 // contexts are either privileged WebUI or extensions with their own set of
314 // permissions.
315 if (content_capabilities_.find(permission) != content_capabilities_.end())
316 return true;
318 return false;
321 ScriptContext::Runner::Runner(ScriptContext* context) : context_(context) {
323 void ScriptContext::Runner::Run(const std::string& source,
324 const std::string& resource_name) {
325 context_->module_system()->RunString(source, resource_name);
328 v8::Handle<v8::Value> ScriptContext::Runner::Call(
329 v8::Handle<v8::Function> function,
330 v8::Handle<v8::Value> receiver,
331 int argc,
332 v8::Handle<v8::Value> argv[]) {
333 return context_->CallFunction(function, argc, argv);
336 gin::ContextHolder* ScriptContext::Runner::GetContextHolder() {
337 v8::HandleScope handle_scope(context_->isolate());
338 return gin::PerContextData::From(context_->v8_context())->context_holder();
341 } // namespace extensions