2 * Copyright (C) 2006, 2007, 2008, 2010, 2013 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 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 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 "DOMWindow.h"
30 #include "BackForwardController.h"
32 #include "BeforeUnloadEvent.h"
33 #include "CSSComputedStyleDeclaration.h"
35 #include "CSSRuleList.h"
37 #include "ChromeClient.h"
39 #include "DOMApplicationCache.h"
40 #include "DOMSelection.h"
41 #include "DOMSettableTokenList.h"
42 #include "DOMStringList.h"
44 #include "DOMTokenList.h"
46 #include "DOMWindowCSS.h"
47 #include "DOMWindowExtension.h"
48 #include "DOMWindowNotifications.h"
49 #include "DeviceMotionController.h"
50 #include "DeviceOrientationController.h"
52 #include "DocumentLoader.h"
55 #include "EventException.h"
56 #include "EventHandler.h"
57 #include "EventListener.h"
58 #include "EventNames.h"
59 #include "ExceptionCode.h"
60 #include "ExceptionCodePlaceholder.h"
61 #include "FloatRect.h"
62 #include "FocusController.h"
63 #include "FrameLoadRequest.h"
64 #include "FrameLoader.h"
65 #include "FrameLoaderClient.h"
66 #include "FrameTree.h"
67 #include "FrameView.h"
68 #include "HTMLFrameOwnerElement.h"
70 #include "InspectorInstrumentation.h"
71 #include "JSMainThreadExecState.h"
73 #include "MainFrame.h"
74 #include "MediaQueryList.h"
75 #include "MediaQueryMatcher.h"
76 #include "MessageEvent.h"
77 #include "Navigator.h"
79 #include "PageConsole.h"
80 #include "PageGroup.h"
81 #include "PageTransitionEvent.h"
82 #include "Performance.h"
83 #include "PlatformScreen.h"
84 #include "RuntimeEnabledFeatures.h"
85 #include "ScheduledAction.h"
87 #include "ScriptController.h"
88 #include "SecurityOrigin.h"
89 #include "SecurityPolicy.h"
90 #include "SerializedScriptValue.h"
93 #include "StorageArea.h"
94 #include "StorageNamespace.h"
95 #include "StyleMedia.h"
96 #include "StyleResolver.h"
97 #include "SuddenTermination.h"
99 #include "WebKitPoint.h"
100 #include "WindowFeatures.h"
101 #include "WindowFocusAllowedIndicator.h"
103 #include <inspector/ScriptCallStack.h>
104 #include <inspector/ScriptCallStackFactory.h>
106 #include <wtf/CurrentTime.h>
107 #include <wtf/MainThread.h>
108 #include <wtf/MathExtras.h>
110 #include <wtf/text/Base64.h>
111 #include <wtf/text/WTFString.h>
113 #if ENABLE(USER_MESSAGE_HANDLERS)
114 #include "UserContentController.h"
115 #include "UserMessageHandlerDescriptor.h"
116 #include "WebKitNamespace.h"
119 #if ENABLE(PROXIMITY_EVENTS)
120 #include "DeviceProximityController.h"
123 #if ENABLE(REQUEST_ANIMATION_FRAME)
124 #include "RequestAnimationFrameCallback.h"
128 #if ENABLE(GEOLOCATION)
129 #include "NavigatorGeolocation.h"
131 #include "WKContentObservation.h"
134 using namespace Inspector;
138 class PostMessageTimer : public TimerBase {
140 PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, std::unique_ptr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtr<ScriptCallStack> stackTrace)
143 , m_origin(sourceOrigin)
145 , m_channels(std::move(channels))
146 , m_targetOrigin(targetOrigin)
147 , m_stackTrace(stackTrace)
151 PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
153 std::unique_ptr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, std::move(m_channels));
154 return MessageEvent::create(std::move(messagePorts), m_message, m_origin, String(), m_source);
156 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
157 ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
162 // This object gets deleted when std::unique_ptr falls out of scope..
163 std::unique_ptr<PostMessageTimer> timer(this);
164 m_window->postMessageTimerFired(*timer);
167 RefPtr<DOMWindow> m_window;
168 RefPtr<SerializedScriptValue> m_message;
170 RefPtr<DOMWindow> m_source;
171 std::unique_ptr<MessagePortChannelArray> m_channels;
172 RefPtr<SecurityOrigin> m_targetOrigin;
173 RefPtr<ScriptCallStack> m_stackTrace;
176 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
178 static DOMWindowSet& windowsWithUnloadEventListeners()
180 DEPRECATED_DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
181 return windowsWithUnloadEventListeners;
184 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
186 DEPRECATED_DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
187 return windowsWithBeforeUnloadEventListeners;
190 static void addUnloadEventListener(DOMWindow* domWindow)
192 if (windowsWithUnloadEventListeners().add(domWindow).isNewEntry)
193 domWindow->disableSuddenTermination();
196 static void removeUnloadEventListener(DOMWindow* domWindow)
198 if (windowsWithUnloadEventListeners().remove(domWindow))
199 domWindow->enableSuddenTermination();
202 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
204 if (windowsWithUnloadEventListeners().removeAll(domWindow))
205 domWindow->enableSuddenTermination();
208 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
210 if (windowsWithBeforeUnloadEventListeners().add(domWindow).isNewEntry)
211 domWindow->disableSuddenTermination();
214 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
216 if (windowsWithBeforeUnloadEventListeners().remove(domWindow))
217 domWindow->enableSuddenTermination();
220 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
222 if (windowsWithBeforeUnloadEventListeners().removeAll(domWindow))
223 domWindow->enableSuddenTermination();
226 static bool allowsBeforeUnloadListeners(DOMWindow* window)
228 ASSERT_ARG(window, window);
229 Frame* frame = window->frame();
234 return frame->isMainFrame();
237 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
239 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
243 static bool alreadyDispatched = false;
244 ASSERT(!alreadyDispatched);
245 if (alreadyDispatched)
248 Vector<Ref<DOMWindow>> windows;
249 windows.reserveInitialCapacity(set.size());
250 for (auto it = set.begin(), end = set.end(); it != end; ++it)
251 windows.uncheckedAppend(*it->key);
253 for (unsigned i = 0; i < windows.size(); ++i) {
254 DOMWindow& window = windows[i].get();
255 if (!set.contains(&window))
258 Frame* frame = window.frame();
262 if (!frame->loader().shouldClose())
265 window.enableSuddenTermination();
268 alreadyDispatched = true;
272 unsigned DOMWindow::pendingUnloadEventListeners() const
274 return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
277 void DOMWindow::dispatchAllPendingUnloadEvents()
279 DOMWindowSet& set = windowsWithUnloadEventListeners();
283 static bool alreadyDispatched = false;
284 ASSERT(!alreadyDispatched);
285 if (alreadyDispatched)
288 Vector<Ref<DOMWindow>> windows;
289 windows.reserveInitialCapacity(set.size());
290 for (auto it = set.begin(), end = set.end(); it != end; ++it)
291 windows.uncheckedAppend(*it->key);
293 for (unsigned i = 0; i < windows.size(); ++i) {
294 DOMWindow& window = windows[i].get();
295 if (!set.contains(&window))
298 window.dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window.document());
299 window.dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window.document());
301 window.enableSuddenTermination();
304 alreadyDispatched = true;
308 // 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
309 // 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
310 // 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
311 // 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
312 // 5) Translate the window rect coordinates to be within the coordinate space of the screen.
313 FloatRect DOMWindow::adjustWindowRect(Page* page, const FloatRect& pendingChanges)
317 FloatRect screen = screenAvailableRect(page->mainFrame().view());
318 FloatRect window = page->chrome().windowRect();
320 // Make sure we're in a valid state before adjusting dimensions.
321 ASSERT(std::isfinite(screen.x()));
322 ASSERT(std::isfinite(screen.y()));
323 ASSERT(std::isfinite(screen.width()));
324 ASSERT(std::isfinite(screen.height()));
325 ASSERT(std::isfinite(window.x()));
326 ASSERT(std::isfinite(window.y()));
327 ASSERT(std::isfinite(window.width()));
328 ASSERT(std::isfinite(window.height()));
330 // Update window values if new requested values are not NaN.
331 if (!std::isnan(pendingChanges.x()))
332 window.setX(pendingChanges.x());
333 if (!std::isnan(pendingChanges.y()))
334 window.setY(pendingChanges.y());
335 if (!std::isnan(pendingChanges.width()))
336 window.setWidth(pendingChanges.width());
337 if (!std::isnan(pendingChanges.height()))
338 window.setHeight(pendingChanges.height());
340 FloatSize minimumSize = page->chrome().client().minimumWindowSize();
341 window.setWidth(std::min(std::max(minimumSize.width(), window.width()), screen.width()));
342 window.setHeight(std::min(std::max(minimumSize.height(), window.height()), screen.height()));
344 // Constrain the window position within the valid screen area.
345 window.setX(std::max(screen.x(), std::min(window.x(), screen.maxX() - window.width())));
346 window.setY(std::max(screen.y(), std::min(window.y(), screen.maxY() - window.height())));
351 bool DOMWindow::allowPopUp(Frame* firstFrame)
355 if (ScriptController::processingUserGesture())
358 return firstFrame->settings().javaScriptCanOpenWindowsAutomatically();
361 bool DOMWindow::allowPopUp()
363 return m_frame && allowPopUp(m_frame);
366 bool DOMWindow::canShowModalDialog(const Frame* frame)
370 Page* page = frame->page();
373 return page->chrome().canRunModal();
376 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
380 Page* page = frame->page();
383 return page->chrome().canRunModalNow();
386 DOMWindow::DOMWindow(Document* document)
387 : ContextDestructionObserver(document)
388 , FrameDestructionObserver(document->frame())
389 , m_shouldPrintWhenFinishedLoading(false)
390 , m_suspendedForPageCache(false)
391 , m_lastPageStatus(PageStatusNone)
393 , m_scrollEventListenerCount(0)
395 #if ENABLE(IOS_TOUCH_EVENTS) || ENABLE(IOS_GESTURE_EVENTS)
396 , m_touchEventListenerCount(0)
400 ASSERT(DOMWindow::document());
403 void DOMWindow::didSecureTransitionTo(Document* document)
405 observeContext(document);
408 DOMWindow::~DOMWindow()
411 if (!m_suspendedForPageCache) {
415 ASSERT(!m_locationbar);
417 ASSERT(!m_personalbar);
418 ASSERT(!m_scrollbars);
419 ASSERT(!m_statusbar);
421 ASSERT(!m_navigator);
422 #if ENABLE(WEB_TIMING)
423 ASSERT(!m_performance);
427 ASSERT(!m_sessionStorage);
428 ASSERT(!m_localStorage);
429 ASSERT(!m_applicationCache);
433 if (m_suspendedForPageCache)
434 willDestroyCachedFrame();
436 willDestroyDocumentInFrame();
438 // As the ASSERTs above indicate, this reset should only be necessary if this DOMWindow is suspended for the page cache.
439 // But we don't want to risk any of these objects hanging around after we've been destroyed.
440 resetDOMWindowProperties();
442 removeAllUnloadEventListeners(this);
443 removeAllBeforeUnloadEventListeners(this);
446 DOMWindow* DOMWindow::toDOMWindow()
451 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
453 return document() ? document()->mediaQueryMatcher().matchMedia(media) : 0;
456 Page* DOMWindow::page()
458 return frame() ? frame()->page() : 0;
461 void DOMWindow::frameDestroyed()
463 willDestroyDocumentInFrame();
464 FrameDestructionObserver::frameDestroyed();
465 resetDOMWindowProperties();
466 JSDOMWindowBase::fireFrameClearedWatchpointsForWindow(this);
469 void DOMWindow::willDetachPage()
471 InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
474 void DOMWindow::willDestroyCachedFrame()
476 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
477 // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInCachedFrame.
478 Vector<DOMWindowProperty*> properties;
479 copyToVector(m_properties, properties);
480 for (size_t i = 0; i < properties.size(); ++i)
481 properties[i]->willDestroyGlobalObjectInCachedFrame();
484 void DOMWindow::willDestroyDocumentInFrame()
486 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
487 // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInFrame.
488 Vector<DOMWindowProperty*> properties;
489 copyToVector(m_properties, properties);
490 for (size_t i = 0; i < properties.size(); ++i)
491 properties[i]->willDestroyGlobalObjectInFrame();
494 void DOMWindow::willDetachDocumentFromFrame()
496 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
497 // unregister themselves from the DOMWindow as a result of the call to willDetachGlobalObjectFromFrame.
498 Vector<DOMWindowProperty*> properties;
499 copyToVector(m_properties, properties);
500 for (size_t i = 0; i < properties.size(); ++i)
501 properties[i]->willDetachGlobalObjectFromFrame();
504 void DOMWindow::registerProperty(DOMWindowProperty* property)
506 m_properties.add(property);
509 void DOMWindow::unregisterProperty(DOMWindowProperty* property)
511 m_properties.remove(property);
514 void DOMWindow::resetUnlessSuspendedForPageCache()
516 if (m_suspendedForPageCache)
518 willDestroyDocumentInFrame();
519 resetDOMWindowProperties();
522 void DOMWindow::suspendForPageCache()
524 disconnectDOMWindowProperties();
525 m_suspendedForPageCache = true;
528 void DOMWindow::resumeFromPageCache()
530 reconnectDOMWindowProperties();
531 m_suspendedForPageCache = false;
534 void DOMWindow::disconnectDOMWindowProperties()
536 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
537 // unregister themselves from the DOMWindow as a result of the call to disconnectFrameForPageCache.
538 Vector<DOMWindowProperty*> properties;
539 copyToVector(m_properties, properties);
540 for (size_t i = 0; i < properties.size(); ++i)
541 properties[i]->disconnectFrameForPageCache();
544 void DOMWindow::reconnectDOMWindowProperties()
546 ASSERT(m_suspendedForPageCache);
547 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
548 // unregister themselves from the DOMWindow as a result of the call to reconnectFromPageCache.
549 Vector<DOMWindowProperty*> properties;
550 copyToVector(m_properties, properties);
551 for (size_t i = 0; i < properties.size(); ++i)
552 properties[i]->reconnectFrameFromPageCache(m_frame);
555 void DOMWindow::resetDOMWindowProperties()
557 m_properties.clear();
569 #if ENABLE(WEB_TIMING)
574 m_sessionStorage = 0;
576 m_applicationCache = 0;
579 bool DOMWindow::isCurrentlyDisplayedInFrame() const
581 return m_frame && m_frame->document()->domWindow() == this;
584 #if ENABLE(ORIENTATION_EVENTS)
585 int DOMWindow::orientation() const
590 return m_frame->orientation();
594 Screen* DOMWindow::screen() const
596 if (!isCurrentlyDisplayedInFrame())
599 m_screen = Screen::create(m_frame);
600 return m_screen.get();
603 History* DOMWindow::history() const
605 if (!isCurrentlyDisplayedInFrame())
608 m_history = History::create(m_frame);
609 return m_history.get();
612 Crypto* DOMWindow::crypto() const
614 // FIXME: Why is crypto not available when the window is not currently displayed in a frame?
615 if (!isCurrentlyDisplayedInFrame())
618 m_crypto = Crypto::create(*document());
619 return m_crypto.get();
622 BarProp* DOMWindow::locationbar() const
624 if (!isCurrentlyDisplayedInFrame())
627 m_locationbar = BarProp::create(m_frame, BarProp::Locationbar);
628 return m_locationbar.get();
631 BarProp* DOMWindow::menubar() const
633 if (!isCurrentlyDisplayedInFrame())
636 m_menubar = BarProp::create(m_frame, BarProp::Menubar);
637 return m_menubar.get();
640 BarProp* DOMWindow::personalbar() const
642 if (!isCurrentlyDisplayedInFrame())
645 m_personalbar = BarProp::create(m_frame, BarProp::Personalbar);
646 return m_personalbar.get();
649 BarProp* DOMWindow::scrollbars() const
651 if (!isCurrentlyDisplayedInFrame())
654 m_scrollbars = BarProp::create(m_frame, BarProp::Scrollbars);
655 return m_scrollbars.get();
658 BarProp* DOMWindow::statusbar() const
660 if (!isCurrentlyDisplayedInFrame())
663 m_statusbar = BarProp::create(m_frame, BarProp::Statusbar);
664 return m_statusbar.get();
667 BarProp* DOMWindow::toolbar() const
669 if (!isCurrentlyDisplayedInFrame())
672 m_toolbar = BarProp::create(m_frame, BarProp::Toolbar);
673 return m_toolbar.get();
676 PageConsole* DOMWindow::pageConsole() const
678 if (!isCurrentlyDisplayedInFrame())
680 return m_frame->page() ? &m_frame->page()->console() : 0;
683 DOMApplicationCache* DOMWindow::applicationCache() const
685 if (!isCurrentlyDisplayedInFrame())
687 if (!m_applicationCache)
688 m_applicationCache = DOMApplicationCache::create(m_frame);
689 return m_applicationCache.get();
692 Navigator* DOMWindow::navigator() const
694 if (!isCurrentlyDisplayedInFrame())
697 m_navigator = Navigator::create(m_frame);
698 return m_navigator.get();
701 #if ENABLE(WEB_TIMING)
702 Performance* DOMWindow::performance() const
704 if (!isCurrentlyDisplayedInFrame())
707 m_performance = Performance::create(m_frame);
708 return m_performance.get();
712 Location* DOMWindow::location() const
714 if (!isCurrentlyDisplayedInFrame())
717 m_location = Location::create(m_frame);
718 return m_location.get();
721 #if ENABLE(USER_MESSAGE_HANDLERS)
722 bool DOMWindow::shouldHaveWebKitNamespaceForWorld(DOMWrapperWorld& world)
727 auto* page = m_frame->page();
731 auto* userContentController = page->userContentController();
732 if (!userContentController)
735 auto* descriptorMap = userContentController->userMessageHandlerDescriptors();
739 for (auto& descriptor : descriptorMap->values()) {
740 if (&descriptor->world() == &world)
747 WebKitNamespace* DOMWindow::webkitNamespace() const
749 if (!isCurrentlyDisplayedInFrame())
751 if (!m_webkitNamespace)
752 m_webkitNamespace = WebKitNamespace::create(*m_frame);
753 return m_webkitNamespace.get();
757 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
759 if (!isCurrentlyDisplayedInFrame())
762 Document* document = this->document();
766 if (!document->securityOrigin()->canAccessSessionStorage(document->topOrigin())) {
771 if (m_sessionStorage) {
772 if (!m_sessionStorage->area().canAccessStorage(m_frame)) {
776 return m_sessionStorage.get();
779 Page* page = document->page();
783 RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
784 if (!storageArea->canAccessStorage(m_frame)) {
789 m_sessionStorage = Storage::create(m_frame, storageArea.release());
790 return m_sessionStorage.get();
793 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
795 if (!isCurrentlyDisplayedInFrame())
798 Document* document = this->document();
802 if (!document->securityOrigin()->canAccessLocalStorage(0)) {
807 if (m_localStorage) {
808 if (!m_localStorage->area().canAccessStorage(m_frame)) {
812 return m_localStorage.get();
815 Page* page = document->page();
819 if (!page->settings().localStorageEnabled())
822 RefPtr<StorageArea> storageArea;
823 if (!document->securityOrigin()->canAccessLocalStorage(document->topOrigin()))
824 storageArea = page->group().transientLocalStorage(document->topOrigin())->storageArea(document->securityOrigin());
826 storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
828 if (!storageArea->canAccessStorage(m_frame)) {
833 m_localStorage = Storage::create(m_frame, storageArea.release());
834 return m_localStorage.get();
837 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow& source, ExceptionCode& ec)
839 MessagePortArray ports;
842 postMessage(message, &ports, targetOrigin, source, ec);
845 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow& source, ExceptionCode& ec)
847 if (!isCurrentlyDisplayedInFrame())
850 Document* sourceDocument = source.document();
852 // Compute the target origin. We need to do this synchronously in order
853 // to generate the SYNTAX_ERR exception correctly.
854 RefPtr<SecurityOrigin> target;
855 if (targetOrigin == "/") {
858 target = sourceDocument->securityOrigin();
859 } else if (targetOrigin != "*") {
860 target = SecurityOrigin::createFromString(targetOrigin);
861 // It doesn't make sense target a postMessage at a unique origin
862 // because there's no way to represent a unique origin in a string.
863 if (target->isUnique()) {
869 std::unique_ptr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
873 // Capture the source of the message. We need to do this synchronously
874 // in order to capture the source of the message correctly.
877 String sourceOrigin = sourceDocument->securityOrigin()->toString();
879 // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
880 RefPtr<ScriptCallStack> stackTrace;
881 if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
882 stackTrace = createScriptCallStack(JSMainThreadExecState::currentState(), ScriptCallStack::maxCallStackSizeToCapture);
884 // Schedule the message.
885 PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, &source, std::move(channels), target.get(), stackTrace.release());
886 timer->startOneShot(0);
889 void DOMWindow::postMessageTimerFired(PostMessageTimer& timer)
891 if (!document() || !isCurrentlyDisplayedInFrame())
894 dispatchMessageEventWithOriginCheck(timer.targetOrigin(), timer.event(document()), timer.stackTrace());
897 void DOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event> event, PassRefPtr<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 = "Unable to post message to " + intendedTargetOrigin->toString() +
903 ". Recipient has origin " + document()->securityOrigin()->toString() + ".\n";
904 pageConsole()->addMessage(MessageSource::Security, MessageLevel::Error, message, stackTrace);
909 dispatchEvent(event);
912 DOMSelection* DOMWindow::getSelection()
914 if (!isCurrentlyDisplayedInFrame() || !m_frame)
917 return m_frame->document()->getSelection();
920 Element* DOMWindow::frameElement() const
925 return m_frame->ownerElement();
928 void DOMWindow::focus(ScriptExecutionContext* context)
933 Page* page = m_frame->page();
937 bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed() || !m_frame->settings().windowFocusRestricted();
939 ASSERT(isMainThread());
940 Document* activeDocument = toDocument(context);
941 if (opener() && opener() != this && activeDocument->domWindow() == opener())
945 // If we're a top level window, bring the window to the front.
946 if (m_frame->isMainFrame() && allowFocus)
947 page->chrome().focus();
952 // Clear the current frame's focused node if a new frame is about to be focused.
953 Frame* focusedFrame = page->focusController().focusedFrame();
954 if (focusedFrame && focusedFrame != m_frame)
955 focusedFrame->document()->setFocusedElement(0);
957 m_frame->eventHandler().focusDocumentView();
960 void DOMWindow::blur()
965 Page* page = m_frame->page();
969 if (m_frame->settings().windowFocusRestricted())
972 if (!m_frame->isMainFrame())
975 page->chrome().unfocus();
978 void DOMWindow::close(ScriptExecutionContext* context)
983 Page* page = m_frame->page();
987 if (!m_frame->isMainFrame())
991 ASSERT(isMainThread());
992 Document* activeDocument = toDocument(context);
996 if (!activeDocument->canNavigate(m_frame))
1000 bool allowScriptsToCloseWindows = m_frame->settings().allowScriptsToCloseWindows();
1002 if (!(page->openedByDOM() || page->backForward().count() <= 1 || allowScriptsToCloseWindows)) {
1003 pageConsole()->addMessage(MessageSource::JS, MessageLevel::Warning, ASCIILiteral("Can't close the window since it was not opened by JavaScript"));
1007 if (!m_frame->loader().shouldClose())
1010 page->chrome().closeWindowSoon();
1013 void DOMWindow::print()
1018 Page* page = m_frame->page();
1022 // Pages are not allowed to bring up a modal print dialog during BeforeUnload dispatch.
1023 if (page->isAnyFrameHandlingBeforeUnloadEvent()) {
1024 printErrorMessage("Use of window.print is not allowed during beforeunload event dispatch.");
1028 if (m_frame->loader().activeDocumentLoader()->isLoading()) {
1029 m_shouldPrintWhenFinishedLoading = true;
1032 m_shouldPrintWhenFinishedLoading = false;
1033 page->chrome().print(m_frame);
1036 void DOMWindow::stop()
1041 // We must check whether the load is complete asynchronously, because we might still be parsing
1042 // the document until the callstack unwinds.
1043 m_frame->loader().stopForUserCancel(true);
1046 void DOMWindow::alert(const String& message)
1051 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1052 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1053 printErrorMessage("Use of window.alert is not allowed during beforeunload event dispatch.");
1057 m_frame->document()->updateStyleIfNeeded();
1059 Page* page = m_frame->page();
1063 page->chrome().runJavaScriptAlert(m_frame, message);
1066 bool DOMWindow::confirm(const String& message)
1071 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1072 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1073 printErrorMessage("Use of window.confirm is not allowed during beforeunload event dispatch.");
1077 m_frame->document()->updateStyleIfNeeded();
1079 Page* page = m_frame->page();
1083 return page->chrome().runJavaScriptConfirm(m_frame, message);
1086 String DOMWindow::prompt(const String& message, const String& defaultValue)
1091 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1092 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1093 printErrorMessage("Use of window.prompt is not allowed during beforeunload event dispatch.");
1097 m_frame->document()->updateStyleIfNeeded();
1099 Page* page = m_frame->page();
1104 if (page->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
1110 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
1112 if (stringToEncode.isNull())
1115 if (!stringToEncode.containsOnlyLatin1()) {
1116 ec = INVALID_CHARACTER_ERR;
1120 return base64Encode(stringToEncode.latin1());
1123 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
1125 if (encodedString.isNull())
1128 if (!encodedString.containsOnlyLatin1()) {
1129 ec = INVALID_CHARACTER_ERR;
1134 if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacterOrExcessPadding)) {
1135 ec = INVALID_CHARACTER_ERR;
1139 return String(out.data(), out.size());
1142 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1144 if (!isCurrentlyDisplayedInFrame())
1147 // FIXME (13016): Support wholeWord, searchInFrames and showDialog.
1148 FindOptions options = (backwards ? Backwards : 0) | (caseSensitive ? 0 : CaseInsensitive) | (wrap ? WrapAround : 0);
1149 return m_frame->editor().findString(string, options);
1152 bool DOMWindow::offscreenBuffering() const
1157 int DOMWindow::outerHeight() const
1162 Page* page = m_frame->page();
1166 return static_cast<int>(page->chrome().windowRect().height());
1169 int DOMWindow::outerWidth() const
1174 Page* page = m_frame->page();
1178 return static_cast<int>(page->chrome().windowRect().width());
1181 int DOMWindow::innerHeight() const
1186 FrameView* view = m_frame->view();
1190 return view->mapFromLayoutToCSSUnits(static_cast<int>(view->unobscuredContentRectIncludingScrollbars().height()));
1193 int DOMWindow::innerWidth() const
1198 FrameView* view = m_frame->view();
1202 return view->mapFromLayoutToCSSUnits(static_cast<int>(view->unobscuredContentRectIncludingScrollbars().width()));
1205 int DOMWindow::screenX() const
1210 Page* page = m_frame->page();
1214 return static_cast<int>(page->chrome().windowRect().x());
1217 int DOMWindow::screenY() const
1222 Page* page = m_frame->page();
1226 return static_cast<int>(page->chrome().windowRect().y());
1229 int DOMWindow::scrollX() const
1234 FrameView* view = m_frame->view();
1238 int scrollX = view->contentsScrollPosition().x();
1242 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1244 return view->mapFromLayoutToCSSUnits(view->contentsScrollPosition().x());
1247 int DOMWindow::scrollY() const
1252 FrameView* view = m_frame->view();
1256 int scrollY = view->contentsScrollPosition().y();
1260 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1262 return view->mapFromLayoutToCSSUnits(view->contentsScrollPosition().y());
1265 bool DOMWindow::closed() const
1270 unsigned DOMWindow::length() const
1272 if (!isCurrentlyDisplayedInFrame())
1275 return m_frame->tree().scopedChildCount();
1278 String DOMWindow::name() const
1283 return m_frame->tree().name();
1286 void DOMWindow::setName(const String& string)
1291 m_frame->tree().setName(string);
1294 void DOMWindow::setStatus(const String& string)
1301 Page* page = m_frame->page();
1305 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1306 page->chrome().setStatusbarText(m_frame, m_status);
1309 void DOMWindow::setDefaultStatus(const String& string)
1311 m_defaultStatus = string;
1316 Page* page = m_frame->page();
1320 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1321 page->chrome().setStatusbarText(m_frame, m_defaultStatus);
1324 DOMWindow* DOMWindow::self() const
1329 return m_frame->document()->domWindow();
1332 DOMWindow* DOMWindow::opener() const
1337 Frame* opener = m_frame->loader().opener();
1341 return opener->document()->domWindow();
1344 DOMWindow* DOMWindow::parent() const
1349 Frame* parent = m_frame->tree().parent();
1351 return parent->document()->domWindow();
1353 return m_frame->document()->domWindow();
1356 DOMWindow* DOMWindow::top() const
1361 Page* page = m_frame->page();
1365 return m_frame->tree().top().document()->domWindow();
1368 Document* DOMWindow::document() const
1370 ScriptExecutionContext* context = ContextDestructionObserver::scriptExecutionContext();
1371 return toDocument(context);
1374 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1376 if (!isCurrentlyDisplayedInFrame())
1379 m_media = StyleMedia::create(m_frame);
1380 return m_media.get();
1383 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1388 return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
1391 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement, bool authorOnly) const
1393 if (!isCurrentlyDisplayedInFrame())
1396 unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
1397 CSSSelector::PseudoElementType pseudoType = CSSSelector::parsePseudoElementType(pseudoElement.substringSharingImpl(colonStart));
1398 if (pseudoType == CSSSelector::PseudoElementUnknown && !pseudoElement.isEmpty())
1401 unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
1403 rulesToInclude |= StyleResolver::UAAndUserCSSRules;
1404 if (m_frame->settings().crossOriginCheckInGetMatchedCSSRulesDisabled())
1405 rulesToInclude |= StyleResolver::CrossOriginCSSRules;
1407 PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
1409 auto matchedRules = m_frame->document()->ensureStyleResolver().pseudoStyleRulesForElement(element, pseudoId, rulesToInclude);
1410 if (matchedRules.isEmpty())
1413 RefPtr<StaticCSSRuleList> ruleList = StaticCSSRuleList::create();
1414 for (unsigned i = 0; i < matchedRules.size(); ++i)
1415 ruleList->rules().append(matchedRules[i]->createCSSOMWrapper());
1417 return ruleList.release();
1420 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1428 document()->updateLayoutIgnorePendingStylesheets();
1430 FloatPoint pagePoint(p->x(), p->y());
1431 pagePoint = node->convertToPage(pagePoint);
1432 return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1435 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1443 document()->updateLayoutIgnorePendingStylesheets();
1445 FloatPoint nodePoint(p->x(), p->y());
1446 nodePoint = node->convertFromPage(nodePoint);
1447 return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1450 double DOMWindow::devicePixelRatio() const
1455 Page* page = m_frame->page();
1459 return page->deviceScaleFactor();
1462 void DOMWindow::scrollBy(int x, int y) const
1464 if (!isCurrentlyDisplayedInFrame())
1467 document()->updateLayoutIgnorePendingStylesheets();
1469 FrameView* view = m_frame->view();
1473 IntSize scaledOffset(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
1474 view->setContentsScrollPosition(view->contentsScrollPosition() + scaledOffset);
1477 void DOMWindow::scrollTo(int x, int y) const
1479 if (!isCurrentlyDisplayedInFrame())
1482 RefPtr<FrameView> view = m_frame->view();
1486 if (!x && !y && view->contentsScrollPosition() == IntPoint(0, 0))
1489 document()->updateLayoutIgnorePendingStylesheets();
1491 IntPoint layoutPos(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
1492 view->setContentsScrollPosition(layoutPos);
1495 bool DOMWindow::allowedToChangeWindowGeometry() const
1499 if (!m_frame->page())
1501 if (!m_frame->isMainFrame())
1503 // Prevent web content from tricking the user into initiating a drag.
1504 if (m_frame->eventHandler().mousePressed())
1509 void DOMWindow::moveBy(float x, float y) const
1511 if (!allowedToChangeWindowGeometry())
1514 Page* page = m_frame->page();
1515 FloatRect fr = page->chrome().windowRect();
1516 FloatRect update = fr;
1518 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1519 page->chrome().setWindowRect(adjustWindowRect(page, update));
1522 void DOMWindow::moveTo(float x, float y) const
1524 if (!allowedToChangeWindowGeometry())
1527 Page* page = m_frame->page();
1528 FloatRect fr = page->chrome().windowRect();
1529 FloatRect sr = screenAvailableRect(page->mainFrame().view());
1530 fr.setLocation(sr.location());
1531 FloatRect update = fr;
1533 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1534 page->chrome().setWindowRect(adjustWindowRect(page, update));
1537 void DOMWindow::resizeBy(float x, float y) const
1539 if (!allowedToChangeWindowGeometry())
1542 Page* page = m_frame->page();
1543 FloatRect fr = page->chrome().windowRect();
1544 FloatSize dest = fr.size() + FloatSize(x, y);
1545 FloatRect update(fr.location(), dest);
1546 page->chrome().setWindowRect(adjustWindowRect(page, update));
1549 void DOMWindow::resizeTo(float width, float height) const
1551 if (!allowedToChangeWindowGeometry())
1554 Page* page = m_frame->page();
1555 FloatRect fr = page->chrome().windowRect();
1556 FloatSize dest = FloatSize(width, height);
1557 FloatRect update(fr.location(), dest);
1558 page->chrome().setWindowRect(adjustWindowRect(page, update));
1561 int DOMWindow::setTimeout(std::unique_ptr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1563 ScriptExecutionContext* context = scriptExecutionContext();
1565 ec = INVALID_ACCESS_ERR;
1568 return DOMTimer::install(context, std::move(action), timeout, true);
1571 void DOMWindow::clearTimeout(int timeoutId)
1575 Document* document = m_frame->document();
1576 if (timeoutId > 0 && document) {
1577 DOMTimer* timer = document->findTimeout(timeoutId);
1578 if (timer && WebThreadContainsObservedContentModifier(timer)) {
1579 WebThreadRemoveObservedContentModifier(timer);
1581 if (!WebThreadCountOfObservedContentModifiers()) {
1582 if (Page* page = m_frame->page())
1583 page->chrome().client().observedContentChange(m_frame);
1589 ScriptExecutionContext* context = scriptExecutionContext();
1592 DOMTimer::removeById(context, timeoutId);
1595 int DOMWindow::setInterval(std::unique_ptr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1597 ScriptExecutionContext* context = scriptExecutionContext();
1599 ec = INVALID_ACCESS_ERR;
1602 return DOMTimer::install(context, std::move(action), timeout, false);
1605 void DOMWindow::clearInterval(int timeoutId)
1607 ScriptExecutionContext* context = scriptExecutionContext();
1610 DOMTimer::removeById(context, timeoutId);
1613 #if ENABLE(REQUEST_ANIMATION_FRAME)
1614 int DOMWindow::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
1616 callback->m_useLegacyTimeBase = false;
1617 if (Document* d = document())
1618 return d->requestAnimationFrame(callback);
1622 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
1624 callback->m_useLegacyTimeBase = true;
1625 if (Document* d = document())
1626 return d->requestAnimationFrame(callback);
1630 void DOMWindow::cancelAnimationFrame(int id)
1632 if (Document* d = document())
1633 d->cancelAnimationFrame(id);
1637 #if ENABLE(CSS3_CONDITIONAL_RULES)
1638 DOMWindowCSS* DOMWindow::css()
1641 m_css = DOMWindowCSS::create();
1646 static void didAddStorageEventListener(DOMWindow* window)
1648 // Creating these WebCore::Storage objects informs the system that we'd like to receive
1649 // notifications about storage events that might be triggered in other processes. Rather
1650 // than subscribe to these notifications explicitly, we subscribe to them implicitly to
1651 // simplify the work done by the system.
1652 window->localStorage(IGNORE_EXCEPTION);
1653 window->sessionStorage(IGNORE_EXCEPTION);
1656 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1658 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1661 if (Document* document = this->document()) {
1662 document->addListenerTypeIfNeeded(eventType);
1663 if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
1664 document->didAddWheelEventHandler();
1665 else if (eventNames().isTouchEventType(eventType))
1666 document->didAddTouchEventHandler(document);
1667 else if (eventType == eventNames().storageEvent)
1668 didAddStorageEventListener(this);
1671 if (eventType == eventNames().unloadEvent)
1672 addUnloadEventListener(this);
1673 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1674 addBeforeUnloadEventListener(this);
1675 #if ENABLE(DEVICE_ORIENTATION)
1677 else if (eventType == eventNames().devicemotionEvent && document())
1678 document()->deviceMotionController()->addDeviceEventListener(this);
1679 else if (eventType == eventNames().deviceorientationEvent && document())
1680 document()->deviceOrientationController()->addDeviceEventListener(this);
1682 else if (eventType == eventNames().devicemotionEvent && RuntimeEnabledFeatures::sharedFeatures().deviceMotionEnabled()) {
1683 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1684 controller->addDeviceEventListener(this);
1685 } else if (eventType == eventNames().deviceorientationEvent && RuntimeEnabledFeatures::sharedFeatures().deviceOrientationEnabled()) {
1686 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1687 controller->addDeviceEventListener(this);
1689 #endif // PLATFORM(IOS)
1690 #endif // ENABLE(DEVICE_ORIENTATION)
1692 else if (eventType == eventNames().scrollEvent)
1693 incrementScrollEventListenersCount();
1695 #if ENABLE(IOS_TOUCH_EVENTS)
1696 else if (eventNames().isTouchEventType(eventType))
1697 ++m_touchEventListenerCount;
1699 #if ENABLE(IOS_GESTURE_EVENTS)
1700 else if (eventNames().isGestureEventType(eventType))
1701 ++m_touchEventListenerCount;
1704 #if ENABLE(PROXIMITY_EVENTS)
1705 else if (eventType == eventNames().webkitdeviceproximityEvent) {
1706 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1707 controller->addDeviceEventListener(this);
1715 void DOMWindow::incrementScrollEventListenersCount()
1717 Document* document = this->document();
1718 if (++m_scrollEventListenerCount == 1 && document == &document->topDocument()) {
1719 Frame* frame = this->frame();
1720 if (frame && frame->page())
1721 frame->page()->chrome().client().setNeedsScrollNotifications(frame, true);
1725 void DOMWindow::decrementScrollEventListenersCount()
1727 Document* document = this->document();
1728 if (!--m_scrollEventListenerCount && document == &document->topDocument()) {
1729 Frame* frame = this->frame();
1730 if (frame && frame->page() && !document->inPageCache())
1731 frame->page()->chrome().client().setNeedsScrollNotifications(frame, false);
1736 void DOMWindow::resetAllGeolocationPermission()
1738 // FIXME: Remove PLATFORM(IOS)-guard once we upstream the iOS changes to Geolocation.cpp.
1739 #if ENABLE(GEOLOCATION) && PLATFORM(IOS)
1741 NavigatorGeolocation::from(m_navigator.get())->resetAllGeolocationPermission();
1745 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1747 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1750 if (Document* document = this->document()) {
1751 if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
1752 document->didRemoveWheelEventHandler();
1753 else if (eventNames().isTouchEventType(eventType))
1754 document->didRemoveTouchEventHandler(document);
1757 if (eventType == eventNames().unloadEvent)
1758 removeUnloadEventListener(this);
1759 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1760 removeBeforeUnloadEventListener(this);
1761 #if ENABLE(DEVICE_ORIENTATION)
1763 else if (eventType == eventNames().devicemotionEvent && document())
1764 document()->deviceMotionController()->removeDeviceEventListener(this);
1765 else if (eventType == eventNames().deviceorientationEvent && document())
1766 document()->deviceOrientationController()->removeDeviceEventListener(this);
1768 else if (eventType == eventNames().devicemotionEvent) {
1769 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1770 controller->removeDeviceEventListener(this);
1771 } else if (eventType == eventNames().deviceorientationEvent) {
1772 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1773 controller->removeDeviceEventListener(this);
1775 #endif // PLATFORM(IOS)
1776 #endif // ENABLE(DEVICE_ORIENTATION)
1778 else if (eventType == eventNames().scrollEvent)
1779 decrementScrollEventListenersCount();
1781 #if ENABLE(IOS_TOUCH_EVENTS)
1782 else if (eventNames().isTouchEventType(eventType)) {
1783 ASSERT(m_touchEventListenerCount > 0);
1784 --m_touchEventListenerCount;
1787 #if ENABLE(IOS_GESTURE_EVENTS)
1788 else if (eventNames().isGestureEventType(eventType)) {
1789 ASSERT(m_touchEventListenerCount > 0);
1790 --m_touchEventListenerCount;
1794 #if ENABLE(PROXIMITY_EVENTS)
1795 else if (eventType == eventNames().webkitdeviceproximityEvent) {
1796 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1797 controller->removeDeviceEventListener(this);
1804 void DOMWindow::dispatchLoadEvent()
1806 RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1807 if (m_frame && m_frame->loader().documentLoader() && !m_frame->loader().documentLoader()->timing()->loadEventStart()) {
1808 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1809 // the event, so protect it to prevent writing the end time into freed memory.
1810 RefPtr<DocumentLoader> documentLoader = m_frame->loader().documentLoader();
1811 DocumentLoadTiming* timing = documentLoader->timing();
1812 timing->markLoadEventStart();
1813 dispatchEvent(loadEvent, document());
1814 timing->markLoadEventEnd();
1816 dispatchEvent(loadEvent, document());
1818 // For load events, send a separate load event to the enclosing frame only.
1819 // This is a DOM extension and is independent of bubbling/capturing rules of
1821 Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
1823 ownerElement->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
1825 InspectorInstrumentation::loadEventFired(frame());
1828 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1830 Ref<EventTarget> protect(*this);
1831 RefPtr<Event> event = prpEvent;
1833 // Pausing a page may trigger pagehide and pageshow events. WebCore also implicitly fires these
1834 // events when closing a WebView. Here we keep track of the state of the page to prevent duplicate,
1835 // unbalanced events per the definition of the pageshow event:
1836 // <http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pageshow>.
1837 if (event->eventInterface() == PageTransitionEventInterfaceType) {
1838 if (event->type() == eventNames().pageshowEvent) {
1839 if (m_lastPageStatus == PageStatusShown)
1840 return true; // Event was previously dispatched; do not fire a duplicate event.
1841 m_lastPageStatus = PageStatusShown;
1842 } else if (event->type() == eventNames().pagehideEvent) {
1843 if (m_lastPageStatus == PageStatusHidden)
1844 return true; // Event was previously dispatched; do not fire a duplicate event.
1845 m_lastPageStatus = PageStatusHidden;
1849 event->setTarget(prpTarget ? prpTarget : this);
1850 event->setCurrentTarget(this);
1851 event->setEventPhase(Event::AT_TARGET);
1853 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1855 bool result = fireEventListeners(event.get());
1857 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1862 void DOMWindow::removeAllEventListeners()
1864 EventTarget::removeAllEventListeners();
1866 #if ENABLE(DEVICE_ORIENTATION)
1868 if (Document* document = this->document()) {
1869 document->deviceMotionController()->removeAllDeviceEventListeners(this);
1870 document->deviceOrientationController()->removeAllDeviceEventListeners(this);
1873 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1874 controller->removeAllDeviceEventListeners(this);
1875 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1876 controller->removeAllDeviceEventListeners(this);
1877 #endif // PLATFORM(IOS)
1878 #endif // ENABLE(DEVICE_ORIENTATION)
1881 if (m_scrollEventListenerCount) {
1882 m_scrollEventListenerCount = 1;
1883 decrementScrollEventListenersCount();
1887 #if ENABLE(IOS_TOUCH_EVENTS) || ENABLE(IOS_GESTURE_EVENTS)
1888 m_touchEventListenerCount = 0;
1891 #if ENABLE(TOUCH_EVENTS)
1892 if (Document* document = this->document())
1893 document->didRemoveEventTargetNode(document);
1896 #if ENABLE(PROXIMITY_EVENTS)
1897 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1898 controller->removeAllDeviceEventListeners(this);
1901 removeAllUnloadEventListeners(this);
1902 removeAllBeforeUnloadEventListeners(this);
1905 void DOMWindow::captureEvents()
1910 void DOMWindow::releaseEvents()
1915 void DOMWindow::finishedLoading()
1917 if (m_shouldPrintWhenFinishedLoading) {
1918 m_shouldPrintWhenFinishedLoading = false;
1923 void DOMWindow::setLocation(const String& urlString, DOMWindow& activeWindow, DOMWindow& firstWindow, SetLocationLocking locking)
1925 if (!isCurrentlyDisplayedInFrame())
1928 Document* activeDocument = activeWindow.document();
1929 if (!activeDocument)
1932 if (!activeDocument->canNavigate(m_frame))
1935 Frame* firstFrame = firstWindow.frame();
1939 URL completedURL = firstFrame->document()->completeURL(urlString);
1940 if (completedURL.isNull())
1943 if (isInsecureScriptAccess(activeWindow, completedURL))
1946 // We want a new history item if we are processing a user gesture.
1947 LockHistory lockHistory = (locking != LockHistoryBasedOnGestureState || !ScriptController::processingUserGesture()) ? LockHistory::Yes : LockHistory::No;
1948 LockBackForwardList lockBackForwardList = (locking != LockHistoryBasedOnGestureState) ? LockBackForwardList::Yes : LockBackForwardList::No;
1949 m_frame->navigationScheduler().scheduleLocationChange(activeDocument->securityOrigin(),
1950 // FIXME: What if activeDocument()->frame() is 0?
1951 completedURL, activeDocument->frame()->loader().outgoingReferrer(),
1952 lockHistory, lockBackForwardList);
1955 void DOMWindow::printErrorMessage(const String& message)
1957 if (message.isEmpty())
1960 if (PageConsole* console = pageConsole())
1961 console->addMessage(MessageSource::JS, MessageLevel::Error, message);
1964 String DOMWindow::crossDomainAccessErrorMessage(const DOMWindow& activeWindow)
1966 const URL& activeWindowURL = activeWindow.document()->url();
1967 if (activeWindowURL.isNull())
1970 ASSERT(!activeWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()));
1972 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1973 SecurityOrigin* activeOrigin = activeWindow.document()->securityOrigin();
1974 SecurityOrigin* targetOrigin = document()->securityOrigin();
1975 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
1977 // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
1978 URL activeURL = activeWindow.document()->url();
1979 URL targetURL = document()->url();
1980 if (document()->isSandboxed(SandboxOrigin) || activeWindow.document()->isSandboxed(SandboxOrigin)) {
1981 message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL)->toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL)->toString() + "\". ";
1982 if (document()->isSandboxed(SandboxOrigin) && activeWindow.document()->isSandboxed(SandboxOrigin))
1983 return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
1984 if (document()->isSandboxed(SandboxOrigin))
1985 return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
1986 return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
1989 // 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:'.
1990 if (targetOrigin->protocol() != activeOrigin->protocol())
1991 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";
1993 // 'document.domain' errors.
1994 if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
1995 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.";
1996 if (activeOrigin->domainWasSetInDOM())
1997 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.";
1998 if (targetOrigin->domainWasSetInDOM())
1999 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.";
2002 return message + "Protocols, domains, and ports must match.";
2005 bool DOMWindow::isInsecureScriptAccess(DOMWindow& activeWindow, const String& urlString)
2007 if (!protocolIsJavaScript(urlString))
2010 // If this DOMWindow isn't currently active in the Frame, then there's no
2011 // way we should allow the access.
2012 // FIXME: Remove this check if we're able to disconnect DOMWindow from
2013 // Frame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
2014 if (isCurrentlyDisplayedInFrame()) {
2015 // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
2016 if (&activeWindow == this)
2019 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
2020 // Can we name the SecurityOrigin function better to make this more clear?
2021 if (activeWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()))
2025 printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
2029 PassRefPtr<Frame> DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures, DOMWindow& activeWindow, Frame* firstFrame, Frame* openerFrame, std::function<void (DOMWindow&)> prepareDialogFunction)
2031 Frame* activeFrame = activeWindow.frame();
2033 URL completedURL = urlString.isEmpty() ? URL(ParsedURLString, emptyString()) : firstFrame->document()->completeURL(urlString);
2034 if (!completedURL.isEmpty() && !completedURL.isValid()) {
2035 // Don't expose client code to invalid URLs.
2036 activeWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.string() + "'.\n");
2040 // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
2041 String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->loader().outgoingReferrer());
2043 ResourceRequest request(completedURL, referrer);
2044 FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader().outgoingOrigin());
2045 FrameLoadRequest frameRequest(activeWindow.document()->securityOrigin(), request, frameName);
2047 // We pass the opener frame for the lookupFrame in case the active frame is different from
2048 // the opener frame, and the name references a frame relative to the opener frame.
2050 RefPtr<Frame> newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
2054 newFrame->loader().setOpener(openerFrame);
2055 newFrame->page()->setOpenedByDOM();
2057 if (newFrame->document()->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
2058 return newFrame.release();
2060 if (prepareDialogFunction)
2061 prepareDialogFunction(*newFrame->document()->domWindow());
2064 newFrame->loader().changeLocation(activeWindow.document()->securityOrigin(), completedURL, referrer, LockHistory::No, LockBackForwardList::No);
2065 else if (!urlString.isEmpty()) {
2066 LockHistory lockHistory = ScriptController::processingUserGesture() ? LockHistory::No : LockHistory::Yes;
2067 newFrame->navigationScheduler().scheduleLocationChange(activeWindow.document()->securityOrigin(), completedURL, referrer, lockHistory, LockBackForwardList::No);
2070 // Navigating the new frame could result in it being detached from its page by a navigation policy delegate.
2071 if (!newFrame->page())
2074 return newFrame.release();
2077 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
2078 DOMWindow& activeWindow, DOMWindow& firstWindow)
2080 if (!isCurrentlyDisplayedInFrame())
2082 Document* activeDocument = activeWindow.document();
2083 if (!activeDocument)
2085 Frame* firstFrame = firstWindow.frame();
2089 if (!firstWindow.allowPopUp()) {
2090 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
2091 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
2092 if (frameName.isEmpty() || !m_frame->tree().find(frameName))
2096 // Get the target frame for the special cases of _top and _parent.
2097 // In those cases, we schedule a location change right now and return early.
2098 Frame* targetFrame = 0;
2099 if (frameName == "_top")
2100 targetFrame = &m_frame->tree().top();
2101 else if (frameName == "_parent") {
2102 if (Frame* parent = m_frame->tree().parent())
2103 targetFrame = parent;
2105 targetFrame = m_frame;
2108 if (!activeDocument->canNavigate(targetFrame))
2111 URL completedURL = firstFrame->document()->completeURL(urlString);
2113 if (targetFrame->document()->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
2114 return targetFrame->document()->domWindow();
2116 if (urlString.isEmpty())
2117 return targetFrame->document()->domWindow();
2119 // For whatever reason, Firefox uses the first window rather than the active window to
2120 // determine the outgoing referrer. We replicate that behavior here.
2121 LockHistory lockHistory = ScriptController::processingUserGesture() ? LockHistory::No : LockHistory::Yes;
2122 targetFrame->navigationScheduler().scheduleLocationChange(activeDocument->securityOrigin(), completedURL, firstFrame->loader().outgoingReferrer(),
2123 lockHistory, LockBackForwardList::No);
2124 return targetFrame->document()->domWindow();
2127 WindowFeatures windowFeatures(windowFeaturesString);
2128 RefPtr<Frame> result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
2129 return result ? result->document()->domWindow() : 0;
2132 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString, DOMWindow& activeWindow, DOMWindow& firstWindow, std::function<void (DOMWindow&)> prepareDialogFunction)
2134 if (!isCurrentlyDisplayedInFrame())
2136 Frame* activeFrame = activeWindow.frame();
2139 Frame* firstFrame = firstWindow.frame();
2143 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
2144 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
2145 printErrorMessage("Use of window.showModalDialog is not allowed during beforeunload event dispatch.");
2149 if (!canShowModalDialogNow(m_frame) || !firstWindow.allowPopUp())
2152 WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view()));
2153 RefPtr<Frame> dialogFrame = createWindow(urlString, emptyAtom, windowFeatures, activeWindow, firstFrame, m_frame, std::move(prepareDialogFunction));
2156 dialogFrame->page()->chrome().runModal();
2159 void DOMWindow::enableSuddenTermination()
2161 if (Page* page = this->page())
2162 page->chrome().enableSuddenTermination();
2165 void DOMWindow::disableSuddenTermination()
2167 if (Page* page = this->page())
2168 page->chrome().disableSuddenTermination();
2171 } // namespace WebCore