Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / extensions / renderer / script_context.cc
bloba1af29591c3b6f497d9222a6e68e21d8995d9366
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/common/url_constants.h"
13 #include "content/public/renderer/render_frame.h"
14 #include "content/public/renderer/render_view.h"
15 #include "content/public/renderer/v8_value_converter.h"
16 #include "extensions/common/extension.h"
17 #include "extensions/common/extension_api.h"
18 #include "extensions/common/extension_urls.h"
19 #include "extensions/common/features/base_feature_provider.h"
20 #include "gin/per_context_data.h"
21 #include "third_party/WebKit/public/web/WebDataSource.h"
22 #include "third_party/WebKit/public/web/WebDocument.h"
23 #include "third_party/WebKit/public/web/WebFrame.h"
24 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
25 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
26 #include "third_party/WebKit/public/web/WebView.h"
27 #include "v8/include/v8.h"
29 using content::V8ValueConverter;
31 namespace extensions {
33 ScriptContext::ScriptContext(const v8::Handle<v8::Context>& v8_context,
34 blink::WebFrame* web_frame,
35 const Extension* extension,
36 Feature::Context context_type)
37 : v8_context_(v8_context),
38 web_frame_(web_frame),
39 extension_(extension),
40 context_type_(context_type),
41 safe_builtins_(this),
42 isolate_(v8_context->GetIsolate()) {
43 VLOG(1) << "Created context:\n"
44 << " extension id: " << GetExtensionID() << "\n"
45 << " frame: " << web_frame_ << "\n"
46 << " URL: " << GetURL() << "\n"
47 << " context type: " << GetContextTypeDescription();
48 gin::PerContextData::From(v8_context)->set_runner(this);
51 ScriptContext::~ScriptContext() {
52 VLOG(1) << "Destroyed context for extension\n"
53 << " extension id: " << GetExtensionID();
54 Invalidate();
57 void ScriptContext::Invalidate() {
58 if (!is_valid())
59 return;
60 if (module_system_)
61 module_system_->Invalidate();
62 web_frame_ = NULL;
63 v8_context_.reset();
66 const std::string& ScriptContext::GetExtensionID() const {
67 return extension_.get() ? extension_->id() : base::EmptyString();
70 content::RenderView* ScriptContext::GetRenderView() const {
71 if (web_frame_ && web_frame_->view())
72 return content::RenderView::FromWebView(web_frame_->view());
73 return NULL;
76 content::RenderFrame* ScriptContext::GetRenderFrame() const {
77 if (web_frame_)
78 return content::RenderFrame::FromWebFrame(web_frame_);
79 return NULL;
82 v8::Local<v8::Value> ScriptContext::CallFunction(
83 v8::Handle<v8::Function> function,
84 int argc,
85 v8::Handle<v8::Value> argv[]) const {
86 v8::EscapableHandleScope handle_scope(isolate());
87 v8::Context::Scope scope(v8_context());
89 blink::WebScopedMicrotaskSuppression suppression;
90 if (!is_valid()) {
91 return handle_scope.Escape(
92 v8::Local<v8::Primitive>(v8::Undefined(isolate())));
95 v8::Handle<v8::Object> global = v8_context()->Global();
96 if (!web_frame_)
97 return handle_scope.Escape(function->Call(global, argc, argv));
98 return handle_scope.Escape(
99 v8::Local<v8::Value>(web_frame_->callFunctionEvenIfScriptDisabled(
100 function, global, argc, argv)));
103 Feature::Availability ScriptContext::GetAvailability(
104 const std::string& api_name) {
105 // Hack: Hosted apps should have the availability of messaging APIs based on
106 // the URL of the page (which might have access depending on some extension
107 // with externally_connectable), not whether the app has access to messaging
108 // (which it won't).
109 const Extension* extension = extension_.get();
110 if (extension && extension->is_hosted_app() &&
111 (api_name == "runtime.connect" || api_name == "runtime.sendMessage")) {
112 extension = NULL;
114 return ExtensionAPI::GetSharedInstance()->IsAvailable(
115 api_name, extension, context_type_, GetURL());
118 void ScriptContext::DispatchEvent(const char* event_name,
119 v8::Handle<v8::Array> args) const {
120 v8::HandleScope handle_scope(isolate());
121 v8::Context::Scope context_scope(v8_context());
123 v8::Handle<v8::Value> argv[] = {
124 v8::String::NewFromUtf8(isolate(), event_name), args};
125 module_system_->CallModuleMethod(
126 kEventBindings, "dispatchEvent", arraysize(argv), argv);
129 void ScriptContext::DispatchOnUnloadEvent() {
130 v8::HandleScope handle_scope(isolate());
131 v8::Context::Scope context_scope(v8_context());
132 module_system_->CallModuleMethod("unload_event", "dispatch");
135 std::string ScriptContext::GetContextTypeDescription() {
136 switch (context_type_) {
137 case Feature::UNSPECIFIED_CONTEXT:
138 return "UNSPECIFIED";
139 case Feature::BLESSED_EXTENSION_CONTEXT:
140 return "BLESSED_EXTENSION";
141 case Feature::UNBLESSED_EXTENSION_CONTEXT:
142 return "UNBLESSED_EXTENSION";
143 case Feature::CONTENT_SCRIPT_CONTEXT:
144 return "CONTENT_SCRIPT";
145 case Feature::WEB_PAGE_CONTEXT:
146 return "WEB_PAGE";
147 case Feature::BLESSED_WEB_PAGE_CONTEXT:
148 return "BLESSED_WEB_PAGE";
149 case Feature::WEBUI_CONTEXT:
150 return "WEBUI";
152 NOTREACHED();
153 return std::string();
156 GURL ScriptContext::GetURL() const {
157 return web_frame() ? GetDataSourceURLForFrame(web_frame()) : GURL();
160 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature& api) {
161 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
162 api, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
165 // static
166 GURL ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame* frame) {
167 // Normally we would use frame->document().url() to determine the document's
168 // URL, but to decide whether to inject a content script, we use the URL from
169 // the data source. This "quirk" helps prevents content scripts from
170 // inadvertently adding DOM elements to the compose iframe in Gmail because
171 // the compose iframe's dataSource URL is about:blank, but the document URL
172 // changes to match the parent document after Gmail document.writes into
173 // it to create the editor.
174 // http://code.google.com/p/chromium/issues/detail?id=86742
175 blink::WebDataSource* data_source = frame->provisionalDataSource()
176 ? frame->provisionalDataSource()
177 : frame->dataSource();
178 return data_source ? GURL(data_source->request().url()) : GURL();
181 // static
182 GURL ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame* frame,
183 const GURL& document_url,
184 bool match_about_blank) {
185 // Common scenario. If |match_about_blank| is false (as is the case in most
186 // extensions), or if the frame is not an about:-page, just return
187 // |document_url| (supposedly the URL of the frame).
188 if (!match_about_blank || !document_url.SchemeIs(url::kAboutScheme))
189 return document_url;
191 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
192 // origin from their parent frame/window. So, traverse the frame/window
193 // hierarchy to find the closest non-about:-page and return its URL.
194 const blink::WebFrame* parent = frame;
195 do {
196 parent = parent->parent() ? parent->parent() : parent->opener();
197 } while (parent != NULL && !parent->document().isNull() &&
198 GURL(parent->document().url()).SchemeIs(url::kAboutScheme));
200 if (parent && !parent->document().isNull()) {
201 // Only return the parent URL if the frame can access it.
202 const blink::WebDocument& parent_document = parent->document();
203 if (frame->document().securityOrigin().canAccess(
204 parent_document.securityOrigin()))
205 return parent_document.url();
207 return document_url;
210 ScriptContext* ScriptContext::GetContext() { return this; }
212 void ScriptContext::OnResponseReceived(const std::string& name,
213 int request_id,
214 bool success,
215 const base::ListValue& response,
216 const std::string& error) {
217 v8::HandleScope handle_scope(isolate());
219 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
220 v8::Handle<v8::Value> argv[] = {
221 v8::Integer::New(isolate(), request_id),
222 v8::String::NewFromUtf8(isolate(), name.c_str()),
223 v8::Boolean::New(isolate(), success),
224 converter->ToV8Value(&response, v8_context_.NewHandle(isolate())),
225 v8::String::NewFromUtf8(isolate(), error.c_str())};
227 v8::Handle<v8::Value> retval = module_system()->CallModuleMethod(
228 "sendRequest", "handleResponse", arraysize(argv), argv);
230 // In debug, the js will validate the callback parameters and return a
231 // string if a validation error has occured.
232 DCHECK(retval.IsEmpty() || retval->IsUndefined())
233 << *v8::String::Utf8Value(retval);
236 void ScriptContext::Run(const std::string& source,
237 const std::string& resource_name) {
238 module_system_->RunString(source, resource_name);
241 v8::Handle<v8::Value> ScriptContext::Call(v8::Handle<v8::Function> function,
242 v8::Handle<v8::Value> receiver,
243 int argc,
244 v8::Handle<v8::Value> argv[]) {
245 return CallFunction(function, argc, argv);
248 gin::ContextHolder* ScriptContext::GetContextHolder() {
249 v8::HandleScope handle_scope(isolate());
250 return gin::PerContextData::From(v8_context())->context_holder();
253 } // namespace extensions