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/ScrollOptions.h"
72 #include "core/frame/Settings.h"
73 #include "core/html/HTMLFrameOwnerElement.h"
74 #include "core/inspector/ConsoleMessage.h"
75 #include "core/inspector/ConsoleMessageStorage.h"
76 #include "core/inspector/InspectorInstrumentation.h"
77 #include "core/inspector/InspectorTraceEvents.h"
78 #include "core/inspector/ScriptCallStack.h"
79 #include "core/loader/DocumentLoader.h"
80 #include "core/loader/FrameLoadRequest.h"
81 #include "core/loader/FrameLoader.h"
82 #include "core/loader/FrameLoaderClient.h"
83 #include "core/loader/MixedContentChecker.h"
84 #include "core/loader/SinkDocument.h"
85 #include "core/loader/appcache/ApplicationCache.h"
86 #include "core/page/Chrome.h"
87 #include "core/page/ChromeClient.h"
88 #include "core/page/CreateWindow.h"
89 #include "core/page/EventHandler.h"
90 #include "core/page/FrameTree.h"
91 #include "core/page/Page.h"
92 #include "core/page/WindowFeatures.h"
93 #include "core/page/WindowFocusAllowedIndicator.h"
94 #include "core/page/scrolling/ScrollingCoordinator.h"
95 #include "core/storage/Storage.h"
96 #include "core/storage/StorageArea.h"
97 #include "core/storage/StorageNamespace.h"
98 #include "core/timing/Performance.h"
99 #include "platform/EventDispatchForbiddenScope.h"
100 #include "platform/PlatformScreen.h"
101 #include "platform/RuntimeEnabledFeatures.h"
102 #include "platform/UserGestureIndicator.h"
103 #include "platform/geometry/FloatRect.h"
104 #include "platform/graphics/media/MediaPlayer.h"
105 #include "platform/weborigin/KURL.h"
106 #include "platform/weborigin/SecurityOrigin.h"
107 #include "platform/weborigin/SecurityPolicy.h"
108 #include "public/platform/Platform.h"
109 #include "wtf/MainThread.h"
110 #include "wtf/MathExtras.h"
111 #include "wtf/text/WTFString.h"
119 LocalDOMWindow::WindowFrameObserver::WindowFrameObserver(LocalDOMWindow* window, LocalFrame& frame)
120 : FrameDestructionObserver(&frame)
125 PassOwnPtrWillBeRawPtr<LocalDOMWindow::WindowFrameObserver> LocalDOMWindow::WindowFrameObserver::create(LocalDOMWindow* window, LocalFrame& frame)
127 return adoptPtrWillBeNoop(new WindowFrameObserver(window, frame));
131 LocalDOMWindow::WindowFrameObserver::~WindowFrameObserver()
136 void LocalDOMWindow::WindowFrameObserver::trace(Visitor* visitor)
138 visitor->trace(m_window);
139 FrameDestructionObserver::trace(visitor);
142 void LocalDOMWindow::WindowFrameObserver::willDetachFrameHost()
144 m_window->willDetachFrameHost();
147 class PostMessageTimer final : public SuspendableTimer {
149 PostMessageTimer(LocalDOMWindow& window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtrWillBeRawPtr<LocalDOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace, UserGestureToken* userGestureToken)
150 : SuspendableTimer(window.document())
153 , m_origin(sourceOrigin)
155 , m_channels(channels)
156 , m_targetOrigin(targetOrigin)
157 , m_stackTrace(stackTrace)
158 , m_userGestureToken(userGestureToken)
160 m_asyncOperationId = InspectorInstrumentation::traceAsyncOperationStarting(executionContext(), "postMessage");
163 PassRefPtrWillBeRawPtr<MessageEvent> event()
165 return MessageEvent::create(m_channels.release(), m_message, m_origin, String(), m_source.get());
168 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
169 ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
170 UserGestureToken* userGestureToken() const { return m_userGestureToken.get(); }
171 LocalDOMWindow* source() const { return m_source.get(); }
174 virtual void fired() override
176 InspectorInstrumentationCookie cookie = InspectorInstrumentation::traceAsyncOperationCompletedCallbackStarting(executionContext(), m_asyncOperationId);
177 m_window->postMessageTimerFired(this);
178 // This object is deleted now.
179 InspectorInstrumentation::traceAsyncCallbackCompleted(cookie);
182 // FIXME: Oilpan: This raw pointer is safe because the PostMessageTimer is
183 // owned by the LocalDOMWindow. Ideally PostMessageTimer should be moved to
184 // the heap and use Member<LocalDOMWindow>.
185 LocalDOMWindow* m_window;
186 RefPtr<SerializedScriptValue> m_message;
188 RefPtrWillBePersistent<LocalDOMWindow> m_source;
189 OwnPtr<MessagePortChannelArray> m_channels;
190 RefPtr<SecurityOrigin> m_targetOrigin;
191 RefPtrWillBePersistent<ScriptCallStack> m_stackTrace;
192 RefPtr<UserGestureToken> m_userGestureToken;
193 int m_asyncOperationId;
196 static void disableSuddenTermination()
198 blink::Platform::current()->suddenTerminationChanged(false);
201 static void enableSuddenTermination()
203 blink::Platform::current()->suddenTerminationChanged(true);
206 typedef HashCountedSet<LocalDOMWindow*> DOMWindowSet;
208 static DOMWindowSet& windowsWithUnloadEventListeners()
210 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
211 return windowsWithUnloadEventListeners;
214 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
216 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
217 return windowsWithBeforeUnloadEventListeners;
220 static void addUnloadEventListener(LocalDOMWindow* domWindow)
222 DOMWindowSet& set = windowsWithUnloadEventListeners();
224 disableSuddenTermination();
228 static void removeUnloadEventListener(LocalDOMWindow* domWindow)
230 DOMWindowSet& set = windowsWithUnloadEventListeners();
231 DOMWindowSet::iterator it = set.find(domWindow);
236 enableSuddenTermination();
239 static void removeAllUnloadEventListeners(LocalDOMWindow* domWindow)
241 DOMWindowSet& set = windowsWithUnloadEventListeners();
242 DOMWindowSet::iterator it = set.find(domWindow);
247 enableSuddenTermination();
250 static void addBeforeUnloadEventListener(LocalDOMWindow* domWindow)
252 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
254 disableSuddenTermination();
258 static void removeBeforeUnloadEventListener(LocalDOMWindow* domWindow)
260 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
261 DOMWindowSet::iterator it = set.find(domWindow);
266 enableSuddenTermination();
269 static void removeAllBeforeUnloadEventListeners(LocalDOMWindow* domWindow)
271 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
272 DOMWindowSet::iterator it = set.find(domWindow);
277 enableSuddenTermination();
280 static bool allowsBeforeUnloadListeners(LocalDOMWindow* window)
282 ASSERT_ARG(window, window);
283 LocalFrame* frame = window->frame();
286 return frame->isMainFrame();
289 unsigned LocalDOMWindow::pendingUnloadEventListeners() const
291 return windowsWithUnloadEventListeners().count(const_cast<LocalDOMWindow*>(this));
295 // 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
296 // 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
297 // 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
298 // 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
299 // 5) Translate the window rect coordinates to be within the coordinate space of the screen.
300 FloatRect LocalDOMWindow::adjustWindowRect(LocalFrame& frame, const FloatRect& pendingChanges)
302 FrameHost* host = frame.host();
305 FloatRect screen = screenAvailableRect(frame.view());
306 FloatRect window = host->chrome().windowRect();
308 // Make sure we're in a valid state before adjusting dimensions.
309 ASSERT(std::isfinite(screen.x()));
310 ASSERT(std::isfinite(screen.y()));
311 ASSERT(std::isfinite(screen.width()));
312 ASSERT(std::isfinite(screen.height()));
313 ASSERT(std::isfinite(window.x()));
314 ASSERT(std::isfinite(window.y()));
315 ASSERT(std::isfinite(window.width()));
316 ASSERT(std::isfinite(window.height()));
318 // Update window values if new requested values are not NaN.
319 if (!std::isnan(pendingChanges.x()))
320 window.setX(pendingChanges.x());
321 if (!std::isnan(pendingChanges.y()))
322 window.setY(pendingChanges.y());
323 if (!std::isnan(pendingChanges.width()))
324 window.setWidth(pendingChanges.width());
325 if (!std::isnan(pendingChanges.height()))
326 window.setHeight(pendingChanges.height());
328 FloatSize minimumSize = host->chrome().client().minimumWindowSize();
329 // Let size 0 pass through, since that indicates default size, not minimum size.
331 window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
333 window.setHeight(min(max(minimumSize.height(), window.height()), screen.height()));
335 // Constrain the window position within the valid screen area.
336 window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
337 window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
342 bool LocalDOMWindow::allowPopUp(LocalFrame& firstFrame)
344 if (UserGestureIndicator::processingUserGesture())
347 Settings* settings = firstFrame.settings();
348 return settings && settings->javaScriptCanOpenWindowsAutomatically();
351 bool LocalDOMWindow::allowPopUp()
353 return frame() && allowPopUp(*frame());
356 bool LocalDOMWindow::canShowModalDialogNow(const LocalFrame* frame)
360 FrameHost* host = frame->host();
363 return host->chrome().canRunModalNow();
366 LocalDOMWindow::LocalDOMWindow(LocalFrame& frame)
367 : m_frameObserver(WindowFrameObserver::create(this, frame))
368 , m_shouldPrintWhenFinishedLoading(false)
370 , m_hasBeenReset(false)
375 void LocalDOMWindow::clearDocument()
380 if (m_document->isActive()) {
381 // FIXME: We don't call willRemove here. Why is that OK?
382 // This detach() call is also mostly redundant. Most of the calls to
383 // this function come via DocumentLoader::createWriterFor, which
384 // always detaches the previous Document first. Only XSLTProcessor
385 // depends on this detach() call, so it seems like there's some room
387 m_document->detach();
390 // FIXME: This should be part of ActiveDOMObject shutdown
393 m_document->clearDOMWindow();
394 m_document = nullptr;
397 void LocalDOMWindow::clearEventQueue()
401 m_eventQueue->close();
402 m_eventQueue.clear();
405 void LocalDOMWindow::acceptLanguagesChanged()
408 m_navigator->setLanguagesChanged();
410 dispatchEvent(Event::create(EventTypeNames::languagechange));
413 PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
415 RefPtrWillBeRawPtr<Document> document = nullptr;
417 // This is a hack for XSLTProcessor. See XSLTProcessor::createDocumentFromSource().
418 document = Document::create(init);
420 document = DOMImplementation::createDocument(mimeType, init, init.frame() ? init.frame()->inViewSourceMode() : false);
421 if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
422 document = SinkDocument::create(init);
425 return document.release();
428 PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::installNewDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
430 ASSERT(init.frame() == frame());
434 m_document = createDocument(mimeType, init, forceXHTML);
435 m_eventQueue = DOMWindowEventQueue::create(m_document.get());
436 m_document->attach();
441 frame()->script().updateDocument();
442 m_document->updateViewportDescription();
444 if (frame()->page() && frame()->view()) {
445 if (ScrollingCoordinator* scrollingCoordinator = frame()->page()->scrollingCoordinator()) {
446 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frame()->view(), HorizontalScrollbar);
447 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frame()->view(), VerticalScrollbar);
448 scrollingCoordinator->scrollableAreaScrollLayerDidChange(frame()->view());
452 frame()->selection().updateSecureKeyboardEntryIfActive();
456 EventQueue* LocalDOMWindow::eventQueue() const
458 return m_eventQueue.get();
461 void LocalDOMWindow::enqueueWindowEvent(PassRefPtrWillBeRawPtr<Event> event)
465 event->setTarget(this);
466 m_eventQueue->enqueueEvent(event);
469 void LocalDOMWindow::enqueueDocumentEvent(PassRefPtrWillBeRawPtr<Event> event)
473 event->setTarget(m_document.get());
474 m_eventQueue->enqueueEvent(event);
477 void LocalDOMWindow::dispatchWindowLoadEvent()
479 ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());
483 void LocalDOMWindow::documentWasClosed()
485 dispatchWindowLoadEvent();
486 enqueuePageshowEvent(PageshowEventNotPersisted);
487 if (m_pendingStateObject)
488 enqueuePopstateEvent(m_pendingStateObject.release());
491 void LocalDOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
493 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
494 // As per spec pageshow must be triggered asynchronously.
495 // However to be compatible with other browsers blink fires pageshow synchronously.
496 dispatchEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), m_document.get());
499 void LocalDOMWindow::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
501 enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
504 void LocalDOMWindow::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
506 if (!ContextFeatures::pushStateEnabled(document()))
509 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
510 dispatchEvent(PopStateEvent::create(stateObject, history()));
513 void LocalDOMWindow::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
518 // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
519 // defer firing of popstate until we're in the complete state.
520 if (document()->isLoadCompleted())
521 enqueuePopstateEvent(stateObject);
523 m_pendingStateObject = stateObject;
526 LocalDOMWindow::~LocalDOMWindow()
529 // Oilpan: the frame host and document objects are
530 // also garbage collected; cannot notify these
531 // when removing event listeners.
532 removeAllEventListenersInternal(DoNotBroadcastListenerRemoval);
534 // Cleared when detaching document.
535 ASSERT(!m_eventQueue);
537 ASSERT(m_hasBeenReset);
540 removeAllEventListenersInternal(DoBroadcastListenerRemoval);
542 ASSERT(m_document->isStopped());
547 const AtomicString& LocalDOMWindow::interfaceName() const
549 return EventTargetNames::LocalDOMWindow;
552 ExecutionContext* LocalDOMWindow::executionContext() const
554 return m_document.get();
557 LocalDOMWindow* LocalDOMWindow::toDOMWindow()
562 PassRefPtrWillBeRawPtr<MediaQueryList> LocalDOMWindow::matchMedia(const String& media)
564 return document() ? document()->mediaQueryMatcher().matchMedia(media) : nullptr;
567 Page* LocalDOMWindow::page()
569 return frame() ? frame()->page() : 0;
572 void LocalDOMWindow::willDetachFrameHost()
574 frame()->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);
575 frame()->host()->consoleMessageStorage().frameWindowDiscarded(this);
576 InspectorInstrumentation::frameWindowDiscarded(frame(), this);
579 void LocalDOMWindow::willDestroyDocumentInFrame()
581 for (const auto& domWindowProperty : m_properties)
582 domWindowProperty->willDestroyGlobalObjectInFrame();
585 void LocalDOMWindow::willDetachDocumentFromFrame()
587 for (const auto& domWindowProperty : m_properties)
588 domWindowProperty->willDetachGlobalObjectFromFrame();
591 void LocalDOMWindow::registerProperty(DOMWindowProperty* property)
593 m_properties.add(property);
596 void LocalDOMWindow::unregisterProperty(DOMWindowProperty* property)
598 m_properties.remove(property);
601 void LocalDOMWindow::reset()
603 willDestroyDocumentInFrame();
604 m_properties.clear();
608 m_locationbar = nullptr;
610 m_personalbar = nullptr;
611 m_scrollbars = nullptr;
612 m_statusbar = nullptr;
615 m_navigator = nullptr;
616 m_performance = nullptr;
617 m_location = nullptr;
619 m_sessionStorage = nullptr;
620 m_localStorage = nullptr;
621 m_applicationCache = nullptr;
623 m_hasBeenReset = true;
627 bool LocalDOMWindow::isCurrentlyDisplayedInFrame() const
629 return frame() && frame()->domWindow() == this && frame()->host();
632 void LocalDOMWindow::sendOrientationChangeEvent()
634 ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());
636 // Before dispatching the event, build a list of the child frames to
637 // also send the event to, to mitigate side effects from event handlers
638 // potentially interfering with others.
639 WillBeHeapVector<RefPtrWillBeMember<Frame> > childFrames;
640 for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
641 childFrames.append(child);
644 dispatchEvent(Event::create(EventTypeNames::orientationchange));
646 for (size_t i = 0; i < childFrames.size(); ++i) {
647 if (childFrames[i]->domWindow())
648 childFrames[i]->domWindow()->sendOrientationChangeEvent();
652 int LocalDOMWindow::orientation() const
654 ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());
659 int orientation = screenOrientationAngle(frame()->view());
660 // For backward compatibility, we want to return a value in the range of
661 // [-90; 180] instead of [0; 360[ because window.orientation used to behave
662 // like that in WebKit (this is a WebKit proprietary API).
663 if (orientation == 270)
668 Screen* LocalDOMWindow::screen() const
671 m_screen = Screen::create(frame());
672 return m_screen.get();
675 History* LocalDOMWindow::history() const
678 m_history = History::create(frame());
679 return m_history.get();
682 BarProp* LocalDOMWindow::locationbar() const
685 m_locationbar = BarProp::create(frame(), BarProp::Locationbar);
686 return m_locationbar.get();
689 BarProp* LocalDOMWindow::menubar() const
692 m_menubar = BarProp::create(frame(), BarProp::Menubar);
693 return m_menubar.get();
696 BarProp* LocalDOMWindow::personalbar() const
699 m_personalbar = BarProp::create(frame(), BarProp::Personalbar);
700 return m_personalbar.get();
703 BarProp* LocalDOMWindow::scrollbars() const
706 m_scrollbars = BarProp::create(frame(), BarProp::Scrollbars);
707 return m_scrollbars.get();
710 BarProp* LocalDOMWindow::statusbar() const
713 m_statusbar = BarProp::create(frame(), BarProp::Statusbar);
714 return m_statusbar.get();
717 BarProp* LocalDOMWindow::toolbar() const
720 m_toolbar = BarProp::create(frame(), BarProp::Toolbar);
721 return m_toolbar.get();
724 Console* LocalDOMWindow::console() const
727 m_console = Console::create(frame());
728 return m_console.get();
731 FrameConsole* LocalDOMWindow::frameConsole() const
733 if (!isCurrentlyDisplayedInFrame())
735 return &frame()->console();
738 ApplicationCache* LocalDOMWindow::applicationCache() const
740 if (!isCurrentlyDisplayedInFrame())
742 if (!m_applicationCache)
743 m_applicationCache = ApplicationCache::create(frame());
744 return m_applicationCache.get();
747 Navigator* LocalDOMWindow::navigator() const
750 m_navigator = Navigator::create(frame());
751 return m_navigator.get();
754 Performance* LocalDOMWindow::performance() const
757 m_performance = Performance::create(frame());
758 return m_performance.get();
761 Location& LocalDOMWindow::location() const
764 m_location = Location::create(frame());
768 Storage* LocalDOMWindow::sessionStorage(ExceptionState& exceptionState) const
770 if (!isCurrentlyDisplayedInFrame())
773 Document* document = this->document();
777 String accessDeniedMessage = "Access is denied for this document.";
778 if (!document->securityOrigin()->canAccessLocalStorage()) {
779 if (document->isSandboxed(SandboxOrigin))
780 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
781 else if (document->url().protocolIs("data"))
782 exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
784 exceptionState.throwSecurityError(accessDeniedMessage);
788 if (m_sessionStorage) {
789 if (!m_sessionStorage->area()->canAccessStorage(frame())) {
790 exceptionState.throwSecurityError(accessDeniedMessage);
793 return m_sessionStorage.get();
796 Page* page = document->page();
800 OwnPtrWillBeRawPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
801 if (!storageArea->canAccessStorage(frame())) {
802 exceptionState.throwSecurityError(accessDeniedMessage);
806 m_sessionStorage = Storage::create(frame(), storageArea.release());
807 return m_sessionStorage.get();
810 Storage* LocalDOMWindow::localStorage(ExceptionState& exceptionState) const
812 if (!isCurrentlyDisplayedInFrame())
815 Document* document = this->document();
819 String accessDeniedMessage = "Access is denied for this document.";
820 if (!document->securityOrigin()->canAccessLocalStorage()) {
821 if (document->isSandboxed(SandboxOrigin))
822 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
823 else if (document->url().protocolIs("data"))
824 exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
826 exceptionState.throwSecurityError(accessDeniedMessage);
830 if (m_localStorage) {
831 if (!m_localStorage->area()->canAccessStorage(frame())) {
832 exceptionState.throwSecurityError(accessDeniedMessage);
835 return m_localStorage.get();
838 // FIXME: Seems this check should be much higher?
839 FrameHost* host = document->frameHost();
840 if (!host || !host->settings().localStorageEnabled())
843 OwnPtrWillBeRawPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
844 if (!storageArea->canAccessStorage(frame())) {
845 exceptionState.throwSecurityError(accessDeniedMessage);
849 m_localStorage = Storage::create(frame(), storageArea.release());
850 return m_localStorage.get();
853 void LocalDOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, LocalDOMWindow* source, ExceptionState& exceptionState)
855 if (!isCurrentlyDisplayedInFrame())
858 Document* sourceDocument = source->document();
860 // Compute the target origin. We need to do this synchronously in order
861 // to generate the SyntaxError exception correctly.
862 RefPtr<SecurityOrigin> target;
863 if (targetOrigin == "/") {
866 target = sourceDocument->securityOrigin();
867 } else if (targetOrigin != "*") {
868 target = SecurityOrigin::createFromString(targetOrigin);
869 // It doesn't make sense target a postMessage at a unique origin
870 // because there's no way to represent a unique origin in a string.
871 if (target->isUnique()) {
872 exceptionState.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
877 OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
878 if (exceptionState.hadException())
881 // Capture the source of the message. We need to do this synchronously
882 // in order to capture the source of the message correctly.
885 String sourceOrigin = sourceDocument->securityOrigin()->toString();
887 if (MixedContentChecker::isMixedContent(sourceDocument->securityOrigin(), document()->url()))
888 UseCounter::count(document(), UseCounter::PostMessageFromSecureToInsecure);
889 else if (MixedContentChecker::isMixedContent(document()->securityOrigin(), sourceDocument->url()))
890 UseCounter::count(document(), UseCounter::PostMessageFromInsecureToSecure);
892 // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
893 RefPtrWillBeRawPtr<ScriptCallStack> stackTrace = nullptr;
894 if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
895 stackTrace = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture, true);
897 // Schedule the message.
898 OwnPtr<PostMessageTimer> timer = adoptPtr(new PostMessageTimer(*this, message, sourceOrigin, source, channels.release(), target.get(), stackTrace.release(), UserGestureIndicator::currentToken()));
899 timer->startOneShot(0, FROM_HERE);
900 timer->suspendIfNeeded();
901 m_postMessageTimers.add(timer.release());
904 void LocalDOMWindow::postMessageTimerFired(PostMessageTimer* timer)
906 if (!isCurrentlyDisplayedInFrame()) {
907 m_postMessageTimers.remove(timer);
911 RefPtrWillBeRawPtr<MessageEvent> event = timer->event();
913 // Give the embedder a chance to intercept this postMessage because this
914 // LocalDOMWindow might be a proxy for another in browsers that support
915 // postMessage calls across WebKit instances.
916 LocalFrame* source = timer->source()->document() ? timer->source()->document()->frame() : 0;
917 if (frame()->client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get(), source)) {
918 m_postMessageTimers.remove(timer);
922 UserGestureIndicator gestureIndicator(timer->userGestureToken());
924 event->entangleMessagePorts(document());
925 dispatchMessageEventWithOriginCheck(timer->targetOrigin(), event, timer->stackTrace());
926 m_postMessageTimers.remove(timer);
929 void LocalDOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtrWillBeRawPtr<Event> event, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace)
931 if (intendedTargetOrigin) {
932 // Check target origin now since the target document may have changed since the timer was scheduled.
933 if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
934 String message = ExceptionMessages::failedToExecute("postMessage", "DOMWindow", "The target origin provided ('" + intendedTargetOrigin->toString() + "') does not match the recipient window's origin ('" + document()->securityOrigin()->toString() + "').");
935 RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message);
936 consoleMessage->setCallStack(stackTrace);
937 frameConsole()->addMessage(consoleMessage.release());
942 dispatchEvent(event);
945 DOMSelection* LocalDOMWindow::getSelection()
947 if (!isCurrentlyDisplayedInFrame())
950 return frame()->document()->getSelection();
953 Element* LocalDOMWindow::frameElement() const
958 // The bindings security check should ensure we're same origin...
959 ASSERT(!frame()->owner() || frame()->owner()->isLocal());
960 return frame()->deprecatedLocalOwner();
963 void LocalDOMWindow::focus(ExecutionContext* context)
968 FrameHost* host = frame()->host();
972 bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed();
974 ASSERT(isMainThread());
975 Document* activeDocument = toDocument(context);
976 if (opener() && opener() != this && activeDocument->domWindow() == opener())
980 // If we're a top level window, bring the window to the front.
981 if (frame()->isMainFrame() && allowFocus)
982 host->chrome().focus();
987 frame()->eventHandler().focusDocumentView();
990 void LocalDOMWindow::blur()
994 void LocalDOMWindow::close(ExecutionContext* context)
996 if (!frame() || !frame()->isMainFrame())
999 Page* page = frame()->page();
1004 ASSERT(isMainThread());
1005 Document* activeDocument = toDocument(context);
1006 if (!activeDocument)
1009 if (!activeDocument->canNavigate(*frame()))
1013 Settings* settings = frame()->settings();
1014 bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
1016 if (!page->openedByDOM() && frame()->loader().client()->backForwardLength() > 1 && !allowScriptsToCloseWindows) {
1017 frameConsole()->addMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, "Scripts may close only the windows that were opened by it."));
1021 if (!frame()->loader().shouldClose())
1024 InspectorInstrumentation::willCloseWindow(context);
1026 page->chrome().closeWindowSoon();
1029 void LocalDOMWindow::print()
1034 FrameHost* host = frame()->host();
1038 if (frame()->loader().state() != FrameStateComplete) {
1039 m_shouldPrintWhenFinishedLoading = true;
1042 m_shouldPrintWhenFinishedLoading = false;
1043 host->chrome().print(frame());
1046 void LocalDOMWindow::stop()
1050 frame()->loader().stopAllLoaders();
1053 void LocalDOMWindow::alert(const String& message)
1058 frame()->document()->updateRenderTreeIfNeeded();
1060 FrameHost* host = frame()->host();
1064 host->chrome().runJavaScriptAlert(frame(), message);
1067 bool LocalDOMWindow::confirm(const String& message)
1072 frame()->document()->updateRenderTreeIfNeeded();
1074 FrameHost* host = frame()->host();
1078 return host->chrome().runJavaScriptConfirm(frame(), message);
1081 String LocalDOMWindow::prompt(const String& message, const String& defaultValue)
1086 frame()->document()->updateRenderTreeIfNeeded();
1088 FrameHost* host = frame()->host();
1093 if (host->chrome().runJavaScriptPrompt(frame(), message, defaultValue, returnValue))
1099 bool LocalDOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1101 if (!isCurrentlyDisplayedInFrame())
1104 // |frame()| can be destructed during |Editor::findString()| via
1105 // |Document::updateLayout()|, e.g. event handler removes a frame.
1106 RefPtrWillBeRawPtr<LocalFrame> protectFrame(frame());
1108 // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1109 return frame()->editor().findString(string, !backwards, caseSensitive, wrap, false);
1112 bool LocalDOMWindow::offscreenBuffering() const
1117 int LocalDOMWindow::outerHeight() const
1122 FrameHost* host = frame()->host();
1126 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1127 return lroundf(host->chrome().windowRect().height() * host->deviceScaleFactor());
1128 return static_cast<int>(host->chrome().windowRect().height());
1131 int LocalDOMWindow::outerWidth() const
1136 FrameHost* host = frame()->host();
1140 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1141 return lroundf(host->chrome().windowRect().width() * host->deviceScaleFactor());
1142 return static_cast<int>(host->chrome().windowRect().width());
1145 int LocalDOMWindow::innerHeight() const
1150 FrameView* view = frame()->view();
1154 // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
1155 if (Frame* parent = frame()->tree().parent()) {
1156 if (parent && parent->isLocalFrame())
1157 toLocalFrame(parent)->document()->updateLayoutIgnorePendingStylesheets();
1160 return adjustForAbsoluteZoom(view->visibleContentRect(IncludeScrollbars).height(), frame()->pageZoomFactor());
1163 int LocalDOMWindow::innerWidth() const
1168 FrameView* view = frame()->view();
1172 // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
1173 if (Frame* parent = frame()->tree().parent()) {
1174 if (parent && parent->isLocalFrame())
1175 toLocalFrame(parent)->document()->updateLayoutIgnorePendingStylesheets();
1178 return adjustForAbsoluteZoom(view->visibleContentRect(IncludeScrollbars).width(), frame()->pageZoomFactor());
1181 int LocalDOMWindow::screenX() const
1186 FrameHost* host = frame()->host();
1190 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1191 return lroundf(host->chrome().windowRect().x() * host->deviceScaleFactor());
1192 return static_cast<int>(host->chrome().windowRect().x());
1195 int LocalDOMWindow::screenY() const
1200 FrameHost* host = frame()->host();
1204 if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
1205 return lroundf(host->chrome().windowRect().y() * host->deviceScaleFactor());
1206 return static_cast<int>(host->chrome().windowRect().y());
1209 double LocalDOMWindow::scrollX() const
1214 FrameView* view = frame()->view();
1218 frame()->document()->updateLayoutIgnorePendingStylesheets();
1220 return adjustScrollForAbsoluteZoom(view->scrollX(), frame()->pageZoomFactor());
1223 double LocalDOMWindow::scrollY() const
1228 FrameView* view = frame()->view();
1232 frame()->document()->updateLayoutIgnorePendingStylesheets();
1234 return adjustScrollForAbsoluteZoom(view->scrollY(), frame()->pageZoomFactor());
1237 bool LocalDOMWindow::closed() const
1239 return !frame() || !frame()->host();
1242 unsigned LocalDOMWindow::length() const
1244 if (!isCurrentlyDisplayedInFrame())
1247 return frame()->tree().scopedChildCount();
1250 const AtomicString& LocalDOMWindow::name() const
1252 if (!isCurrentlyDisplayedInFrame())
1255 return frame()->tree().name();
1258 void LocalDOMWindow::setName(const AtomicString& name)
1260 if (!isCurrentlyDisplayedInFrame())
1263 frame()->tree().setName(name);
1264 ASSERT(frame()->loader().client());
1265 frame()->loader().client()->didChangeName(name);
1268 void LocalDOMWindow::setStatus(const String& string)
1275 FrameHost* host = frame()->host();
1279 ASSERT(frame()->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1280 host->chrome().setStatusbarText(frame(), m_status);
1283 void LocalDOMWindow::setDefaultStatus(const String& string)
1285 m_defaultStatus = string;
1290 FrameHost* host = frame()->host();
1294 ASSERT(frame()->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1295 host->chrome().setStatusbarText(frame(), m_defaultStatus);
1298 LocalDOMWindow* LocalDOMWindow::self() const
1303 return frame()->domWindow();
1306 LocalDOMWindow* LocalDOMWindow::opener() const
1311 Frame* opener = frame()->loader().opener();
1315 return opener->domWindow();
1318 LocalDOMWindow* LocalDOMWindow::parent() const
1323 Frame* parent = frame()->tree().parent();
1325 return parent->domWindow();
1327 return frame()->domWindow();
1330 LocalDOMWindow* LocalDOMWindow::top() const
1335 return frame()->tree().top()->domWindow();
1338 Document* LocalDOMWindow::document() const
1340 return m_document.get();
1343 StyleMedia* LocalDOMWindow::styleMedia() const
1346 m_media = StyleMedia::create(frame());
1347 return m_media.get();
1350 PassRefPtrWillBeRawPtr<CSSStyleDeclaration> LocalDOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1355 return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
1358 PassRefPtrWillBeRawPtr<CSSRuleList> LocalDOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement) const
1363 if (!isCurrentlyDisplayedInFrame())
1366 unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
1367 CSSSelector::PseudoType pseudoType = CSSSelector::parsePseudoType(AtomicString(pseudoElement.substring(colonStart)), false);
1368 if (pseudoType == CSSSelector::PseudoUnknown && !pseudoElement.isEmpty())
1371 unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
1372 PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
1373 element->document().updateRenderTreeIfNeeded();
1374 return frame()->document()->ensureStyleResolver().pseudoCSSRulesForElement(element, pseudoId, rulesToInclude);
1377 double LocalDOMWindow::devicePixelRatio() const
1382 return frame()->devicePixelRatio();
1385 static bool scrollBehaviorFromScrollOptions(const ScrollOptions& scrollOptions, ScrollBehavior& scrollBehavior, ExceptionState& exceptionState)
1387 if (!scrollOptions.hasBehavior()) {
1388 scrollBehavior = ScrollBehaviorAuto;
1392 if (ScrollableArea::scrollBehaviorFromString(scrollOptions.behavior(), scrollBehavior))
1395 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
1399 void LocalDOMWindow::scrollBy(double x, double y, ScrollBehavior scrollBehavior) const
1401 if (!isCurrentlyDisplayedInFrame())
1404 document()->updateLayoutIgnorePendingStylesheets();
1406 FrameView* view = frame()->view();
1410 if (std::isnan(x) || std::isnan(y))
1413 DoubleSize scaledOffset(x * frame()->pageZoomFactor(), y * frame()->pageZoomFactor());
1414 view->scrollBy(scaledOffset, scrollBehavior);
1417 void LocalDOMWindow::scrollBy(double x, double y, const ScrollOptions& scrollOptions, ExceptionState &exceptionState) const
1419 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
1420 if (!scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
1422 scrollBy(x, y, scrollBehavior);
1425 void LocalDOMWindow::scrollTo(double x, double y, ScrollBehavior scrollBehavior) const
1427 if (!isCurrentlyDisplayedInFrame())
1430 document()->updateLayoutIgnorePendingStylesheets();
1432 RefPtrWillBeRawPtr<FrameView> view = frame()->view();
1436 if (std::isnan(x) || std::isnan(y))
1439 DoublePoint layoutPos(x * frame()->pageZoomFactor(), y * frame()->pageZoomFactor());
1440 view->setScrollPosition(layoutPos, scrollBehavior);
1443 void LocalDOMWindow::scrollTo(double x, double y, const ScrollOptions& scrollOptions, ExceptionState& exceptionState) const
1445 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
1446 if (!scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
1448 scrollTo(x, y, scrollBehavior);
1451 void LocalDOMWindow::moveBy(float x, float y) const
1453 if (!frame() || !frame()->isMainFrame())
1456 FrameHost* host = frame()->host();
1460 FloatRect windowRect = host->chrome().windowRect();
1461 windowRect.move(x, y);
1462 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1463 host->chrome().setWindowRect(adjustWindowRect(*frame(), windowRect));
1466 void LocalDOMWindow::moveTo(float x, float y) const
1468 if (!frame() || !frame()->isMainFrame())
1471 FrameHost* host = frame()->host();
1475 FloatRect windowRect = host->chrome().windowRect();
1476 windowRect.setLocation(FloatPoint(x, y));
1477 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1478 host->chrome().setWindowRect(adjustWindowRect(*frame(), windowRect));
1481 void LocalDOMWindow::resizeBy(float x, float y) const
1483 if (!frame() || !frame()->isMainFrame())
1486 FrameHost* host = frame()->host();
1490 FloatRect fr = host->chrome().windowRect();
1491 FloatSize dest = fr.size() + FloatSize(x, y);
1492 FloatRect update(fr.location(), dest);
1493 host->chrome().setWindowRect(adjustWindowRect(*frame(), update));
1496 void LocalDOMWindow::resizeTo(float width, float height) const
1498 if (!frame() || !frame()->isMainFrame())
1501 FrameHost* host = frame()->host();
1505 FloatRect fr = host->chrome().windowRect();
1506 FloatSize dest = FloatSize(width, height);
1507 FloatRect update(fr.location(), dest);
1508 host->chrome().setWindowRect(adjustWindowRect(*frame(), update));
1511 int LocalDOMWindow::requestAnimationFrame(RequestAnimationFrameCallback* callback)
1513 callback->m_useLegacyTimeBase = false;
1514 if (Document* d = document())
1515 return d->requestAnimationFrame(callback);
1519 int LocalDOMWindow::webkitRequestAnimationFrame(RequestAnimationFrameCallback* callback)
1521 callback->m_useLegacyTimeBase = true;
1522 if (Document* d = document())
1523 return d->requestAnimationFrame(callback);
1527 void LocalDOMWindow::cancelAnimationFrame(int id)
1529 if (Document* d = document())
1530 d->cancelAnimationFrame(id);
1533 DOMWindowCSS* LocalDOMWindow::css() const
1536 m_css = DOMWindowCSS::create();
1540 static void didAddStorageEventListener(LocalDOMWindow* window)
1542 // Creating these blink::Storage objects informs the system that we'd like to receive
1543 // notifications about storage events that might be triggered in other processes. Rather
1544 // than subscribe to these notifications explicitly, we subscribe to them implicitly to
1545 // simplify the work done by the system.
1546 window->localStorage(IGNORE_EXCEPTION);
1547 window->sessionStorage(IGNORE_EXCEPTION);
1550 bool LocalDOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1552 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1555 if (frame() && frame()->host())
1556 frame()->host()->eventHandlerRegistry().didAddEventHandler(*this, eventType);
1558 if (Document* document = this->document()) {
1559 document->addListenerTypeIfNeeded(eventType);
1560 if (eventType == EventTypeNames::storage)
1561 didAddStorageEventListener(this);
1564 lifecycleNotifier().notifyAddEventListener(this, eventType);
1566 if (eventType == EventTypeNames::unload) {
1567 UseCounter::count(document(), UseCounter::DocumentUnloadRegistered);
1568 addUnloadEventListener(this);
1569 } else if (eventType == EventTypeNames::beforeunload) {
1570 UseCounter::count(document(), UseCounter::DocumentBeforeUnloadRegistered);
1571 if (allowsBeforeUnloadListeners(this)) {
1572 // This is confusingly named. It doesn't actually add the listener. It just increments a count
1573 // so that we know we have listeners registered for the purposes of determining if we can
1574 // fast terminate the renderer process.
1575 addBeforeUnloadEventListener(this);
1577 // Subframes return false from allowsBeforeUnloadListeners.
1578 UseCounter::count(document(), UseCounter::SubFrameBeforeUnloadRegistered);
1585 bool LocalDOMWindow::removeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1587 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1590 if (frame() && frame()->host())
1591 frame()->host()->eventHandlerRegistry().didRemoveEventHandler(*this, eventType);
1593 lifecycleNotifier().notifyRemoveEventListener(this, eventType);
1595 if (eventType == EventTypeNames::unload) {
1596 removeUnloadEventListener(this);
1597 } else if (eventType == EventTypeNames::beforeunload && allowsBeforeUnloadListeners(this)) {
1598 removeBeforeUnloadEventListener(this);
1604 void LocalDOMWindow::dispatchLoadEvent()
1606 RefPtrWillBeRawPtr<Event> loadEvent(Event::create(EventTypeNames::load));
1607 if (frame() && frame()->loader().documentLoader() && !frame()->loader().documentLoader()->timing()->loadEventStart()) {
1608 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1609 // the event, so protect it to prevent writing the end time into freed memory.
1610 RefPtr<DocumentLoader> documentLoader = frame()->loader().documentLoader();
1611 DocumentLoadTiming* timing = documentLoader->timing();
1612 timing->markLoadEventStart();
1613 dispatchEvent(loadEvent, document());
1614 timing->markLoadEventEnd();
1616 dispatchEvent(loadEvent, document());
1618 // For load events, send a separate load event to the enclosing frame only.
1619 // This is a DOM extension and is independent of bubbling/capturing rules of
1621 FrameOwner* owner = frame() ? frame()->owner() : 0;
1623 owner->dispatchLoad();
1625 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkLoad", "data", InspectorMarkLoadEvent::data(frame()));
1626 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1627 InspectorInstrumentation::loadEventFired(frame());
1630 bool LocalDOMWindow::dispatchEvent(PassRefPtrWillBeRawPtr<Event> prpEvent, PassRefPtrWillBeRawPtr<EventTarget> prpTarget)
1632 ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());
1634 RefPtrWillBeRawPtr<EventTarget> protect(this);
1635 RefPtrWillBeRawPtr<Event> event = prpEvent;
1637 event->setTarget(prpTarget ? prpTarget : this);
1638 event->setCurrentTarget(this);
1639 event->setEventPhase(Event::AT_TARGET);
1641 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EventDispatch", "data", InspectorEventDispatchEvent::data(*event));
1642 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1643 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1645 bool result = fireEventListeners(event.get());
1647 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1652 void LocalDOMWindow::removeAllEventListenersInternal(BroadcastListenerRemoval mode)
1654 EventTarget::removeAllEventListeners();
1656 lifecycleNotifier().notifyRemoveAllEventListeners(this);
1658 if (mode == DoBroadcastListenerRemoval) {
1659 if (frame() && frame()->host())
1660 frame()->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);
1663 removeAllUnloadEventListeners(this);
1664 removeAllBeforeUnloadEventListeners(this);
1667 void LocalDOMWindow::removeAllEventListeners()
1669 removeAllEventListenersInternal(DoBroadcastListenerRemoval);
1672 void LocalDOMWindow::finishedLoading()
1674 if (m_shouldPrintWhenFinishedLoading) {
1675 m_shouldPrintWhenFinishedLoading = false;
1680 void LocalDOMWindow::setLocation(const String& urlString, LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow, SetLocationLocking locking)
1682 if (!isCurrentlyDisplayedInFrame())
1685 Document* activeDocument = callingWindow->document();
1686 if (!activeDocument)
1690 if (!activeDocument->canNavigate(*frame()))
1693 LocalFrame* firstFrame = enteredWindow->frame();
1697 KURL completedURL = firstFrame->document()->completeURL(urlString);
1698 if (completedURL.isNull())
1701 if (isInsecureScriptAccess(*callingWindow, completedURL))
1704 V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
1705 if (activityLogger) {
1706 Vector<String> argv;
1707 argv.append("LocalDOMWindow");
1709 argv.append(firstFrame->document()->url());
1710 argv.append(completedURL);
1711 activityLogger->logEvent("blinkSetAttribute", argv.size(), argv.data());
1714 // We want a new history item if we are processing a user gesture.
1715 frame()->navigationScheduler().scheduleLocationChange(activeDocument, completedURL, locking != LockHistoryBasedOnGestureState);
1718 void LocalDOMWindow::printErrorMessage(const String& message)
1720 if (!isCurrentlyDisplayedInFrame())
1723 if (message.isEmpty())
1726 frameConsole()->addMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
1729 // FIXME: Once we're throwing exceptions for cross-origin access violations, we will always sanitize the target
1730 // frame details, so we can safely combine 'crossDomainAccessErrorMessage' with this method after considering
1731 // exactly which details may be exposed to JavaScript.
1733 // http://crbug.com/17325
1734 String LocalDOMWindow::sanitizedCrossDomainAccessErrorMessage(LocalDOMWindow* callingWindow)
1736 if (!callingWindow || !callingWindow->document())
1739 const KURL& callingWindowURL = callingWindow->document()->url();
1740 if (callingWindowURL.isNull())
1743 ASSERT(!callingWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
1745 SecurityOrigin* activeOrigin = callingWindow->document()->securityOrigin();
1746 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a cross-origin frame.";
1748 // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may safely be reported to JavaScript.
1753 String LocalDOMWindow::crossDomainAccessErrorMessage(LocalDOMWindow* callingWindow)
1755 if (!callingWindow || !callingWindow->document())
1758 const KURL& callingWindowURL = callingWindow->document()->url();
1759 if (callingWindowURL.isNull())
1762 ASSERT(!callingWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
1764 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1765 SecurityOrigin* activeOrigin = callingWindow->document()->securityOrigin();
1766 SecurityOrigin* targetOrigin = document()->securityOrigin();
1767 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
1769 // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
1770 KURL activeURL = callingWindow->document()->url();
1771 KURL targetURL = document()->url();
1772 if (document()->isSandboxed(SandboxOrigin) || callingWindow->document()->isSandboxed(SandboxOrigin)) {
1773 message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL)->toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL)->toString() + "\". ";
1774 if (document()->isSandboxed(SandboxOrigin) && callingWindow->document()->isSandboxed(SandboxOrigin))
1775 return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
1776 if (document()->isSandboxed(SandboxOrigin))
1777 return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
1778 return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
1781 // 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:'.
1782 if (targetOrigin->protocol() != activeOrigin->protocol())
1783 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";
1785 // 'document.domain' errors.
1786 if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
1787 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.";
1788 if (activeOrigin->domainWasSetInDOM())
1789 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.";
1790 if (targetOrigin->domainWasSetInDOM())
1791 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.";
1794 return message + "Protocols, domains, and ports must match.";
1797 bool LocalDOMWindow::isInsecureScriptAccess(LocalDOMWindow& callingWindow, const String& urlString)
1799 if (!protocolIsJavaScript(urlString))
1802 // If this LocalDOMWindow isn't currently active in the LocalFrame, then there's no
1803 // way we should allow the access.
1804 // FIXME: Remove this check if we're able to disconnect LocalDOMWindow from
1805 // LocalFrame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
1806 if (isCurrentlyDisplayedInFrame()) {
1807 // FIXME: Is there some way to eliminate the need for a separate "callingWindow == this" check?
1808 if (&callingWindow == this)
1811 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1812 // Can we name the SecurityOrigin function better to make this more clear?
1813 if (callingWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()))
1817 printErrorMessage(crossDomainAccessErrorMessage(&callingWindow));
1821 PassRefPtrWillBeRawPtr<LocalDOMWindow> LocalDOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1822 LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow)
1824 if (!isCurrentlyDisplayedInFrame())
1826 Document* activeDocument = callingWindow->document();
1827 if (!activeDocument)
1829 LocalFrame* firstFrame = enteredWindow->frame();
1833 UseCounter::count(*activeDocument, UseCounter::DOMWindowOpen);
1834 if (!windowFeaturesString.isEmpty())
1835 UseCounter::count(*activeDocument, UseCounter::DOMWindowOpenFeatures);
1837 if (!enteredWindow->allowPopUp()) {
1838 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1839 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1840 if (frameName.isEmpty() || !frame()->tree().find(frameName))
1844 // Get the target frame for the special cases of _top and _parent.
1845 // In those cases, we schedule a location change right now and return early.
1846 Frame* targetFrame = 0;
1847 if (frameName == "_top")
1848 targetFrame = frame()->tree().top();
1849 else if (frameName == "_parent") {
1850 if (Frame* parent = frame()->tree().parent())
1851 targetFrame = parent;
1853 targetFrame = frame();
1855 // FIXME: Navigating RemoteFrames is not yet supported.
1856 if (targetFrame && targetFrame->isLocalFrame()) {
1857 if (!activeDocument->canNavigate(*targetFrame))
1860 KURL completedURL = firstFrame->document()->completeURL(urlString);
1862 if (targetFrame->domWindow()->isInsecureScriptAccess(*callingWindow, completedURL))
1863 return targetFrame->domWindow();
1865 if (urlString.isEmpty())
1866 return targetFrame->domWindow();
1868 toLocalFrame(targetFrame)->navigationScheduler().scheduleLocationChange(activeDocument, completedURL, false);
1869 return targetFrame->domWindow();
1872 WindowFeatures windowFeatures(windowFeaturesString);
1873 LocalFrame* result = createWindow(urlString, frameName, windowFeatures, *callingWindow, *firstFrame, *frame());
1874 return result ? result->domWindow() : 0;
1877 void LocalDOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1878 LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow, PrepareDialogFunction function, void* functionContext)
1880 if (!isCurrentlyDisplayedInFrame())
1882 LocalFrame* activeFrame = callingWindow->frame();
1885 LocalFrame* firstFrame = enteredWindow->frame();
1889 if (!canShowModalDialogNow(frame()) || !enteredWindow->allowPopUp())
1892 UseCounter::countDeprecation(this, UseCounter::ShowModalDialog);
1894 WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(frame()->view()));
1895 LocalFrame* dialogFrame = createWindow(urlString, emptyAtom, windowFeatures,
1896 *callingWindow, *firstFrame, *frame(), function, functionContext);
1899 UserGestureIndicatorDisabler disabler;
1900 dialogFrame->host()->chrome().runModal();
1903 LocalDOMWindow* LocalDOMWindow::anonymousIndexedGetter(uint32_t index)
1908 Frame* child = frame()->tree().scopedChild(index);
1910 return child->domWindow();
1915 DOMWindowLifecycleNotifier& LocalDOMWindow::lifecycleNotifier()
1917 return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext<LocalDOMWindow>::lifecycleNotifier());
1920 PassOwnPtr<LifecycleNotifier<LocalDOMWindow> > LocalDOMWindow::createLifecycleNotifier()
1922 return DOMWindowLifecycleNotifier::create(this);
1925 void LocalDOMWindow::trace(Visitor* visitor)
1928 visitor->trace(m_frameObserver);
1929 visitor->trace(m_document);
1930 visitor->trace(m_properties);
1931 visitor->trace(m_screen);
1932 visitor->trace(m_history);
1933 visitor->trace(m_locationbar);
1934 visitor->trace(m_menubar);
1935 visitor->trace(m_personalbar);
1936 visitor->trace(m_scrollbars);
1937 visitor->trace(m_statusbar);
1938 visitor->trace(m_toolbar);
1939 visitor->trace(m_console);
1940 visitor->trace(m_navigator);
1941 visitor->trace(m_location);
1942 visitor->trace(m_media);
1943 visitor->trace(m_sessionStorage);
1944 visitor->trace(m_localStorage);
1945 visitor->trace(m_applicationCache);
1946 visitor->trace(m_performance);
1947 visitor->trace(m_css);
1948 visitor->trace(m_eventQueue);
1949 HeapSupplementable<LocalDOMWindow>::trace(visitor);
1951 DOMWindow::trace(visitor);
1952 LifecycleContext<LocalDOMWindow>::trace(visitor);
1955 LocalFrame* LocalDOMWindow::frame() const
1957 return m_frameObserver->frame();
1960 v8::Handle<v8::Object> LocalDOMWindow::wrap(v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
1962 ASSERT_NOT_REACHED(); // LocalDOMWindow has [Custom=ToV8].
1963 return v8::Handle<v8::Object>();
1966 } // namespace blink