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/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 "extensions/common/permissions/permissions_data.h"
21 #include "gin/per_context_data.h"
22 #include "third_party/WebKit/public/web/WebDataSource.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/WebScopedMicrotaskSuppression.h"
26 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
27 #include "third_party/WebKit/public/web/WebView.h"
28 #include "v8/include/v8.h"
30 using content::V8ValueConverter
;
32 namespace extensions
{
36 std::string
GetContextTypeDescriptionString(Feature::Context context_type
) {
37 switch (context_type
) {
38 case Feature::UNSPECIFIED_CONTEXT
:
40 case Feature::BLESSED_EXTENSION_CONTEXT
:
41 return "BLESSED_EXTENSION";
42 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
43 return "UNBLESSED_EXTENSION";
44 case Feature::CONTENT_SCRIPT_CONTEXT
:
45 return "CONTENT_SCRIPT";
46 case Feature::WEB_PAGE_CONTEXT
:
48 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
49 return "BLESSED_WEB_PAGE";
50 case Feature::WEBUI_CONTEXT
:
59 // A gin::Runner that delegates to its ScriptContext.
60 class ScriptContext::Runner
: public gin::Runner
{
62 explicit Runner(ScriptContext
* context
);
64 // gin::Runner overrides.
65 void Run(const std::string
& source
,
66 const std::string
& resource_name
) override
;
67 v8::Handle
<v8::Value
> Call(v8::Handle
<v8::Function
> function
,
68 v8::Handle
<v8::Value
> receiver
,
70 v8::Handle
<v8::Value
> argv
[]) override
;
71 gin::ContextHolder
* GetContextHolder() override
;
74 ScriptContext
* context_
;
77 ScriptContext::ScriptContext(const v8::Handle
<v8::Context
>& v8_context
,
78 blink::WebFrame
* web_frame
,
79 const Extension
* extension
,
80 Feature::Context context_type
,
81 const Extension
* effective_extension
,
82 Feature::Context effective_context_type
)
83 : v8_context_(v8_context
->GetIsolate(), v8_context
),
84 web_frame_(web_frame
),
85 extension_(extension
),
86 context_type_(context_type
),
87 effective_extension_(effective_extension
),
88 effective_context_type_(effective_context_type
),
90 isolate_(v8_context
->GetIsolate()),
91 url_(web_frame_
? GetDataSourceURLForFrame(web_frame_
) : GURL()),
92 runner_(new Runner(this)) {
93 VLOG(1) << "Created context:\n"
94 << " extension id: " << GetExtensionID() << "\n"
95 << " frame: " << web_frame_
<< "\n"
96 << " URL: " << GetURL() << "\n"
97 << " context type: " << GetContextTypeDescription() << "\n"
98 << " effective extension id: "
99 << (effective_extension_
.get() ? effective_extension_
->id() : "")
100 << " effective context type: "
101 << GetEffectiveContextTypeDescription();
102 gin::PerContextData::From(v8_context
)->set_runner(runner_
.get());
105 ScriptContext::~ScriptContext() {
106 VLOG(1) << "Destroyed context for extension\n"
107 << " extension id: " << GetExtensionID() << "\n"
108 << " effective extension id: "
109 << (effective_extension_
.get() ? effective_extension_
->id() : "");
113 void ScriptContext::Invalidate() {
117 module_system_
->Invalidate();
123 const std::string
& ScriptContext::GetExtensionID() const {
124 return extension_
.get() ? extension_
->id() : base::EmptyString();
127 content::RenderView
* ScriptContext::GetRenderView() const {
128 if (web_frame_
&& web_frame_
->view())
129 return content::RenderView::FromWebView(web_frame_
->view());
133 content::RenderFrame
* ScriptContext::GetRenderFrame() const {
135 return content::RenderFrame::FromWebFrame(web_frame_
);
139 v8::Local
<v8::Value
> ScriptContext::CallFunction(
140 v8::Handle
<v8::Function
> function
,
142 v8::Handle
<v8::Value
> argv
[]) const {
143 v8::EscapableHandleScope
handle_scope(isolate());
144 v8::Context::Scope
scope(v8_context());
146 blink::WebScopedMicrotaskSuppression suppression
;
148 return handle_scope
.Escape(
149 v8::Local
<v8::Primitive
>(v8::Undefined(isolate())));
152 v8::Handle
<v8::Object
> global
= v8_context()->Global();
154 return handle_scope
.Escape(function
->Call(global
, argc
, argv
));
155 return handle_scope
.Escape(
156 v8::Local
<v8::Value
>(web_frame_
->callFunctionEvenIfScriptDisabled(
157 function
, global
, argc
, argv
)));
160 Feature::Availability
ScriptContext::GetAvailability(
161 const std::string
& api_name
) {
162 // Hack: Hosted apps should have the availability of messaging APIs based on
163 // the URL of the page (which might have access depending on some extension
164 // with externally_connectable), not whether the app has access to messaging
166 const Extension
* extension
= extension_
.get();
167 if (extension
&& extension
->is_hosted_app() &&
168 (api_name
== "runtime.connect" || api_name
== "runtime.sendMessage")) {
171 return ExtensionAPI::GetSharedInstance()->IsAvailable(
172 api_name
, extension
, context_type_
, GetURL());
175 void ScriptContext::DispatchEvent(const char* event_name
,
176 v8::Handle
<v8::Array
> args
) const {
177 v8::HandleScope
handle_scope(isolate());
178 v8::Context::Scope
context_scope(v8_context());
180 v8::Handle
<v8::Value
> argv
[] = {
181 v8::String::NewFromUtf8(isolate(), event_name
), args
};
182 module_system_
->CallModuleMethod(
183 kEventBindings
, "dispatchEvent", arraysize(argv
), argv
);
186 void ScriptContext::DispatchOnUnloadEvent() {
187 v8::HandleScope
handle_scope(isolate());
188 v8::Context::Scope
context_scope(v8_context());
189 module_system_
->CallModuleMethod("unload_event", "dispatch");
192 std::string
ScriptContext::GetContextTypeDescription() {
193 return GetContextTypeDescriptionString(context_type_
);
196 std::string
ScriptContext::GetEffectiveContextTypeDescription() {
197 return GetContextTypeDescriptionString(effective_context_type_
);
200 GURL
ScriptContext::GetURL() const {
204 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature
& api
) {
205 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
206 api
, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
210 GURL
ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame
* frame
) {
211 // Normally we would use frame->document().url() to determine the document's
212 // URL, but to decide whether to inject a content script, we use the URL from
213 // the data source. This "quirk" helps prevents content scripts from
214 // inadvertently adding DOM elements to the compose iframe in Gmail because
215 // the compose iframe's dataSource URL is about:blank, but the document URL
216 // changes to match the parent document after Gmail document.writes into
217 // it to create the editor.
218 // http://code.google.com/p/chromium/issues/detail?id=86742
219 blink::WebDataSource
* data_source
= frame
->provisionalDataSource()
220 ? frame
->provisionalDataSource()
221 : frame
->dataSource();
222 return data_source
? GURL(data_source
->request().url()) : GURL();
226 GURL
ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame
* frame
,
227 const GURL
& document_url
,
228 bool match_about_blank
) {
229 // Common scenario. If |match_about_blank| is false (as is the case in most
230 // extensions), or if the frame is not an about:-page, just return
231 // |document_url| (supposedly the URL of the frame).
232 if (!match_about_blank
|| !document_url
.SchemeIs(url::kAboutScheme
))
235 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
236 // origin from their parent frame/window. So, traverse the frame/window
237 // hierarchy to find the closest non-about:-page and return its URL.
238 const blink::WebFrame
* parent
= frame
;
240 parent
= parent
->parent() ? parent
->parent() : parent
->opener();
241 } while (parent
!= NULL
&& !parent
->document().isNull() &&
242 GURL(parent
->document().url()).SchemeIs(url::kAboutScheme
));
244 if (parent
&& !parent
->document().isNull()) {
245 // Only return the parent URL if the frame can access it.
246 const blink::WebDocument
& parent_document
= parent
->document();
247 if (frame
->document().securityOrigin().canAccess(
248 parent_document
.securityOrigin()))
249 return parent_document
.url();
254 ScriptContext
* ScriptContext::GetContext() { return this; }
256 void ScriptContext::OnResponseReceived(const std::string
& name
,
259 const base::ListValue
& response
,
260 const std::string
& error
) {
261 v8::HandleScope
handle_scope(isolate());
263 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
264 v8::Handle
<v8::Value
> argv
[] = {
265 v8::Integer::New(isolate(), request_id
),
266 v8::String::NewFromUtf8(isolate(), name
.c_str()),
267 v8::Boolean::New(isolate(), success
),
268 converter
->ToV8Value(&response
,
269 v8::Local
<v8::Context
>::New(isolate(), v8_context_
)),
270 v8::String::NewFromUtf8(isolate(), error
.c_str())};
272 v8::Handle
<v8::Value
> retval
= module_system()->CallModuleMethod(
273 "sendRequest", "handleResponse", arraysize(argv
), argv
);
275 // In debug, the js will validate the callback parameters and return a
276 // string if a validation error has occured.
277 DCHECK(retval
.IsEmpty() || retval
->IsUndefined())
278 << *v8::String::Utf8Value(retval
);
281 void ScriptContext::SetContentCapabilities(
282 const APIPermissionSet
& permissions
) {
283 content_capabilities_
= permissions
;
286 bool ScriptContext::HasAPIPermission(APIPermission::ID permission
) const {
287 if (effective_extension_
.get()) {
288 return effective_extension_
->permissions_data()->HasAPIPermission(
290 } else if (context_type() == Feature::WEB_PAGE_CONTEXT
) {
291 // Only web page contexts may be granted content capabilities. Other
292 // contexts are either privileged WebUI or extensions with their own set of
294 if (content_capabilities_
.find(permission
) != content_capabilities_
.end())
300 ScriptContext::Runner::Runner(ScriptContext
* context
) : context_(context
) {
302 void ScriptContext::Runner::Run(const std::string
& source
,
303 const std::string
& resource_name
) {
304 context_
->module_system()->RunString(source
, resource_name
);
307 v8::Handle
<v8::Value
> ScriptContext::Runner::Call(
308 v8::Handle
<v8::Function
> function
,
309 v8::Handle
<v8::Value
> receiver
,
311 v8::Handle
<v8::Value
> argv
[]) {
312 return context_
->CallFunction(function
, argc
, argv
);
315 gin::ContextHolder
* ScriptContext::Runner::GetContextHolder() {
316 v8::HandleScope
handle_scope(context_
->isolate());
317 return gin::PerContextData::From(context_
->v8_context())->context_holder();
320 } // namespace extensions