2 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "core/frame/LocalDOMWindow.h"
30 #include "bindings/core/v8/Dictionary.h"
31 #include "bindings/core/v8/ExceptionMessages.h"
32 #include "bindings/core/v8/ExceptionState.h"
33 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
34 #include "bindings/core/v8/ScriptCallStackFactory.h"
35 #include "bindings/core/v8/ScriptController.h"
36 #include "bindings/core/v8/SerializedScriptValue.h"
37 #include "bindings/core/v8/V8DOMActivityLogger.h"
38 #include "core/css/CSSComputedStyleDeclaration.h"
39 #include "core/css/CSSRuleList.h"
40 #include "core/css/DOMWindowCSS.h"
41 #include "core/css/MediaQueryList.h"
42 #include "core/css/MediaQueryMatcher.h"
43 #include "core/css/StyleMedia.h"
44 #include "core/css/resolver/StyleResolver.h"
45 #include "core/dom/ContextFeatures.h"
46 #include "core/dom/DOMImplementation.h"
47 #include "core/dom/Document.h"
48 #include "core/dom/Element.h"
49 #include "core/dom/ExceptionCode.h"
50 #include "core/dom/ExecutionContext.h"
51 #include "core/dom/RequestAnimationFrameCallback.h"
52 #include "core/editing/Editor.h"
53 #include "core/events/DOMWindowEventQueue.h"
54 #include "core/events/EventListener.h"
55 #include "core/events/HashChangeEvent.h"
56 #include "core/events/MessageEvent.h"
57 #include "core/events/PageTransitionEvent.h"
58 #include "core/events/PopStateEvent.h"
59 #include "core/frame/BarProp.h"
60 #include "core/frame/Console.h"
61 #include "core/frame/DOMWindowLifecycleNotifier.h"
62 #include "core/frame/EventHandlerRegistry.h"
63 #include "core/frame/FrameConsole.h"
64 #include "core/frame/FrameHost.h"
65 #include "core/frame/FrameView.h"
66 #include "core/frame/History.h"
67 #include "core/frame/LocalFrame.h"
68 #include "core/frame/Location.h"
69 #include "core/frame/Navigator.h"
70 #include "core/frame/Screen.h"
71 #include "core/frame/Settings.h"
72 #include "core/html/HTMLFrameOwnerElement.h"
73 #include "core/inspector/ConsoleMessage.h"
74 #include "core/inspector/InspectorInstrumentation.h"
75 #include "core/inspector/InspectorTraceEvents.h"
76 #include "core/inspector/ScriptCallStack.h"
77 #include "core/loader/DocumentLoader.h"
78 #include "core/loader/FrameLoadRequest.h"
79 #include "core/loader/FrameLoader.h"
80 #include "core/loader/FrameLoaderClient.h"
81 #include "core/loader/MixedContentChecker.h"
82 #include "core/loader/SinkDocument.h"
83 #include "core/loader/appcache/ApplicationCache.h"
84 #include "core/page/BackForwardClient.h"
85 #include "core/page/Chrome.h"
86 #include "core/page/ChromeClient.h"
87 #include "core/page/CreateWindow.h"
88 #include "core/page/EventHandler.h"
89 #include "core/page/FrameTree.h"
90 #include "core/page/Page.h"
91 #include "core/page/WindowFeatures.h"
92 #include "core/page/WindowFocusAllowedIndicator.h"
93 #include "core/page/scrolling/ScrollingCoordinator.h"
94 #include "core/storage/Storage.h"
95 #include "core/storage/StorageArea.h"
96 #include "core/storage/StorageNamespace.h"
97 #include "core/timing/Performance.h"
98 #include "platform/EventDispatchForbiddenScope.h"
99 #include "platform/PlatformScreen.h"
100 #include "platform/RuntimeEnabledFeatures.h"
101 #include "platform/UserGestureIndicator.h"
102 #include "platform/geometry/FloatRect.h"
103 #include "platform/graphics/media/MediaPlayer.h"
104 #include "platform/weborigin/KURL.h"
105 #include "platform/weborigin/SecurityOrigin.h"
106 #include "platform/weborigin/SecurityPolicy.h"
107 #include "public/platform/Platform.h"
108 #include "wtf/MainThread.h"
109 #include "wtf/MathExtras.h"
110 #include "wtf/text/WTFString.h"
118 class PostMessageTimer FINAL : public SuspendableTimer {
120 PostMessageTimer(LocalDOMWindow& window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtrWillBeRawPtr<LocalDOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace, UserGestureToken* userGestureToken)
121 : SuspendableTimer(window.document())
124 , m_origin(sourceOrigin)
126 , m_channels(channels)
127 , m_targetOrigin(targetOrigin)
128 , m_stackTrace(stackTrace)
129 , m_userGestureToken(userGestureToken)
131 m_asyncOperationId = InspectorInstrumentation::traceAsyncOperationStarting(executionContext(), "postMessage");
134 PassRefPtrWillBeRawPtr<MessageEvent> event()
136 return MessageEvent::create(m_channels.release(), m_message, m_origin, String(), m_source.get());
139 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
140 ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
141 UserGestureToken* userGestureToken() const { return m_userGestureToken.get(); }
144 virtual void fired() OVERRIDE
146 InspectorInstrumentationCookie cookie = InspectorInstrumentation::traceAsyncOperationCompletedCallbackStarting(executionContext(), m_asyncOperationId);
147 m_window->postMessageTimerFired(this);
148 // This object is deleted now.
149 InspectorInstrumentation::traceAsyncCallbackCompleted(cookie);
152 // FIXME: Oilpan: This raw pointer is safe because the PostMessageTimer is
153 // owned by the LocalDOMWindow. Ideally PostMessageTimer should be moved to
154 // the heap and use Member<LocalDOMWindow>.
155 LocalDOMWindow* m_window;
156 RefPtr<SerializedScriptValue> m_message;
158 RefPtrWillBePersistent<LocalDOMWindow> m_source;
159 OwnPtr<MessagePortChannelArray> m_channels;
160 RefPtr<SecurityOrigin> m_targetOrigin;
161 RefPtrWillBePersistent<ScriptCallStack> m_stackTrace;
162 RefPtr<UserGestureToken> m_userGestureToken;
163 int m_asyncOperationId;
166 static void disableSuddenTermination()
168 blink::Platform::current()->suddenTerminationChanged(false);
171 static void enableSuddenTermination()
173 blink::Platform::current()->suddenTerminationChanged(true);
176 typedef HashCountedSet<LocalDOMWindow*> DOMWindowSet;
178 static DOMWindowSet& windowsWithUnloadEventListeners()
180 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
181 return windowsWithUnloadEventListeners;
184 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
186 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
187 return windowsWithBeforeUnloadEventListeners;
190 static void addUnloadEventListener(LocalDOMWindow* domWindow)
192 DOMWindowSet& set = windowsWithUnloadEventListeners();
194 disableSuddenTermination();
198 static void removeUnloadEventListener(LocalDOMWindow* domWindow)
200 DOMWindowSet& set = windowsWithUnloadEventListeners();
201 DOMWindowSet::iterator it = set.find(domWindow);
206 enableSuddenTermination();
209 static void removeAllUnloadEventListeners(LocalDOMWindow* domWindow)
211 DOMWindowSet& set = windowsWithUnloadEventListeners();
212 DOMWindowSet::iterator it = set.find(domWindow);
217 enableSuddenTermination();
220 static void addBeforeUnloadEventListener(LocalDOMWindow* domWindow)
222 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
224 disableSuddenTermination();
228 static void removeBeforeUnloadEventListener(LocalDOMWindow* domWindow)
230 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
231 DOMWindowSet::iterator it = set.find(domWindow);
236 enableSuddenTermination();
239 static void removeAllBeforeUnloadEventListeners(LocalDOMWindow* domWindow)
241 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
242 DOMWindowSet::iterator it = set.find(domWindow);
247 enableSuddenTermination();
250 static bool allowsBeforeUnloadListeners(LocalDOMWindow* window)
252 ASSERT_ARG(window, window);
253 LocalFrame* frame = window->frame();
256 return frame->isMainFrame();
259 unsigned LocalDOMWindow::pendingUnloadEventListeners() const
261 return windowsWithUnloadEventListeners().count(const_cast<LocalDOMWindow*>(this));
265 // 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
266 // 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
267 // 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
268 // 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
269 // 5) Translate the window rect coordinates to be within the coordinate space of the screen.
270 FloatRect LocalDOMWindow::adjustWindowRect(LocalFrame& frame, const FloatRect& pendingChanges)
272 FrameHost* host = frame.host();
275 FloatRect screen = screenAvailableRect(frame.view());
276 FloatRect window = host->chrome().windowRect();
278 // Make sure we're in a valid state before adjusting dimensions.
279 ASSERT(std::isfinite(screen.x()));
280 ASSERT(std::isfinite(screen.y()));
281 ASSERT(std::isfinite(screen.width()));
282 ASSERT(std::isfinite(screen.height()));
283 ASSERT(std::isfinite(window.x()));
284 ASSERT(std::isfinite(window.y()));
285 ASSERT(std::isfinite(window.width()));
286 ASSERT(std::isfinite(window.height()));
288 // Update window values if new requested values are not NaN.
289 if (!std::isnan(pendingChanges.x()))
290 window.setX(pendingChanges.x());
291 if (!std::isnan(pendingChanges.y()))
292 window.setY(pendingChanges.y());
293 if (!std::isnan(pendingChanges.width()))
294 window.setWidth(pendingChanges.width());
295 if (!std::isnan(pendingChanges.height()))
296 window.setHeight(pendingChanges.height());
298 FloatSize minimumSize = host->chrome().client().minimumWindowSize();
299 // Let size 0 pass through, since that indicates default size, not minimum size.
301 window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
303 window.setHeight(min(max(minimumSize.height(), window.height()), screen.height()));
305 // Constrain the window position within the valid screen area.
306 window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
307 window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
312 bool LocalDOMWindow::allowPopUp(LocalFrame& firstFrame)
314 if (UserGestureIndicator::processingUserGesture())
317 Settings* settings = firstFrame.settings();
318 return settings && settings->javaScriptCanOpenWindowsAutomatically();
321 bool LocalDOMWindow::allowPopUp()
323 return m_frame && allowPopUp(*m_frame);
326 bool LocalDOMWindow::canShowModalDialogNow(const LocalFrame* frame)
330 FrameHost* host = frame->host();
333 return host->chrome().canRunModalNow();
336 LocalDOMWindow::LocalDOMWindow(LocalFrame& frame)
337 : FrameDestructionObserver(&frame)
338 , m_shouldPrintWhenFinishedLoading(false)
340 , m_hasBeenReset(false)
343 ScriptWrappable::init(this);
346 void LocalDOMWindow::clearDocument()
351 if (m_document->isActive()) {
352 // FIXME: We don't call willRemove here. Why is that OK?
353 // This detach() call is also mostly redundant. Most of the calls to
354 // this function come via DocumentLoader::createWriterFor, which
355 // always detaches the previous Document first. Only XSLTProcessor
356 // depends on this detach() call, so it seems like there's some room
358 m_document->detach();
361 // FIXME: This should be part of ActiveDOMObject shutdown
364 m_document->clearDOMWindow();
365 m_document = nullptr;
368 void LocalDOMWindow::clearEventQueue()
372 m_eventQueue->close();
373 m_eventQueue.clear();
376 void LocalDOMWindow::acceptLanguagesChanged()
379 m_navigator->setLanguagesChanged();
381 dispatchEvent(Event::create(EventTypeNames::languagechange));
384 PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
386 RefPtrWillBeRawPtr<Document> document = nullptr;
388 // This is a hack for XSLTProcessor. See XSLTProcessor::createDocumentFromSource().
389 document = Document::create(init);
391 document = DOMImplementation::createDocument(mimeType, init, init.frame() ? init.frame()->inViewSourceMode() : false);
392 if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
393 document = SinkDocument::create(init);
396 return document.release();
399 PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::installNewDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
401 ASSERT(init.frame() == m_frame);
405 m_document = createDocument(mimeType, init, forceXHTML);
406 m_eventQueue = DOMWindowEventQueue::create(m_document.get());
407 m_document->attach();
412 m_frame->script().updateDocument();
413 m_document->updateViewportDescription();
415 if (m_frame->page() && m_frame->view()) {
416 if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator()) {
417 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), HorizontalScrollbar);
418 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), VerticalScrollbar);
419 scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_frame->view());
423 m_frame->selection().updateSecureKeyboardEntryIfActive();
427 EventQueue* LocalDOMWindow::eventQueue() const
429 return m_eventQueue.get();
432 void LocalDOMWindow::enqueueWindowEvent(PassRefPtrWillBeRawPtr<Event> event)
436 event->setTarget(this);
437 m_eventQueue->enqueueEvent(event);
440 void LocalDOMWindow::enqueueDocumentEvent(PassRefPtrWillBeRawPtr<Event> event)
444 event->setTarget(m_document.get());
445 m_eventQueue->enqueueEvent(event);
448 void LocalDOMWindow::dispatchWindowLoadEvent()
450 ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());
454 void LocalDOMWindow::documentWasClosed()
456 dispatchWindowLoadEvent();
457 enqueuePageshowEvent(PageshowEventNotPersisted);
458 if (m_pendingStateObject)
459 enqueuePopstateEvent(m_pendingStateObject.release());
462 void LocalDOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
464 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
465 // As per spec pageshow must be triggered asynchronously.
466 // However to be compatible with other browsers blink fires pageshow synchronously.
467 dispatchEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), m_document.get());
470 void LocalDOMWindow::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
472 enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
475 void LocalDOMWindow::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
477 if (!ContextFeatures::pushStateEnabled(document()))
480 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
481 dispatchEvent(PopStateEvent::create(stateObject, &history()));
484 void LocalDOMWindow::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
489 // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
490 // defer firing of popstate until we're in the complete state.
491 if (document()->isLoadCompleted())
492 enqueuePopstateEvent(stateObject);
494 m_pendingStateObject = stateObject;
497 LocalDOMWindow::~LocalDOMWindow()
499 ASSERT(m_hasBeenReset);
503 // Oilpan: the frame host and document objects are
504 // also garbage collected; cannot notify these
505 // when removing event listeners.
506 removeAllEventListenersInternal(DoNotBroadcastListenerRemoval);
508 // Cleared when detaching document.
509 ASSERT(!m_eventQueue);
511 removeAllEventListenersInternal(DoBroadcastListenerRemoval);
513 ASSERT(m_document->isStopped());
518 const AtomicString& LocalDOMWindow::interfaceName() const
520 return EventTargetNames::LocalDOMWindow;
523 ExecutionContext* LocalDOMWindow::executionContext() const
525 return m_document.get();
528 LocalDOMWindow* LocalDOMWindow::toDOMWindow()
533 PassRefPtrWillBeRawPtr<MediaQueryList> LocalDOMWindow::matchMedia(const String& media)
535 return document() ? document()->mediaQueryMatcher().matchMedia(media) : nullptr;
538 Page* LocalDOMWindow::page()
540 return frame() ? frame()->page() : 0;
543 void LocalDOMWindow::frameDestroyed()
545 FrameDestructionObserver::frameDestroyed();
549 void LocalDOMWindow::willDetachFrameHost()
551 m_frame->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);
552 InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
555 void LocalDOMWindow::willDestroyDocumentInFrame()
557 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
558 // unregister themselves from the LocalDOMWindow as a result of the call to willDestroyGlobalObjectInFrame.
559 Vector<DOMWindowProperty*> properties;
560 copyToVector(m_properties, properties);
561 for (size_t i = 0; i < properties.size(); ++i)
562 properties[i]->willDestroyGlobalObjectInFrame();
565 void LocalDOMWindow::willDetachDocumentFromFrame()
567 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
568 // unregister themselves from the LocalDOMWindow as a result of the call to willDetachGlobalObjectFromFrame.
569 Vector<DOMWindowProperty*> properties;
570 copyToVector(m_properties, properties);
571 for (size_t i = 0; i < properties.size(); ++i)
572 properties[i]->willDetachGlobalObjectFromFrame();
575 void LocalDOMWindow::registerProperty(DOMWindowProperty* property)
577 m_properties.add(property);
580 void LocalDOMWindow::unregisterProperty(DOMWindowProperty* property)
582 m_properties.remove(property);
585 void LocalDOMWindow::reset()
587 willDestroyDocumentInFrame();
588 resetDOMWindowProperties();
591 void LocalDOMWindow::resetDOMWindowProperties()
593 m_properties.clear();
597 m_locationbar = nullptr;
599 m_personalbar = nullptr;
600 m_scrollbars = nullptr;
601 m_statusbar = nullptr;
604 m_navigator = nullptr;
605 m_performance = nullptr;
606 m_location = nullptr;
608 m_sessionStorage = nullptr;
609 m_localStorage = nullptr;
610 m_applicationCache = nullptr;
612 m_hasBeenReset = true;
616 bool LocalDOMWindow::isCurrentlyDisplayedInFrame() const
618 return m_frame && m_frame->domWindow() == this && m_frame->host();
621 int LocalDOMWindow::orientation() const
623 ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());
628 int orientation = screenOrientationAngle(m_frame->view());
629 // For backward compatibility, we want to return a value in the range of
630 // [-90; 180] instead of [0; 360[ because window.orientation used to behave
631 // like that in WebKit (this is a WebKit proprietary API).
632 if (orientation == 270)
637 Screen& LocalDOMWindow::screen() const
640 m_screen = Screen::create(m_frame);
644 History& LocalDOMWindow::history() const
647 m_history = History::create(m_frame);
651 BarProp& LocalDOMWindow::locationbar() const
654 m_locationbar = BarProp::create(m_frame, BarProp::Locationbar);
655 return *m_locationbar;
658 BarProp& LocalDOMWindow::menubar() const
661 m_menubar = BarProp::create(m_frame, BarProp::Menubar);
665 BarProp& LocalDOMWindow::personalbar() const
668 m_personalbar = BarProp::create(m_frame, BarProp::Personalbar);
669 return *m_personalbar;
672 BarProp& LocalDOMWindow::scrollbars() const
675 m_scrollbars = BarProp::create(m_frame, BarProp::Scrollbars);
676 return *m_scrollbars;
679 BarProp& LocalDOMWindow::statusbar() const
682 m_statusbar = BarProp::create(m_frame, BarProp::Statusbar);
686 BarProp& LocalDOMWindow::toolbar() const
689 m_toolbar = BarProp::create(m_frame, BarProp::Toolbar);
693 Console& LocalDOMWindow::console() const
696 m_console = Console::create(m_frame);
700 FrameConsole* LocalDOMWindow::frameConsole() const
702 if (!isCurrentlyDisplayedInFrame())
704 return &m_frame->console();
707 ApplicationCache* LocalDOMWindow::applicationCache() const
709 if (!isCurrentlyDisplayedInFrame())
711 if (!m_applicationCache)
712 m_applicationCache = ApplicationCache::create(m_frame);
713 return m_applicationCache.get();
716 Navigator& LocalDOMWindow::navigator() const
719 m_navigator = Navigator::create(m_frame);
723 Performance& LocalDOMWindow::performance() const
726 m_performance = Performance::create(m_frame);
727 return *m_performance;
730 Location& LocalDOMWindow::location() const
733 m_location = Location::create(m_frame);
737 Storage* LocalDOMWindow::sessionStorage(ExceptionState& exceptionState) const
739 if (!isCurrentlyDisplayedInFrame())
742 Document* document = this->document();
746 String accessDeniedMessage = "Access is denied for this document.";
747 if (!document->securityOrigin()->canAccessLocalStorage()) {
748 if (document->isSandboxed(SandboxOrigin))
749 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
750 else if (document->url().protocolIs("data"))
751 exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
753 exceptionState.throwSecurityError(accessDeniedMessage);
757 if (m_sessionStorage) {
758 if (!m_sessionStorage->area()->canAccessStorage(m_frame)) {
759 exceptionState.throwSecurityError(accessDeniedMessage);
762 return m_sessionStorage.get();
765 Page* page = document->page();
769 OwnPtrWillBeRawPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
770 if (!storageArea->canAccessStorage(m_frame)) {
771 exceptionState.throwSecurityError(accessDeniedMessage);
775 m_sessionStorage = Storage::create(m_frame, storageArea.release());
776 return m_sessionStorage.get();
779 Storage* LocalDOMWindow::localStorage(ExceptionState& exceptionState) const
781 if (!isCurrentlyDisplayedInFrame())
784 Document* document = this->document();
788 String accessDeniedMessage = "Access is denied for this document.";
789 if (!document->securityOrigin()->canAccessLocalStorage()) {
790 if (document->isSandboxed(SandboxOrigin))
791 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
792 else if (document->url().protocolIs("data"))
793 exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
795 exceptionState.throwSecurityError(accessDeniedMessage);
799 if (m_localStorage) {
800 if (!m_localStorage->area()->canAccessStorage(m_frame)) {
801 exceptionState.throwSecurityError(accessDeniedMessage);
804 return m_localStorage.get();
807 // FIXME: Seems this check should be much higher?
808 FrameHost* host = document->frameHost();
809 if (!host || !host->settings().localStorageEnabled())
812 OwnPtrWillBeRawPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
813 if (!storageArea->canAccessStorage(m_frame)) {
814 exceptionState.throwSecurityError(accessDeniedMessage);
818 m_localStorage = Storage::create(m_frame, storageArea.release());
819 return m_localStorage.get();
822 void LocalDOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, LocalDOMWindow* source, ExceptionState& exceptionState)
824 if (!isCurrentlyDisplayedInFrame())
827 Document* sourceDocument = source->document();
829 // Compute the target origin. We need to do this synchronously in order
830 // to generate the SyntaxError exception correctly.
831 RefPtr<SecurityOrigin> target;
832 if (targetOrigin == "/") {
835 target = sourceDocument->securityOrigin();
836 } else if (targetOrigin != "*") {
837 target = SecurityOrigin::createFromString(targetOrigin);
838 // It doesn't make sense target a postMessage at a unique origin
839 // because there's no way to represent a unique origin in a string.
840 if (target->isUnique()) {
841 exceptionState.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
846 OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
847 if (exceptionState.hadException())
850 // Capture the source of the message. We need to do this synchronously
851 // in order to capture the source of the message correctly.
854 String sourceOrigin = sourceDocument->securityOrigin()->toString();
856 if (MixedContentChecker::isMixedContent(sourceDocument->securityOrigin(), document()->url()))
857 UseCounter::count(document(), UseCounter::PostMessageFromSecureToInsecure);
858 else if (MixedContentChecker::isMixedContent(document()->securityOrigin(), sourceDocument->url()))
859 UseCounter::count(document(), UseCounter::PostMessageFromInsecureToSecure);
861 // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
862 RefPtrWillBeRawPtr<ScriptCallStack> stackTrace = nullptr;
863 if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
864 stackTrace = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture, true);
866 // Schedule the message.
867 OwnPtr<PostMessageTimer> timer = adoptPtr(new PostMessageTimer(*this, message, sourceOrigin, source, channels.release(), target.get(), stackTrace.release(), UserGestureIndicator::currentToken()));
868 timer->startOneShot(0, FROM_HERE);
869 timer->suspendIfNeeded();
870 m_postMessageTimers.add(timer.release());
873 void LocalDOMWindow::postMessageTimerFired(PostMessageTimer* timer)
875 if (!isCurrentlyDisplayedInFrame()) {
876 m_postMessageTimers.remove(timer);
880 RefPtrWillBeRawPtr<MessageEvent> event = timer->event();
882 // Give the embedder a chance to intercept this postMessage because this
883 // LocalDOMWindow might be a proxy for another in browsers that support
884 // postMessage calls across WebKit instances.
885 if (m_frame->loader().client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get())) {
886 m_postMessageTimers.remove(timer);
890 UserGestureIndicator gestureIndicator(timer->userGestureToken());
892 event->entangleMessagePorts(document());
893 dispatchMessageEventWithOriginCheck(timer->targetOrigin(), event, timer->stackTrace());
894 m_postMessageTimers.remove(timer);
897 void LocalDOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtrWillBeRawPtr<Event> event, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace)
899 if (intendedTargetOrigin) {
900 // Check target origin now since the target document may have changed since the timer was scheduled.
901 if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
902 String message = ExceptionMessages::failedToExecute("postMessage", "DOMWindow", "The target origin provided ('" + intendedTargetOrigin->toString() + "') does not match the recipient window's origin ('" + document()->securityOrigin()->toString() + "').");
903 RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message);
904 consoleMessage->setCallStack(stackTrace);
905 frameConsole()->addMessage(consoleMessage.release());
910 dispatchEvent(event);
913 DOMSelection* LocalDOMWindow::getSelection()
915 if (!isCurrentlyDisplayedInFrame() || !m_frame)
918 return m_frame->document()->getSelection();
921 Element* LocalDOMWindow::frameElement() const
926 // The bindings security check should ensure we're same origin...
927 ASSERT(!m_frame->owner() || m_frame->owner()->isLocal());
928 return m_frame->deprecatedLocalOwner();
931 void LocalDOMWindow::focus(ExecutionContext* context)
936 FrameHost* host = m_frame->host();
940 bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed();
942 ASSERT(isMainThread());
943 Document* activeDocument = toDocument(context);
944 if (opener() && opener() != this && activeDocument->domWindow() == opener())
948 // If we're a top level window, bring the window to the front.
949 if (m_frame->isMainFrame() && allowFocus)
950 host->chrome().focus();
955 m_frame->eventHandler().focusDocumentView();
958 void LocalDOMWindow::blur()
962 void LocalDOMWindow::close(ExecutionContext* context)
964 if (!m_frame || !m_frame->isMainFrame())
967 Page* page = m_frame->page();
972 ASSERT(isMainThread());
973 Document* activeDocument = toDocument(context);
977 if (!activeDocument->canNavigate(*m_frame))
981 Settings* settings = m_frame->settings();
982 bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
984 if (!(page->openedByDOM() || page->backForward().backForwardListCount() <= 1 || allowScriptsToCloseWindows)) {
985 frameConsole()->addMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, "Scripts may close only the windows that were opened by it."));
989 if (!m_frame->loader().shouldClose())
992 InspectorInstrumentation::willCloseWindow(context);
994 page->chrome().closeWindowSoon();
997 void LocalDOMWindow::print()
1002 FrameHost* host = m_frame->host();
1006 if (m_frame->loader().state() != FrameStateComplete) {
1007 m_shouldPrintWhenFinishedLoading = true;
1010 m_shouldPrintWhenFinishedLoading = false;
1011 host->chrome().print(m_frame);
1014 void LocalDOMWindow::stop()
1018 m_frame->loader().stopAllLoaders();
1021 void LocalDOMWindow::alert(const String& message)
1026 m_frame->document()->updateRenderTreeIfNeeded();
1028 FrameHost* host = m_frame->host();
1032 host->chrome().runJavaScriptAlert(m_frame, message);
1035 bool LocalDOMWindow::confirm(const String& message)
1040 m_frame->document()->updateRenderTreeIfNeeded();
1042 FrameHost* host = m_frame->host();
1046 return host->chrome().runJavaScriptConfirm(m_frame, message);
1049 String LocalDOMWindow::prompt(const String& message, const String& defaultValue)
1054 m_frame->document()->updateRenderTreeIfNeeded();
1056 FrameHost* host = m_frame->host();
1061 if (host->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
1067 bool LocalDOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1069 if (!isCurrentlyDisplayedInFrame())
1072 // |m_frame| can be destructed during |Editor::findString()| via
1073 // |Document::updateLayou()|, e.g. event handler removes a frame.
1074 RefPtr<LocalFrame> protectFrame(m_frame);
1076 // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1077 return m_frame->editor().findString(string, !backwards, caseSensitive, wrap, false);
1080 bool LocalDOMWindow::offscreenBuffering() const
1085 int LocalDOMWindow::outerHeight() const
1090 FrameHost* host = m_frame->host();
1094 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1095 return lroundf(host->chrome().windowRect().height() * host->deviceScaleFactor());
1096 return static_cast<int>(host->chrome().windowRect().height());
1099 int LocalDOMWindow::outerWidth() const
1104 FrameHost* host = m_frame->host();
1108 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1109 return lroundf(host->chrome().windowRect().width() * host->deviceScaleFactor());
1110 return static_cast<int>(host->chrome().windowRect().width());
1113 int LocalDOMWindow::innerHeight() const
1118 FrameView* view = m_frame->view();
1122 // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
1123 if (Frame* parent = m_frame->tree().parent()) {
1124 if (parent && parent->isLocalFrame())
1125 toLocalFrame(parent)->document()->updateLayoutIgnorePendingStylesheets();
1128 return adjustForAbsoluteZoom(view->visibleContentRect(IncludeScrollbars).height(), m_frame->pageZoomFactor());
1131 int LocalDOMWindow::innerWidth() const
1136 FrameView* view = m_frame->view();
1140 // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
1141 if (Frame* parent = m_frame->tree().parent()) {
1142 if (parent && parent->isLocalFrame())
1143 toLocalFrame(parent)->document()->updateLayoutIgnorePendingStylesheets();
1146 return adjustForAbsoluteZoom(view->visibleContentRect(IncludeScrollbars).width(), m_frame->pageZoomFactor());
1149 int LocalDOMWindow::screenX() const
1154 FrameHost* host = m_frame->host();
1158 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1159 return lroundf(host->chrome().windowRect().x() * host->deviceScaleFactor());
1160 return static_cast<int>(host->chrome().windowRect().x());
1163 int LocalDOMWindow::screenY() const
1168 FrameHost* host = m_frame->host();
1172 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1173 return lroundf(host->chrome().windowRect().y() * host->deviceScaleFactor());
1174 return static_cast<int>(host->chrome().windowRect().y());
1177 int LocalDOMWindow::scrollX() const
1182 FrameView* view = m_frame->view();
1186 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1188 return adjustForAbsoluteZoom(view->scrollX(), m_frame->pageZoomFactor());
1191 int LocalDOMWindow::scrollY() const
1196 FrameView* view = m_frame->view();
1200 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1202 return adjustForAbsoluteZoom(view->scrollY(), m_frame->pageZoomFactor());
1205 bool LocalDOMWindow::closed() const
1210 unsigned LocalDOMWindow::length() const
1212 if (!isCurrentlyDisplayedInFrame())
1215 return m_frame->tree().scopedChildCount();
1218 const AtomicString& LocalDOMWindow::name() const
1220 if (!isCurrentlyDisplayedInFrame())
1223 return m_frame->tree().name();
1226 void LocalDOMWindow::setName(const AtomicString& name)
1228 if (!isCurrentlyDisplayedInFrame())
1231 m_frame->tree().setName(name);
1232 ASSERT(m_frame->loader().client());
1233 m_frame->loader().client()->didChangeName(name);
1236 void LocalDOMWindow::setStatus(const String& string)
1243 FrameHost* host = m_frame->host();
1247 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1248 host->chrome().setStatusbarText(m_frame, m_status);
1251 void LocalDOMWindow::setDefaultStatus(const String& string)
1253 m_defaultStatus = string;
1258 FrameHost* host = m_frame->host();
1262 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1263 host->chrome().setStatusbarText(m_frame, m_defaultStatus);
1266 LocalDOMWindow* LocalDOMWindow::self() const
1271 return m_frame->domWindow();
1274 LocalDOMWindow* LocalDOMWindow::opener() const
1279 LocalFrame* opener = m_frame->loader().opener();
1283 return opener->domWindow();
1286 LocalDOMWindow* LocalDOMWindow::parent() const
1291 Frame* parent = m_frame->tree().parent();
1293 return parent->domWindow();
1295 return m_frame->domWindow();
1298 LocalDOMWindow* LocalDOMWindow::top() const
1303 return m_frame->tree().top()->domWindow();
1306 Document* LocalDOMWindow::document() const
1308 return m_document.get();
1311 StyleMedia& LocalDOMWindow::styleMedia() const
1314 m_media = StyleMedia::create(m_frame);
1318 PassRefPtrWillBeRawPtr<CSSStyleDeclaration> LocalDOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1323 return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
1326 PassRefPtrWillBeRawPtr<CSSRuleList> LocalDOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement) const
1331 if (!isCurrentlyDisplayedInFrame())
1334 unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
1335 CSSSelector::PseudoType pseudoType = CSSSelector::parsePseudoType(AtomicString(pseudoElement.substring(colonStart)));
1336 if (pseudoType == CSSSelector::PseudoUnknown && !pseudoElement.isEmpty())
1339 unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
1340 PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
1341 return m_frame->document()->ensureStyleResolver().pseudoCSSRulesForElement(element, pseudoId, rulesToInclude);
1344 double LocalDOMWindow::devicePixelRatio() const
1349 return m_frame->devicePixelRatio();
1352 static bool scrollBehaviorFromScrollOptions(const Dictionary& scrollOptions, ScrollBehavior& scrollBehavior, ExceptionState& exceptionState)
1354 String scrollBehaviorString;
1355 if (!DictionaryHelper::get(scrollOptions, "behavior", scrollBehaviorString)) {
1356 scrollBehavior = ScrollBehaviorAuto;
1360 if (ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior))
1363 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
1367 void LocalDOMWindow::scrollBy(int x, int y, ScrollBehavior scrollBehavior) const
1369 if (!isCurrentlyDisplayedInFrame())
1372 document()->updateLayoutIgnorePendingStylesheets();
1374 FrameView* view = m_frame->view();
1378 IntSize scaledOffset(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
1379 view->scrollBy(scaledOffset, scrollBehavior);
1382 void LocalDOMWindow::scrollBy(int x, int y, const Dictionary& scrollOptions, ExceptionState &exceptionState) const
1384 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
1385 if (!scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
1387 scrollBy(x, y, scrollBehavior);
1390 void LocalDOMWindow::scrollTo(int x, int y, ScrollBehavior scrollBehavior) const
1392 if (!isCurrentlyDisplayedInFrame())
1395 document()->updateLayoutIgnorePendingStylesheets();
1397 RefPtr<FrameView> view = m_frame->view();
1401 IntPoint layoutPos(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
1402 view->setScrollPosition(layoutPos, scrollBehavior);
1405 void LocalDOMWindow::scrollTo(int x, int y, const Dictionary& scrollOptions, ExceptionState& exceptionState) const
1407 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
1408 if (!scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
1410 scrollTo(x, y, scrollBehavior);
1413 void LocalDOMWindow::moveBy(float x, float y) const
1415 if (!m_frame || !m_frame->isMainFrame())
1418 FrameHost* host = m_frame->host();
1422 FloatRect windowRect = host->chrome().windowRect();
1423 windowRect.move(x, y);
1424 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1425 host->chrome().setWindowRect(adjustWindowRect(*m_frame, windowRect));
1428 void LocalDOMWindow::moveTo(float x, float y) const
1430 if (!m_frame || !m_frame->isMainFrame())
1433 FrameHost* host = m_frame->host();
1437 FloatRect windowRect = host->chrome().windowRect();
1438 windowRect.setLocation(FloatPoint(x, y));
1439 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1440 host->chrome().setWindowRect(adjustWindowRect(*m_frame, windowRect));
1443 void LocalDOMWindow::resizeBy(float x, float y) const
1445 if (!m_frame || !m_frame->isMainFrame())
1448 FrameHost* host = m_frame->host();
1452 FloatRect fr = host->chrome().windowRect();
1453 FloatSize dest = fr.size() + FloatSize(x, y);
1454 FloatRect update(fr.location(), dest);
1455 host->chrome().setWindowRect(adjustWindowRect(*m_frame, update));
1458 void LocalDOMWindow::resizeTo(float width, float height) const
1460 if (!m_frame || !m_frame->isMainFrame())
1463 FrameHost* host = m_frame->host();
1467 FloatRect fr = host->chrome().windowRect();
1468 FloatSize dest = FloatSize(width, height);
1469 FloatRect update(fr.location(), dest);
1470 host->chrome().setWindowRect(adjustWindowRect(*m_frame, update));
1473 int LocalDOMWindow::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
1475 callback->m_useLegacyTimeBase = false;
1476 if (Document* d = document())
1477 return d->requestAnimationFrame(callback);
1481 int LocalDOMWindow::webkitRequestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
1483 callback->m_useLegacyTimeBase = true;
1484 if (Document* d = document())
1485 return d->requestAnimationFrame(callback);
1489 void LocalDOMWindow::cancelAnimationFrame(int id)
1491 if (Document* d = document())
1492 d->cancelAnimationFrame(id);
1495 DOMWindowCSS& LocalDOMWindow::css() const
1498 m_css = DOMWindowCSS::create();
1502 static void didAddStorageEventListener(LocalDOMWindow* window)
1504 // Creating these blink::Storage objects informs the system that we'd like to receive
1505 // notifications about storage events that might be triggered in other processes. Rather
1506 // than subscribe to these notifications explicitly, we subscribe to them implicitly to
1507 // simplify the work done by the system.
1508 window->localStorage(IGNORE_EXCEPTION);
1509 window->sessionStorage(IGNORE_EXCEPTION);
1512 bool LocalDOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1514 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1517 if (m_frame && m_frame->host())
1518 m_frame->host()->eventHandlerRegistry().didAddEventHandler(*this, eventType);
1520 if (Document* document = this->document()) {
1521 document->addListenerTypeIfNeeded(eventType);
1522 if (eventType == EventTypeNames::storage)
1523 didAddStorageEventListener(this);
1526 lifecycleNotifier().notifyAddEventListener(this, eventType);
1528 if (eventType == EventTypeNames::unload) {
1529 UseCounter::count(document(), UseCounter::DocumentUnloadRegistered);
1530 addUnloadEventListener(this);
1531 } else if (eventType == EventTypeNames::beforeunload) {
1532 UseCounter::count(document(), UseCounter::DocumentBeforeUnloadRegistered);
1533 if (allowsBeforeUnloadListeners(this)) {
1534 // This is confusingly named. It doesn't actually add the listener. It just increments a count
1535 // so that we know we have listeners registered for the purposes of determining if we can
1536 // fast terminate the renderer process.
1537 addBeforeUnloadEventListener(this);
1539 // Subframes return false from allowsBeforeUnloadListeners.
1540 UseCounter::count(document(), UseCounter::SubFrameBeforeUnloadRegistered);
1547 bool LocalDOMWindow::removeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1549 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1552 if (m_frame && m_frame->host())
1553 m_frame->host()->eventHandlerRegistry().didRemoveEventHandler(*this, eventType);
1555 lifecycleNotifier().notifyRemoveEventListener(this, eventType);
1557 if (eventType == EventTypeNames::unload) {
1558 removeUnloadEventListener(this);
1559 } else if (eventType == EventTypeNames::beforeunload && allowsBeforeUnloadListeners(this)) {
1560 removeBeforeUnloadEventListener(this);
1566 void LocalDOMWindow::dispatchLoadEvent()
1568 RefPtrWillBeRawPtr<Event> loadEvent(Event::create(EventTypeNames::load));
1569 if (m_frame && m_frame->loader().documentLoader() && !m_frame->loader().documentLoader()->timing()->loadEventStart()) {
1570 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1571 // the event, so protect it to prevent writing the end time into freed memory.
1572 RefPtr<DocumentLoader> documentLoader = m_frame->loader().documentLoader();
1573 DocumentLoadTiming* timing = documentLoader->timing();
1574 timing->markLoadEventStart();
1575 dispatchEvent(loadEvent, document());
1576 timing->markLoadEventEnd();
1578 dispatchEvent(loadEvent, document());
1580 // For load events, send a separate load event to the enclosing frame only.
1581 // This is a DOM extension and is independent of bubbling/capturing rules of
1583 FrameOwner* owner = m_frame ? m_frame->owner() : 0;
1585 owner->dispatchLoad();
1587 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkLoad", "data", InspectorMarkLoadEvent::data(frame()));
1588 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1589 InspectorInstrumentation::loadEventFired(frame());
1592 bool LocalDOMWindow::dispatchEvent(PassRefPtrWillBeRawPtr<Event> prpEvent, PassRefPtrWillBeRawPtr<EventTarget> prpTarget)
1594 ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());
1596 RefPtrWillBeRawPtr<EventTarget> protect(this);
1597 RefPtrWillBeRawPtr<Event> event = prpEvent;
1599 event->setTarget(prpTarget ? prpTarget : this);
1600 event->setCurrentTarget(this);
1601 event->setEventPhase(Event::AT_TARGET);
1603 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EventDispatch", "data", InspectorEventDispatchEvent::data(*event));
1604 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1605 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1607 bool result = fireEventListeners(event.get());
1609 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1614 void LocalDOMWindow::removeAllEventListenersInternal(BroadcastListenerRemoval mode)
1616 EventTarget::removeAllEventListeners();
1618 lifecycleNotifier().notifyRemoveAllEventListeners(this);
1620 if (mode == DoBroadcastListenerRemoval) {
1621 if (m_frame && m_frame->host())
1622 m_frame->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);
1625 removeAllUnloadEventListeners(this);
1626 removeAllBeforeUnloadEventListeners(this);
1629 void LocalDOMWindow::removeAllEventListeners()
1631 removeAllEventListenersInternal(DoBroadcastListenerRemoval);
1634 void LocalDOMWindow::finishedLoading()
1636 if (m_shouldPrintWhenFinishedLoading) {
1637 m_shouldPrintWhenFinishedLoading = false;
1642 void LocalDOMWindow::setLocation(const String& urlString, LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow, SetLocationLocking locking)
1644 if (!isCurrentlyDisplayedInFrame())
1647 Document* activeDocument = callingWindow->document();
1648 if (!activeDocument)
1652 if (!activeDocument->canNavigate(*m_frame))
1655 LocalFrame* firstFrame = enteredWindow->frame();
1659 KURL completedURL = firstFrame->document()->completeURL(urlString);
1660 if (completedURL.isNull())
1663 if (isInsecureScriptAccess(*callingWindow, completedURL))
1666 V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
1667 if (activityLogger) {
1668 Vector<String> argv;
1669 argv.append("LocalDOMWindow");
1671 argv.append(firstFrame->document()->url());
1672 argv.append(completedURL);
1673 activityLogger->logEvent("blinkSetAttribute", argv.size(), argv.data());
1676 // We want a new history item if we are processing a user gesture.
1677 m_frame->navigationScheduler().scheduleLocationChange(activeDocument,
1678 // FIXME: What if activeDocument()->frame() is 0?
1679 completedURL, Referrer(activeDocument->outgoingReferrer(), activeDocument->referrerPolicy()),
1680 locking != LockHistoryBasedOnGestureState);
1683 void LocalDOMWindow::printErrorMessage(const String& message)
1685 if (!isCurrentlyDisplayedInFrame())
1688 if (message.isEmpty())
1691 frameConsole()->addMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
1694 // FIXME: Once we're throwing exceptions for cross-origin access violations, we will always sanitize the target
1695 // frame details, so we can safely combine 'crossDomainAccessErrorMessage' with this method after considering
1696 // exactly which details may be exposed to JavaScript.
1698 // http://crbug.com/17325
1699 String LocalDOMWindow::sanitizedCrossDomainAccessErrorMessage(LocalDOMWindow* callingWindow)
1701 if (!callingWindow || !callingWindow->document())
1704 const KURL& callingWindowURL = callingWindow->document()->url();
1705 if (callingWindowURL.isNull())
1708 ASSERT(!callingWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
1710 SecurityOrigin* activeOrigin = callingWindow->document()->securityOrigin();
1711 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a cross-origin frame.";
1713 // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may safely be reported to JavaScript.
1718 String LocalDOMWindow::crossDomainAccessErrorMessage(LocalDOMWindow* callingWindow)
1720 if (!callingWindow || !callingWindow->document())
1723 const KURL& callingWindowURL = callingWindow->document()->url();
1724 if (callingWindowURL.isNull())
1727 ASSERT(!callingWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
1729 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1730 SecurityOrigin* activeOrigin = callingWindow->document()->securityOrigin();
1731 SecurityOrigin* targetOrigin = document()->securityOrigin();
1732 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
1734 // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
1735 KURL activeURL = callingWindow->document()->url();
1736 KURL targetURL = document()->url();
1737 if (document()->isSandboxed(SandboxOrigin) || callingWindow->document()->isSandboxed(SandboxOrigin)) {
1738 message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL)->toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL)->toString() + "\". ";
1739 if (document()->isSandboxed(SandboxOrigin) && callingWindow->document()->isSandboxed(SandboxOrigin))
1740 return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
1741 if (document()->isSandboxed(SandboxOrigin))
1742 return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
1743 return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
1746 // Protocol errors: Use the URL's protocol rather than the origin's protocol so that we get a useful message for non-heirarchal URLs like 'data:'.
1747 if (targetOrigin->protocol() != activeOrigin->protocol())
1748 return message + " The frame requesting access has a protocol of \"" + activeURL.protocol() + "\", the frame being accessed has a protocol of \"" + targetURL.protocol() + "\". Protocols must match.\n";
1750 // 'document.domain' errors.
1751 if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
1752 return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", the frame being accessed set it to \"" + targetOrigin->domain() + "\". Both must set \"document.domain\" to the same value to allow access.";
1753 if (activeOrigin->domainWasSetInDOM())
1754 return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", but the frame being accessed did not. Both must set \"document.domain\" to the same value to allow access.";
1755 if (targetOrigin->domainWasSetInDOM())
1756 return message + "The frame being accessed set \"document.domain\" to \"" + targetOrigin->domain() + "\", but the frame requesting access did not. Both must set \"document.domain\" to the same value to allow access.";
1759 return message + "Protocols, domains, and ports must match.";
1762 bool LocalDOMWindow::isInsecureScriptAccess(LocalDOMWindow& callingWindow, const String& urlString)
1764 if (!protocolIsJavaScript(urlString))
1767 // If this LocalDOMWindow isn't currently active in the LocalFrame, then there's no
1768 // way we should allow the access.
1769 // FIXME: Remove this check if we're able to disconnect LocalDOMWindow from
1770 // LocalFrame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
1771 if (isCurrentlyDisplayedInFrame()) {
1772 // FIXME: Is there some way to eliminate the need for a separate "callingWindow == this" check?
1773 if (&callingWindow == this)
1776 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1777 // Can we name the SecurityOrigin function better to make this more clear?
1778 if (callingWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()))
1782 printErrorMessage(crossDomainAccessErrorMessage(&callingWindow));
1786 PassRefPtrWillBeRawPtr<LocalDOMWindow> LocalDOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1787 LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow)
1789 if (!isCurrentlyDisplayedInFrame())
1791 Document* activeDocument = callingWindow->document();
1792 if (!activeDocument)
1794 LocalFrame* firstFrame = enteredWindow->frame();
1798 UseCounter::count(*activeDocument, UseCounter::DOMWindowOpen);
1799 if (!windowFeaturesString.isEmpty())
1800 UseCounter::count(*activeDocument, UseCounter::DOMWindowOpenFeatures);
1802 if (!enteredWindow->allowPopUp()) {
1803 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1804 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1805 if (frameName.isEmpty() || !m_frame->tree().find(frameName))
1809 // Get the target frame for the special cases of _top and _parent.
1810 // In those cases, we schedule a location change right now and return early.
1811 Frame* targetFrame = 0;
1812 if (frameName == "_top")
1813 targetFrame = m_frame->tree().top();
1814 else if (frameName == "_parent") {
1815 if (Frame* parent = m_frame->tree().parent())
1816 targetFrame = parent;
1818 targetFrame = m_frame;
1820 // FIXME: Navigating RemoteFrames is not yet supported.
1821 if (targetFrame && targetFrame->isLocalFrame()) {
1822 if (!activeDocument->canNavigate(*targetFrame))
1825 KURL completedURL = firstFrame->document()->completeURL(urlString);
1827 if (targetFrame->domWindow()->isInsecureScriptAccess(*callingWindow, completedURL))
1828 return targetFrame->domWindow();
1830 if (urlString.isEmpty())
1831 return targetFrame->domWindow();
1833 // For whatever reason, Firefox uses the first window rather than the active window to
1834 // determine the outgoing referrer. We replicate that behavior here.
1835 toLocalFrame(targetFrame)->navigationScheduler().scheduleLocationChange(
1838 Referrer(firstFrame->document()->outgoingReferrer(), firstFrame->document()->referrerPolicy()),
1840 return targetFrame->domWindow();
1843 WindowFeatures windowFeatures(windowFeaturesString);
1844 LocalFrame* result = createWindow(urlString, frameName, windowFeatures, *callingWindow, *firstFrame, *m_frame);
1845 return result ? result->domWindow() : 0;
1848 void LocalDOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1849 LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow, PrepareDialogFunction function, void* functionContext)
1851 if (!isCurrentlyDisplayedInFrame())
1853 LocalFrame* activeFrame = callingWindow->frame();
1856 LocalFrame* firstFrame = enteredWindow->frame();
1860 if (!canShowModalDialogNow(m_frame) || !enteredWindow->allowPopUp())
1863 UseCounter::countDeprecation(this, UseCounter::ShowModalDialog);
1865 WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view()));
1866 LocalFrame* dialogFrame = createWindow(urlString, emptyAtom, windowFeatures,
1867 *callingWindow, *firstFrame, *m_frame, function, functionContext);
1870 UserGestureIndicatorDisabler disabler;
1871 dialogFrame->host()->chrome().runModal();
1874 LocalDOMWindow* LocalDOMWindow::anonymousIndexedGetter(uint32_t index)
1876 LocalFrame* frame = this->frame();
1880 Frame* child = frame->tree().scopedChild(index);
1882 return child->domWindow();
1887 DOMWindowLifecycleNotifier& LocalDOMWindow::lifecycleNotifier()
1889 return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext<LocalDOMWindow>::lifecycleNotifier());
1892 PassOwnPtr<LifecycleNotifier<LocalDOMWindow> > LocalDOMWindow::createLifecycleNotifier()
1894 return DOMWindowLifecycleNotifier::create(this);
1897 void LocalDOMWindow::trace(Visitor* visitor)
1899 visitor->trace(m_document);
1900 visitor->trace(m_screen);
1901 visitor->trace(m_history);
1902 visitor->trace(m_locationbar);
1903 visitor->trace(m_menubar);
1904 visitor->trace(m_personalbar);
1905 visitor->trace(m_scrollbars);
1906 visitor->trace(m_statusbar);
1907 visitor->trace(m_toolbar);
1908 visitor->trace(m_console);
1909 visitor->trace(m_navigator);
1910 visitor->trace(m_location);
1911 visitor->trace(m_media);
1912 visitor->trace(m_sessionStorage);
1913 visitor->trace(m_localStorage);
1914 visitor->trace(m_applicationCache);
1915 visitor->trace(m_performance);
1916 visitor->trace(m_css);
1917 visitor->trace(m_eventQueue);
1918 WillBeHeapSupplementable<LocalDOMWindow>::trace(visitor);
1919 EventTargetWithInlineData::trace(visitor);
1920 LifecycleContext<LocalDOMWindow>::trace(visitor);
1923 } // namespace blink