Move about://-related constants from //content to //url
[chromium-blink-merge.git] / extensions / renderer / script_context.cc
blobb4eeefd007e3e998ff7716083a31b3613a62596c
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/values.h"
11 #include "content/public/common/url_constants.h"
12 #include "content/public/renderer/render_view.h"
13 #include "content/public/renderer/v8_value_converter.h"
14 #include "extensions/common/extension.h"
15 #include "extensions/common/extension_api.h"
16 #include "extensions/common/extension_urls.h"
17 #include "extensions/common/features/base_feature_provider.h"
18 #include "third_party/WebKit/public/web/WebDataSource.h"
19 #include "third_party/WebKit/public/web/WebDocument.h"
20 #include "third_party/WebKit/public/web/WebFrame.h"
21 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
22 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
23 #include "third_party/WebKit/public/web/WebView.h"
24 #include "v8/include/v8.h"
26 using content::V8ValueConverter;
28 namespace extensions {
30 ScriptContext::ScriptContext(const v8::Handle<v8::Context>& v8_context,
31 blink::WebFrame* web_frame,
32 const Extension* extension,
33 Feature::Context context_type)
34 : v8_context_(v8_context),
35 web_frame_(web_frame),
36 extension_(extension),
37 context_type_(context_type),
38 safe_builtins_(this),
39 isolate_(v8_context->GetIsolate()) {
40 VLOG(1) << "Created context:\n"
41 << " extension id: " << GetExtensionID() << "\n"
42 << " frame: " << web_frame_ << "\n"
43 << " context type: " << GetContextTypeDescription();
46 ScriptContext::~ScriptContext() {
47 VLOG(1) << "Destroyed context for extension\n"
48 << " extension id: " << GetExtensionID();
49 Invalidate();
52 void ScriptContext::Invalidate() {
53 if (!is_valid())
54 return;
55 if (module_system_)
56 module_system_->Invalidate();
57 web_frame_ = NULL;
58 v8_context_.reset();
61 std::string ScriptContext::GetExtensionID() const {
62 return extension_.get() ? extension_->id() : std::string();
65 content::RenderView* ScriptContext::GetRenderView() const {
66 if (web_frame_ && web_frame_->view())
67 return content::RenderView::FromWebView(web_frame_->view());
68 else
69 return NULL;
72 v8::Local<v8::Value> ScriptContext::CallFunction(
73 v8::Handle<v8::Function> function,
74 int argc,
75 v8::Handle<v8::Value> argv[]) const {
76 v8::EscapableHandleScope handle_scope(isolate());
77 v8::Context::Scope scope(v8_context());
79 blink::WebScopedMicrotaskSuppression suppression;
80 if (!is_valid()) {
81 return handle_scope.Escape(
82 v8::Local<v8::Primitive>(v8::Undefined(isolate())));
85 v8::Handle<v8::Object> global = v8_context()->Global();
86 if (!web_frame_)
87 return handle_scope.Escape(function->Call(global, argc, argv));
88 return handle_scope.Escape(
89 v8::Local<v8::Value>(web_frame_->callFunctionEvenIfScriptDisabled(
90 function, global, argc, argv)));
93 Feature::Availability ScriptContext::GetAvailability(
94 const std::string& api_name) {
95 // Hack: Hosted apps should have the availability of messaging APIs based on
96 // the URL of the page (which might have access depending on some extension
97 // with externally_connectable), not whether the app has access to messaging
98 // (which it won't).
99 const Extension* extension = extension_.get();
100 if (extension && extension->is_hosted_app() &&
101 (api_name == "runtime.connect" || api_name == "runtime.sendMessage")) {
102 extension = NULL;
104 return ExtensionAPI::GetSharedInstance()->IsAvailable(
105 api_name, extension, context_type_, GetURL());
108 void ScriptContext::DispatchEvent(const char* event_name,
109 v8::Handle<v8::Array> args) const {
110 v8::HandleScope handle_scope(isolate());
111 v8::Context::Scope context_scope(v8_context());
113 v8::Handle<v8::Value> argv[] = {
114 v8::String::NewFromUtf8(isolate(), event_name), args};
115 module_system_->CallModuleMethod(
116 kEventBindings, "dispatchEvent", arraysize(argv), argv);
119 void ScriptContext::DispatchOnUnloadEvent() {
120 module_system_->CallModuleMethod("unload_event", "dispatch");
123 std::string ScriptContext::GetContextTypeDescription() {
124 switch (context_type_) {
125 case Feature::UNSPECIFIED_CONTEXT:
126 return "UNSPECIFIED";
127 case Feature::BLESSED_EXTENSION_CONTEXT:
128 return "BLESSED_EXTENSION";
129 case Feature::UNBLESSED_EXTENSION_CONTEXT:
130 return "UNBLESSED_EXTENSION";
131 case Feature::CONTENT_SCRIPT_CONTEXT:
132 return "CONTENT_SCRIPT";
133 case Feature::WEB_PAGE_CONTEXT:
134 return "WEB_PAGE";
135 case Feature::BLESSED_WEB_PAGE_CONTEXT:
136 return "BLESSED_WEB_PAGE";
138 NOTREACHED();
139 return std::string();
142 GURL ScriptContext::GetURL() const {
143 return web_frame() ? GetDataSourceURLForFrame(web_frame()) : GURL();
146 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature& api) {
147 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
148 api, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
151 // static
152 GURL ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame* frame) {
153 // Normally we would use frame->document().url() to determine the document's
154 // URL, but to decide whether to inject a content script, we use the URL from
155 // the data source. This "quirk" helps prevents content scripts from
156 // inadvertently adding DOM elements to the compose iframe in Gmail because
157 // the compose iframe's dataSource URL is about:blank, but the document URL
158 // changes to match the parent document after Gmail document.writes into
159 // it to create the editor.
160 // http://code.google.com/p/chromium/issues/detail?id=86742
161 blink::WebDataSource* data_source = frame->provisionalDataSource()
162 ? frame->provisionalDataSource()
163 : frame->dataSource();
164 CHECK(data_source);
165 return GURL(data_source->request().url());
168 // static
169 GURL ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame* frame,
170 const GURL& document_url,
171 bool match_about_blank) {
172 // Common scenario. If |match_about_blank| is false (as is the case in most
173 // extensions), or if the frame is not an about:-page, just return
174 // |document_url| (supposedly the URL of the frame).
175 if (!match_about_blank || !document_url.SchemeIs(url::kAboutScheme))
176 return document_url;
178 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
179 // origin from their parent frame/window. So, traverse the frame/window
180 // hierarchy to find the closest non-about:-page and return its URL.
181 const blink::WebFrame* parent = frame;
182 do {
183 parent = parent->parent() ? parent->parent() : parent->opener();
184 } while (parent != NULL &&
185 GURL(parent->document().url()).SchemeIs(url::kAboutScheme));
187 if (parent) {
188 // Only return the parent URL if the frame can access it.
189 const blink::WebDocument& parent_document = parent->document();
190 if (frame->document().securityOrigin().canAccess(
191 parent_document.securityOrigin()))
192 return parent_document.url();
194 return document_url;
197 ScriptContext* ScriptContext::GetContext() { return this; }
199 void ScriptContext::OnResponseReceived(const std::string& name,
200 int request_id,
201 bool success,
202 const base::ListValue& response,
203 const std::string& error) {
204 v8::HandleScope handle_scope(isolate());
206 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
207 v8::Handle<v8::Value> argv[] = {
208 v8::Integer::New(isolate(), request_id),
209 v8::String::NewFromUtf8(isolate(), name.c_str()),
210 v8::Boolean::New(isolate(), success),
211 converter->ToV8Value(&response, v8_context_.NewHandle(isolate())),
212 v8::String::NewFromUtf8(isolate(), error.c_str())};
214 v8::Handle<v8::Value> retval = module_system()->CallModuleMethod(
215 "sendRequest", "handleResponse", arraysize(argv), argv);
217 // In debug, the js will validate the callback parameters and return a
218 // string if a validation error has occured.
219 DCHECK(retval.IsEmpty() || retval->IsUndefined())
220 << *v8::String::Utf8Value(retval);
223 } // namespace extensions