2 * Copyright (C) 2009, 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "bindings/core/v8/V8Window.h"
34 #include "bindings/core/v8/BindingSecurity.h"
35 #include "bindings/core/v8/ExceptionMessages.h"
36 #include "bindings/core/v8/ExceptionState.h"
37 #include "bindings/core/v8/ScheduledAction.h"
38 #include "bindings/core/v8/ScriptController.h"
39 #include "bindings/core/v8/ScriptSourceCode.h"
40 #include "bindings/core/v8/SerializedScriptValue.h"
41 #include "bindings/core/v8/V8Binding.h"
42 #include "bindings/core/v8/V8EventListener.h"
43 #include "bindings/core/v8/V8EventListenerList.h"
44 #include "bindings/core/v8/V8GCForContextDispose.h"
45 #include "bindings/core/v8/V8HTMLCollection.h"
46 #include "bindings/core/v8/V8HiddenValue.h"
47 #include "bindings/core/v8/V8Node.h"
48 #include "core/dom/DOMArrayBuffer.h"
49 #include "core/dom/ExceptionCode.h"
50 #include "core/dom/MessagePort.h"
51 #include "core/frame/DOMTimer.h"
52 #include "core/frame/DOMWindowTimers.h"
53 #include "core/frame/FrameView.h"
54 #include "core/frame/LocalDOMWindow.h"
55 #include "core/frame/LocalFrame.h"
56 #include "core/frame/Settings.h"
57 #include "core/frame/UseCounter.h"
58 #include "core/frame/csp/ContentSecurityPolicy.h"
59 #include "core/html/HTMLCollection.h"
60 #include "core/html/HTMLDocument.h"
61 #include "core/inspector/ScriptCallStack.h"
62 #include "core/loader/FrameLoadRequest.h"
63 #include "core/loader/FrameLoader.h"
64 #include "core/storage/Storage.h"
65 #include "platform/PlatformScreen.h"
66 #include "platform/graphics/media/MediaPlayer.h"
67 #include "wtf/Assertions.h"
68 #include "wtf/OwnPtr.h"
72 // FIXME: There is a lot of duplication with SetTimeoutOrInterval() in V8WorkerGlobalScopeCustom.cpp.
73 // We should refactor this.
74 static void windowSetTimeoutImpl(const v8::FunctionCallbackInfo<v8::Value>& info, bool singleShot, ExceptionState& exceptionState)
76 int argumentCount = info.Length();
78 if (argumentCount < 1)
81 LocalDOMWindow* impl = V8Window::toImpl(info.Holder());
82 if (!impl->frame() || !impl->document()) {
83 exceptionState.throwDOMException(InvalidAccessError, "No script context is available in which to execute the script.");
86 ScriptState* scriptState = ScriptState::current(info.GetIsolate());
87 v8::Handle<v8::Value> function = info[0];
88 String functionString;
89 if (!function->IsFunction()) {
90 if (function->IsString()) {
91 functionString = toCoreString(function.As<v8::String>());
93 v8::Handle<v8::String> v8String = function->ToString();
95 // Bail out if string conversion failed.
96 if (v8String.IsEmpty())
99 functionString = toCoreString(v8String);
102 // Don't allow setting timeouts to run empty functions!
104 if (!functionString.length())
108 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState))
111 OwnPtr<ScheduledAction> action;
112 if (function->IsFunction()) {
113 int paramCount = argumentCount >= 2 ? argumentCount - 2 : 0;
114 OwnPtr<v8::Local<v8::Value>[]> params;
115 if (paramCount > 0) {
116 params = adoptArrayPtr(new v8::Local<v8::Value>[paramCount]);
117 for (int i = 0; i < paramCount; i++) {
118 // parameters must be globalized
119 params[i] = info[i+2];
123 // params is passed to action, and released in action's destructor
124 ASSERT(impl->frame());
125 action = adoptPtr(new ScheduledAction(scriptState, v8::Handle<v8::Function>::Cast(function), paramCount, params.get(), info.GetIsolate()));
127 if (impl->document() && !impl->document()->contentSecurityPolicy()->allowEval()) {
128 v8SetReturnValue(info, 0);
131 ASSERT(impl->frame());
132 action = adoptPtr(new ScheduledAction(scriptState, functionString, KURL(), info.GetIsolate()));
135 int32_t timeout = argumentCount >= 2 ? info[1]->Int32Value() : 0;
138 timerId = DOMWindowTimers::setTimeout(*impl, action.release(), timeout);
140 timerId = DOMWindowTimers::setInterval(*impl, action.release(), timeout);
142 // FIXME: Crude hack that attempts to pass idle time to V8. This should be
143 // done using the scheduler instead.
145 V8GCForContextDispose::instance().notifyIdle();
147 v8SetReturnValue(info, timerId);
150 void V8Window::eventAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
152 LocalFrame* frame = V8Window::toImpl(info.Holder())->frame();
153 ExceptionState exceptionState(ExceptionState::GetterContext, "event", "Window", info.Holder(), info.GetIsolate());
154 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), frame, exceptionState)) {
155 exceptionState.throwIfNeeded();
160 // This is a fast path to retrieve info.Holder()->CreationContext().
161 v8::Local<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(info.GetIsolate()));
162 if (context.IsEmpty())
165 v8::Handle<v8::Value> jsEvent = V8HiddenValue::getHiddenValue(info.GetIsolate(), context->Global(), V8HiddenValue::event(info.GetIsolate()));
166 if (jsEvent.IsEmpty())
168 v8SetReturnValue(info, jsEvent);
171 void V8Window::eventAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
173 LocalFrame* frame = V8Window::toImpl(info.Holder())->frame();
174 ExceptionState exceptionState(ExceptionState::SetterContext, "event", "Window", info.Holder(), info.GetIsolate());
175 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), frame, exceptionState)) {
176 exceptionState.throwIfNeeded();
181 // This is a fast path to retrieve info.Holder()->CreationContext().
182 v8::Local<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(info.GetIsolate()));
183 if (context.IsEmpty())
186 V8HiddenValue::setHiddenValue(info.GetIsolate(), context->Global(), V8HiddenValue::event(info.GetIsolate()), value);
189 void V8Window::frameElementAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
191 LocalDOMWindow* impl = V8Window::toImpl(info.Holder());
192 ExceptionState exceptionState(ExceptionState::GetterContext, "frame", "Window", info.Holder(), info.GetIsolate());
193 if (!BindingSecurity::shouldAllowAccessToNode(info.GetIsolate(), impl->frameElement(), exceptionState)) {
194 v8SetReturnValueNull(info);
195 exceptionState.throwIfNeeded();
199 // The wrapper for an <iframe> should get its prototype from the context of the frame it's in, rather than its own frame.
200 // So, use its containing document as the creation context when wrapping.
201 v8::Handle<v8::Value> creationContext = toV8(&impl->frameElement()->document(), info.Holder(), info.GetIsolate());
202 RELEASE_ASSERT(!creationContext.IsEmpty());
203 v8::Handle<v8::Value> wrapper = toV8(impl->frameElement(), v8::Handle<v8::Object>::Cast(creationContext), info.GetIsolate());
204 v8SetReturnValue(info, wrapper);
207 void V8Window::openerAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
209 LocalDOMWindow* impl = V8Window::toImpl(info.Holder());
210 ExceptionState exceptionState(ExceptionState::SetterContext, "opener", "Window", info.Holder(), info.GetIsolate());
211 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) {
212 exceptionState.throwIfNeeded();
216 // Opener can be shadowed if it is in the same domain.
217 // Have a special handling of null value to behave
218 // like Firefox. See bug http://b/1224887 & http://b/791706.
219 if (value->IsNull()) {
220 // impl->frame() cannot be null,
221 // otherwise, SameOrigin check would have failed.
222 ASSERT(impl->frame());
223 impl->frame()->loader().setOpener(0);
226 // Delete the accessor from this object.
227 info.Holder()->Delete(v8AtomicString(info.GetIsolate(), "opener"));
229 // Put property on the front (this) object.
230 if (info.This()->IsObject())
231 v8::Handle<v8::Object>::Cast(info.This())->Set(v8AtomicString(info.GetIsolate(), "opener"), value);
234 static bool isLegacyTargetOriginDesignation(v8::Handle<v8::Value> value)
236 if (value->IsString() || value->IsStringObject())
242 void V8Window::postMessageMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
244 // None of these need to be RefPtr because info and context are guaranteed
245 // to hold on to them.
246 LocalDOMWindow* window = V8Window::toImpl(info.Holder());
247 LocalDOMWindow* source = callingDOMWindow(info.GetIsolate());
250 UseCounter::countIfNotPrivateScript(info.GetIsolate(), window->document(), UseCounter::WindowPostMessage);
252 ExceptionState exceptionState(ExceptionState::ExecutionContext, "postMessage", "Window", info.Holder(), info.GetIsolate());
254 // If called directly by WebCore we don't have a calling context.
256 exceptionState.throwTypeError("No active calling context exists.");
257 exceptionState.throwIfNeeded();
261 // This function has variable arguments and can be:
263 // postMessage(message, targetOrigin)
264 // postMessage(message, targetOrigin, {sequence of transferrables})
265 // Legacy non-standard implementations in webkit allowed:
266 // postMessage(message, {sequence of transferrables}, targetOrigin);
267 MessagePortArray portArray;
268 ArrayBufferArray arrayBufferArray;
269 int targetOriginArgIndex = 1;
270 if (info.Length() > 2) {
271 int transferablesArgIndex = 2;
272 if (isLegacyTargetOriginDesignation(info[2])) {
273 UseCounter::countIfNotPrivateScript(info.GetIsolate(), window->document(), UseCounter::WindowPostMessageWithLegacyTargetOriginArgument);
274 targetOriginArgIndex = 2;
275 transferablesArgIndex = 1;
277 if (!SerializedScriptValue::extractTransferables(info.GetIsolate(), info[transferablesArgIndex], transferablesArgIndex, portArray, arrayBufferArray, exceptionState)) {
278 exceptionState.throwIfNeeded();
282 TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, targetOrigin, info[targetOriginArgIndex]);
284 RefPtr<SerializedScriptValue> message = SerializedScriptValue::create(info[0], &portArray, &arrayBufferArray, exceptionState, info.GetIsolate());
285 if (exceptionState.throwIfNeeded())
288 window->postMessage(message.release(), &portArray, targetOrigin, source, exceptionState);
289 exceptionState.throwIfNeeded();
292 // FIXME(fqian): returning string is cheating, and we should
293 // fix this by calling toString function on the receiver.
294 // However, V8 implements toString in JavaScript, which requires
295 // switching context of receiver. I consider it is dangerous.
296 void V8Window::toStringMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
298 v8::Handle<v8::Object> domWrapper = V8Window::findInstanceInPrototypeChain(info.This(), info.GetIsolate());
299 if (domWrapper.IsEmpty()) {
300 v8SetReturnValue(info, info.This()->ObjectProtoToString());
303 v8SetReturnValue(info, domWrapper->ObjectProtoToString());
306 class DialogHandler {
308 explicit DialogHandler(v8::Handle<v8::Value> dialogArguments, ScriptState* scriptState)
309 : m_scriptState(scriptState)
310 , m_dialogArguments(dialogArguments)
314 void dialogCreated(LocalDOMWindow*);
315 v8::Handle<v8::Value> returnValue() const;
318 RefPtr<ScriptState> m_scriptState;
319 RefPtr<ScriptState> m_scriptStateForDialogFrame;
320 v8::Handle<v8::Value> m_dialogArguments;
323 void DialogHandler::dialogCreated(LocalDOMWindow* dialogFrame)
325 if (m_dialogArguments.IsEmpty())
327 v8::Handle<v8::Context> context = toV8Context(dialogFrame->frame(), m_scriptState->world());
328 if (context.IsEmpty())
330 m_scriptStateForDialogFrame = ScriptState::from(context);
332 ScriptState::Scope scope(m_scriptStateForDialogFrame.get());
333 m_scriptStateForDialogFrame->context()->Global()->Set(v8AtomicString(m_scriptState->isolate(), "dialogArguments"), m_dialogArguments);
336 v8::Handle<v8::Value> DialogHandler::returnValue() const
338 if (!m_scriptStateForDialogFrame)
339 return v8Undefined();
340 ASSERT(m_scriptStateForDialogFrame->contextIsValid());
342 v8::Isolate* isolate = m_scriptStateForDialogFrame->isolate();
343 v8::EscapableHandleScope handleScope(isolate);
344 ScriptState::Scope scope(m_scriptStateForDialogFrame.get());
345 v8::Local<v8::Value> returnValue = m_scriptStateForDialogFrame->context()->Global()->Get(v8AtomicString(isolate, "returnValue"));
346 if (returnValue.IsEmpty())
347 return v8Undefined();
348 return handleScope.Escape(returnValue);
351 static void setUpDialog(LocalDOMWindow* dialog, void* handler)
353 static_cast<DialogHandler*>(handler)->dialogCreated(dialog);
356 void V8Window::showModalDialogMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
358 LocalDOMWindow* impl = V8Window::toImpl(info.Holder());
359 ExceptionState exceptionState(ExceptionState::ExecutionContext, "showModalDialog", "Window", info.Holder(), info.GetIsolate());
360 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) {
361 exceptionState.throwIfNeeded();
365 TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, urlString, info[0]);
366 DialogHandler handler(info[1], ScriptState::current(info.GetIsolate()));
367 TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, dialogFeaturesString, info[2]);
369 impl->showModalDialog(urlString, dialogFeaturesString, callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), setUpDialog, &handler);
371 v8SetReturnValue(info, handler.returnValue());
374 void V8Window::openMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
376 LocalDOMWindow* impl = V8Window::toImpl(info.Holder());
377 ExceptionState exceptionState(ExceptionState::ExecutionContext, "open", "Window", info.Holder(), info.GetIsolate());
378 if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) {
379 exceptionState.throwIfNeeded();
383 TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, urlString, info[0]);
384 AtomicString frameName;
385 if (info[1]->IsUndefined() || info[1]->IsNull()) {
386 frameName = "_blank";
388 TOSTRING_VOID(V8StringResource<>, frameNameResource, info[1]);
389 frameName = frameNameResource;
391 TOSTRING_VOID(V8StringResource<TreatNullAndUndefinedAsNullString>, windowFeaturesString, info[2]);
393 RefPtrWillBeRawPtr<LocalDOMWindow> openedWindow = impl->open(urlString, frameName, windowFeaturesString, callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()));
397 v8SetReturnValueFast(info, openedWindow.release(), impl);
400 void V8Window::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
403 LocalDOMWindow* window = V8Window::toImpl(info.Holder());
407 LocalFrame* frame = window->frame();
408 // window is detached from a frame.
412 // Search sub-frames.
413 AtomicString propName = toCoreAtomicString(name);
414 Frame* child = frame->tree().scopedChild(propName);
416 v8SetReturnValueFast(info, child->domWindow(), window);
420 // Search IDL functions defined in the prototype
421 if (!info.Holder()->GetRealNamedProperty(name).IsEmpty())
424 // Search named items in the document.
425 Document* doc = frame->document();
427 if (doc && doc->isHTMLDocument()) {
428 if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) {
429 RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName);
430 if (!items->isEmpty()) {
431 if (items->hasExactlyOneItem()) {
432 v8SetReturnValueFast(info, items->item(0), window);
435 v8SetReturnValueFast(info, items.release(), window);
443 void V8Window::setTimeoutMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
445 ExceptionState exceptionState(ExceptionState::ExecutionContext, "setTimeout", "Window", info.Holder(), info.GetIsolate());
446 windowSetTimeoutImpl(info, true, exceptionState);
447 exceptionState.throwIfNeeded();
451 void V8Window::setIntervalMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
453 ExceptionState exceptionState(ExceptionState::ExecutionContext, "setInterval", "Window", info.Holder(), info.GetIsolate());
454 windowSetTimeoutImpl(info, false, exceptionState);
455 exceptionState.throwIfNeeded();
458 bool V8Window::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>)
460 v8::Isolate* isolate = v8::Isolate::GetCurrent();
461 v8::Handle<v8::Object> window = V8Window::findInstanceInPrototypeChain(host, isolate);
462 if (window.IsEmpty())
463 return false; // the frame is gone.
465 LocalDOMWindow* targetWindow = V8Window::toImpl(window);
467 ASSERT(targetWindow);
469 LocalFrame* target = targetWindow->frame();
473 // Notify the loader's client if the initial document has been accessed.
474 if (target->loader().stateMachine()->isDisplayingInitialEmptyDocument())
475 target->loader().didAccessInitialDocument();
477 if (key->IsString()) {
478 DEFINE_STATIC_LOCAL(const AtomicString, nameOfProtoProperty, ("__proto__", AtomicString::ConstructFromLiteral));
480 AtomicString name = toCoreAtomicString(key.As<v8::String>());
481 Frame* childFrame = target->tree().scopedChild(name);
482 // Notice that we can't call HasRealNamedProperty for ACCESS_HAS
483 // because that would generate infinite recursion.
484 if (type == v8::ACCESS_HAS && childFrame)
486 // We need to explicitly compare against nameOfProtoProperty because
487 // V8's JSObject::LocalLookup finds __proto__ before
488 // interceptors and even when __proto__ isn't a "real named property".
489 v8::Handle<v8::String> keyString = key.As<v8::String>();
490 if (type == v8::ACCESS_GET
492 && !host->HasRealNamedProperty(keyString)
493 && !window->HasRealNamedProperty(keyString)
494 && name != nameOfProtoProperty)
498 return BindingSecurity::shouldAllowAccessToFrame(isolate, target, DoNotReportSecurityError);
501 bool V8Window::indexedSecurityCheckCustom(v8::Local<v8::Object> host, uint32_t index, v8::AccessType type, v8::Local<v8::Value>)
503 v8::Isolate* isolate = v8::Isolate::GetCurrent();
504 v8::Handle<v8::Object> window = V8Window::findInstanceInPrototypeChain(host, isolate);
505 if (window.IsEmpty())
508 LocalDOMWindow* targetWindow = V8Window::toImpl(window);
510 ASSERT(targetWindow);
512 LocalFrame* target = targetWindow->frame();
516 // Notify the loader's client if the initial document has been accessed.
517 if (target->loader().stateMachine()->isDisplayingInitialEmptyDocument())
518 target->loader().didAccessInitialDocument();
520 Frame* childFrame = target->tree().scopedChild(index);
522 // Notice that we can't call HasRealNamedProperty for ACCESS_HAS
523 // because that would generate infinite recursion.
524 if (type == v8::ACCESS_HAS && childFrame)
526 if (type == v8::ACCESS_GET
528 && !host->HasRealIndexedProperty(index)
529 && !window->HasRealIndexedProperty(index))
532 return BindingSecurity::shouldAllowAccessToFrame(isolate, target, DoNotReportSecurityError);
535 v8::Handle<v8::Value> toV8(LocalDOMWindow* window, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
537 // Notice that we explicitly ignore creationContext because the LocalDOMWindow is its own creationContext.
540 return v8::Null(isolate);
541 // Initializes environment of a frame, and return the global object
543 LocalFrame* frame = window->frame();
545 return v8Undefined();
547 v8::Handle<v8::Context> context = toV8Context(frame, DOMWrapperWorld::current(isolate));
548 if (context.IsEmpty())
549 return v8Undefined();
551 v8::Handle<v8::Object> global = context->Global();
552 ASSERT(!global.IsEmpty());