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"
38 #include "ContentExtensionActions.h"
39 #include "ContentExtensionRule.h"
41 #include "DOMApplicationCache.h"
42 #include "DOMSelection.h"
43 #include "DOMSettableTokenList.h"
44 #include "DOMStringList.h"
46 #include "DOMTokenList.h"
48 #include "DOMWindowCSS.h"
49 #include "DOMWindowExtension.h"
50 #include "DOMWindowNotifications.h"
51 #include "DeviceMotionController.h"
52 #include "DeviceOrientationController.h"
54 #include "DocumentLoader.h"
57 #include "EventException.h"
58 #include "EventHandler.h"
59 #include "EventListener.h"
60 #include "EventNames.h"
61 #include "ExceptionCode.h"
62 #include "ExceptionCodePlaceholder.h"
63 #include "FloatRect.h"
64 #include "FocusController.h"
65 #include "FrameLoadRequest.h"
66 #include "FrameLoader.h"
67 #include "FrameLoaderClient.h"
68 #include "FrameTree.h"
69 #include "FrameView.h"
70 #include "HTMLFrameOwnerElement.h"
72 #include "InspectorInstrumentation.h"
73 #include "JSMainThreadExecState.h"
75 #include "MainFrame.h"
76 #include "MediaQueryList.h"
77 #include "MediaQueryMatcher.h"
78 #include "MessageEvent.h"
79 #include "Navigator.h"
81 #include "PageConsoleClient.h"
82 #include "PageGroup.h"
83 #include "PageTransitionEvent.h"
84 #include "Performance.h"
85 #include "PlatformScreen.h"
86 #include "ResourceLoadInfo.h"
87 #include "RuntimeEnabledFeatures.h"
88 #include "ScheduledAction.h"
90 #include "ScriptController.h"
91 #include "SecurityOrigin.h"
92 #include "SecurityPolicy.h"
93 #include "SerializedScriptValue.h"
96 #include "StorageArea.h"
97 #include "StorageNamespace.h"
98 #include "StorageNamespaceProvider.h"
99 #include "StyleMedia.h"
100 #include "StyleResolver.h"
101 #include "SuddenTermination.h"
103 #include "WebKitPoint.h"
104 #include "WindowFeatures.h"
105 #include "WindowFocusAllowedIndicator.h"
106 #include <JavaScriptCore/Profile.h>
108 #include <inspector/ScriptCallStack.h>
109 #include <inspector/ScriptCallStackFactory.h>
111 #include <wtf/CurrentTime.h>
112 #include <wtf/MainThread.h>
113 #include <wtf/MathExtras.h>
115 #include <wtf/text/Base64.h>
116 #include <wtf/text/WTFString.h>
118 #if ENABLE(USER_MESSAGE_HANDLERS)
119 #include "UserContentController.h"
120 #include "UserMessageHandlerDescriptor.h"
121 #include "WebKitNamespace.h"
124 #if ENABLE(PROXIMITY_EVENTS)
125 #include "DeviceProximityController.h"
128 #if ENABLE(REQUEST_ANIMATION_FRAME)
129 #include "RequestAnimationFrameCallback.h"
133 #include "GamepadManager.h"
137 #if ENABLE(GEOLOCATION)
138 #include "NavigatorGeolocation.h"
140 #include "WKContentObservation.h"
143 using namespace Inspector;
147 class PostMessageTimer : public TimerBase {
149 PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, std::unique_ptr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtr<ScriptCallStack> stackTrace)
152 , m_origin(sourceOrigin)
154 , m_channels(WTF::move(channels))
155 , m_targetOrigin(targetOrigin)
156 , m_stackTrace(stackTrace)
160 PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
162 std::unique_ptr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, WTF::move(m_channels));
163 return MessageEvent::create(WTF::move(messagePorts), m_message, m_origin, String(), m_source);
165 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
166 ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
171 // This object gets deleted when std::unique_ptr falls out of scope..
172 std::unique_ptr<PostMessageTimer> timer(this);
173 m_window->postMessageTimerFired(*timer);
176 RefPtr<DOMWindow> m_window;
177 RefPtr<SerializedScriptValue> m_message;
179 RefPtr<DOMWindow> m_source;
180 std::unique_ptr<MessagePortChannelArray> m_channels;
181 RefPtr<SecurityOrigin> m_targetOrigin;
182 RefPtr<ScriptCallStack> m_stackTrace;
185 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
187 static DOMWindowSet& windowsWithUnloadEventListeners()
189 DEPRECATED_DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
190 return windowsWithUnloadEventListeners;
193 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
195 DEPRECATED_DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
196 return windowsWithBeforeUnloadEventListeners;
199 static void addUnloadEventListener(DOMWindow* domWindow)
201 if (windowsWithUnloadEventListeners().add(domWindow).isNewEntry)
202 domWindow->disableSuddenTermination();
205 static void removeUnloadEventListener(DOMWindow* domWindow)
207 if (windowsWithUnloadEventListeners().remove(domWindow))
208 domWindow->enableSuddenTermination();
211 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
213 if (windowsWithUnloadEventListeners().removeAll(domWindow))
214 domWindow->enableSuddenTermination();
217 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
219 if (windowsWithBeforeUnloadEventListeners().add(domWindow).isNewEntry)
220 domWindow->disableSuddenTermination();
223 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
225 if (windowsWithBeforeUnloadEventListeners().remove(domWindow))
226 domWindow->enableSuddenTermination();
229 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
231 if (windowsWithBeforeUnloadEventListeners().removeAll(domWindow))
232 domWindow->enableSuddenTermination();
235 static bool allowsBeforeUnloadListeners(DOMWindow* window)
237 ASSERT_ARG(window, window);
238 Frame* frame = window->frame();
243 return frame->isMainFrame();
246 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
248 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
252 static bool alreadyDispatched = false;
253 ASSERT(!alreadyDispatched);
254 if (alreadyDispatched)
257 Vector<Ref<DOMWindow>> windows;
258 windows.reserveInitialCapacity(set.size());
259 for (auto it = set.begin(), end = set.end(); it != end; ++it)
260 windows.uncheckedAppend(*it->key);
262 for (Ref<DOMWindow>& windowRef : windows) {
263 DOMWindow& window = windowRef;
264 if (!set.contains(&window))
267 Frame* frame = window.frame();
271 if (!frame->loader().shouldClose())
274 window.enableSuddenTermination();
277 alreadyDispatched = true;
281 unsigned DOMWindow::pendingUnloadEventListeners() const
283 return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
286 void DOMWindow::dispatchAllPendingUnloadEvents()
288 DOMWindowSet& set = windowsWithUnloadEventListeners();
292 static bool alreadyDispatched = false;
293 ASSERT(!alreadyDispatched);
294 if (alreadyDispatched)
297 Vector<Ref<DOMWindow>> windows;
298 windows.reserveInitialCapacity(set.size());
299 for (auto& keyValue : set)
300 windows.uncheckedAppend(*keyValue.key);
302 for (Ref<DOMWindow>& windowRef : windows) {
303 DOMWindow& window = windowRef;
304 if (!set.contains(&window))
307 window.dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window.document());
308 window.dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window.document());
310 window.enableSuddenTermination();
313 alreadyDispatched = true;
317 // 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
318 // 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
319 // 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
320 // 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
321 // 5) Translate the window rect coordinates to be within the coordinate space of the screen.
322 FloatRect DOMWindow::adjustWindowRect(Page* page, const FloatRect& pendingChanges)
326 FloatRect screen = screenAvailableRect(page->mainFrame().view());
327 FloatRect window = page->chrome().windowRect();
329 // Make sure we're in a valid state before adjusting dimensions.
330 ASSERT(std::isfinite(screen.x()));
331 ASSERT(std::isfinite(screen.y()));
332 ASSERT(std::isfinite(screen.width()));
333 ASSERT(std::isfinite(screen.height()));
334 ASSERT(std::isfinite(window.x()));
335 ASSERT(std::isfinite(window.y()));
336 ASSERT(std::isfinite(window.width()));
337 ASSERT(std::isfinite(window.height()));
339 // Update window values if new requested values are not NaN.
340 if (!std::isnan(pendingChanges.x()))
341 window.setX(pendingChanges.x());
342 if (!std::isnan(pendingChanges.y()))
343 window.setY(pendingChanges.y());
344 if (!std::isnan(pendingChanges.width()))
345 window.setWidth(pendingChanges.width());
346 if (!std::isnan(pendingChanges.height()))
347 window.setHeight(pendingChanges.height());
349 FloatSize minimumSize = page->chrome().client().minimumWindowSize();
350 window.setWidth(std::min(std::max(minimumSize.width(), window.width()), screen.width()));
351 window.setHeight(std::min(std::max(minimumSize.height(), window.height()), screen.height()));
353 // Constrain the window position within the valid screen area.
354 window.setX(std::max(screen.x(), std::min(window.x(), screen.maxX() - window.width())));
355 window.setY(std::max(screen.y(), std::min(window.y(), screen.maxY() - window.height())));
360 bool DOMWindow::allowPopUp(Frame* firstFrame)
364 if (ScriptController::processingUserGesture())
367 return firstFrame->settings().javaScriptCanOpenWindowsAutomatically();
370 bool DOMWindow::allowPopUp()
372 return m_frame && allowPopUp(m_frame);
375 bool DOMWindow::canShowModalDialog(const Frame* frame)
379 Page* page = frame->page();
382 return page->chrome().canRunModal();
385 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
389 Page* page = frame->page();
392 return page->chrome().canRunModalNow();
395 DOMWindow::DOMWindow(Document* document)
396 : ContextDestructionObserver(document)
397 , FrameDestructionObserver(document->frame())
398 , m_shouldPrintWhenFinishedLoading(false)
399 , m_suspendedForPageCache(false)
400 , m_lastPageStatus(PageStatusNone)
401 , m_weakPtrFactory(this)
403 , m_scrollEventListenerCount(0)
405 #if ENABLE(IOS_TOUCH_EVENTS) || ENABLE(IOS_GESTURE_EVENTS)
406 , m_touchEventListenerCount(0)
409 , m_gamepadEventListenerCount(0)
413 ASSERT(DOMWindow::document());
416 void DOMWindow::didSecureTransitionTo(Document* document)
418 observeContext(document);
421 DOMWindow::~DOMWindow()
424 if (!m_suspendedForPageCache) {
428 ASSERT(!m_locationbar);
430 ASSERT(!m_personalbar);
431 ASSERT(!m_scrollbars);
432 ASSERT(!m_statusbar);
434 ASSERT(!m_navigator);
435 #if ENABLE(WEB_TIMING)
436 ASSERT(!m_performance);
440 ASSERT(!m_sessionStorage);
441 ASSERT(!m_localStorage);
442 ASSERT(!m_applicationCache);
446 if (m_suspendedForPageCache)
447 willDestroyCachedFrame();
449 willDestroyDocumentInFrame();
451 // As the ASSERTs above indicate, this reset should only be necessary if this DOMWindow is suspended for the page cache.
452 // But we don't want to risk any of these objects hanging around after we've been destroyed.
453 resetDOMWindowProperties();
455 removeAllUnloadEventListeners(this);
456 removeAllBeforeUnloadEventListeners(this);
459 if (m_gamepadEventListenerCount)
460 GamepadManager::singleton().unregisterDOMWindow(this);
464 DOMWindow* DOMWindow::toDOMWindow()
469 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
471 return document() ? document()->mediaQueryMatcher().matchMedia(media) : 0;
474 Page* DOMWindow::page()
476 return frame() ? frame()->page() : 0;
479 void DOMWindow::frameDestroyed()
481 willDestroyDocumentInFrame();
482 FrameDestructionObserver::frameDestroyed();
483 resetDOMWindowProperties();
484 JSDOMWindowBase::fireFrameClearedWatchpointsForWindow(this);
487 void DOMWindow::willDetachPage()
489 InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
492 void DOMWindow::willDestroyCachedFrame()
494 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
495 // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInCachedFrame.
496 Vector<DOMWindowProperty*> properties;
497 copyToVector(m_properties, properties);
498 for (size_t i = 0; i < properties.size(); ++i)
499 properties[i]->willDestroyGlobalObjectInCachedFrame();
502 void DOMWindow::willDestroyDocumentInFrame()
504 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
505 // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInFrame.
506 Vector<DOMWindowProperty*> properties;
507 copyToVector(m_properties, properties);
508 for (size_t i = 0; i < properties.size(); ++i)
509 properties[i]->willDestroyGlobalObjectInFrame();
512 void DOMWindow::willDetachDocumentFromFrame()
514 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
515 // unregister themselves from the DOMWindow as a result of the call to willDetachGlobalObjectFromFrame.
516 Vector<DOMWindowProperty*> properties;
517 copyToVector(m_properties, properties);
518 for (size_t i = 0; i < properties.size(); ++i)
519 properties[i]->willDetachGlobalObjectFromFrame();
523 void DOMWindow::incrementGamepadEventListenerCount()
525 if (++m_gamepadEventListenerCount == 1)
526 GamepadManager::singleton().registerDOMWindow(this);
529 void DOMWindow::decrementGamepadEventListenerCount()
531 ASSERT(m_gamepadEventListenerCount);
533 if (!--m_gamepadEventListenerCount)
534 GamepadManager::singleton().unregisterDOMWindow(this);
538 void DOMWindow::registerProperty(DOMWindowProperty* property)
540 m_properties.add(property);
543 void DOMWindow::unregisterProperty(DOMWindowProperty* property)
545 m_properties.remove(property);
548 void DOMWindow::resetUnlessSuspendedForPageCache()
550 if (m_suspendedForPageCache)
552 willDestroyDocumentInFrame();
553 resetDOMWindowProperties();
556 void DOMWindow::suspendForPageCache()
558 disconnectDOMWindowProperties();
559 m_suspendedForPageCache = true;
562 void DOMWindow::resumeFromPageCache()
564 reconnectDOMWindowProperties();
565 m_suspendedForPageCache = false;
568 void DOMWindow::disconnectDOMWindowProperties()
570 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
571 // unregister themselves from the DOMWindow as a result of the call to disconnectFrameForPageCache.
572 Vector<DOMWindowProperty*> properties;
573 copyToVector(m_properties, properties);
574 for (size_t i = 0; i < properties.size(); ++i)
575 properties[i]->disconnectFrameForPageCache();
578 void DOMWindow::reconnectDOMWindowProperties()
580 ASSERT(m_suspendedForPageCache);
581 // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
582 // unregister themselves from the DOMWindow as a result of the call to reconnectFromPageCache.
583 Vector<DOMWindowProperty*> properties;
584 copyToVector(m_properties, properties);
585 for (size_t i = 0; i < properties.size(); ++i)
586 properties[i]->reconnectFrameFromPageCache(m_frame);
589 void DOMWindow::resetDOMWindowProperties()
591 m_properties.clear();
603 #if ENABLE(WEB_TIMING)
608 m_sessionStorage = 0;
610 m_applicationCache = 0;
613 bool DOMWindow::isCurrentlyDisplayedInFrame() const
615 return m_frame && m_frame->document()->domWindow() == this;
618 #if ENABLE(ORIENTATION_EVENTS)
619 int DOMWindow::orientation() const
624 return m_frame->orientation();
628 Screen* DOMWindow::screen() const
630 if (!isCurrentlyDisplayedInFrame())
633 m_screen = Screen::create(m_frame);
634 return m_screen.get();
637 History* DOMWindow::history() const
639 if (!isCurrentlyDisplayedInFrame())
642 m_history = History::create(m_frame);
643 return m_history.get();
646 Crypto* DOMWindow::crypto() const
648 // FIXME: Why is crypto not available when the window is not currently displayed in a frame?
649 if (!isCurrentlyDisplayedInFrame())
652 m_crypto = Crypto::create(*document());
653 return m_crypto.get();
656 BarProp* DOMWindow::locationbar() const
658 if (!isCurrentlyDisplayedInFrame())
661 m_locationbar = BarProp::create(m_frame, BarProp::Locationbar);
662 return m_locationbar.get();
665 BarProp* DOMWindow::menubar() const
667 if (!isCurrentlyDisplayedInFrame())
670 m_menubar = BarProp::create(m_frame, BarProp::Menubar);
671 return m_menubar.get();
674 BarProp* DOMWindow::personalbar() const
676 if (!isCurrentlyDisplayedInFrame())
679 m_personalbar = BarProp::create(m_frame, BarProp::Personalbar);
680 return m_personalbar.get();
683 BarProp* DOMWindow::scrollbars() const
685 if (!isCurrentlyDisplayedInFrame())
688 m_scrollbars = BarProp::create(m_frame, BarProp::Scrollbars);
689 return m_scrollbars.get();
692 BarProp* DOMWindow::statusbar() const
694 if (!isCurrentlyDisplayedInFrame())
697 m_statusbar = BarProp::create(m_frame, BarProp::Statusbar);
698 return m_statusbar.get();
701 BarProp* DOMWindow::toolbar() const
703 if (!isCurrentlyDisplayedInFrame())
706 m_toolbar = BarProp::create(m_frame, BarProp::Toolbar);
707 return m_toolbar.get();
710 PageConsoleClient* DOMWindow::console() const
712 if (!isCurrentlyDisplayedInFrame())
714 return m_frame->page() ? &m_frame->page()->console() : nullptr;
717 DOMApplicationCache* DOMWindow::applicationCache() const
719 if (!isCurrentlyDisplayedInFrame())
721 if (!m_applicationCache)
722 m_applicationCache = DOMApplicationCache::create(m_frame);
723 return m_applicationCache.get();
726 Navigator* DOMWindow::navigator() const
728 if (!isCurrentlyDisplayedInFrame())
731 m_navigator = Navigator::create(m_frame);
732 return m_navigator.get();
735 #if ENABLE(WEB_TIMING)
736 Performance* DOMWindow::performance() const
738 if (!isCurrentlyDisplayedInFrame())
741 m_performance = Performance::create(m_frame);
742 return m_performance.get();
746 Location* DOMWindow::location() const
748 if (!isCurrentlyDisplayedInFrame())
751 m_location = Location::create(m_frame);
752 return m_location.get();
755 #if ENABLE(USER_MESSAGE_HANDLERS)
756 bool DOMWindow::shouldHaveWebKitNamespaceForWorld(DOMWrapperWorld& world)
761 auto* page = m_frame->page();
765 auto* userContentController = page->userContentController();
766 if (!userContentController)
769 auto* descriptorMap = userContentController->userMessageHandlerDescriptors();
773 for (auto& descriptor : descriptorMap->values()) {
774 if (&descriptor->world() == &world)
781 WebKitNamespace* DOMWindow::webkitNamespace() const
783 if (!isCurrentlyDisplayedInFrame())
785 if (!m_webkitNamespace)
786 m_webkitNamespace = WebKitNamespace::create(*m_frame);
787 return m_webkitNamespace.get();
791 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
793 if (!isCurrentlyDisplayedInFrame())
796 Document* document = this->document();
800 if (!document->securityOrigin()->canAccessSessionStorage(document->topOrigin())) {
805 if (m_sessionStorage) {
806 if (!m_sessionStorage->area().canAccessStorage(m_frame)) {
810 return m_sessionStorage.get();
813 Page* page = document->page();
817 RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
818 if (!storageArea->canAccessStorage(m_frame)) {
823 m_sessionStorage = Storage::create(m_frame, storageArea.release());
824 return m_sessionStorage.get();
827 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
829 if (!isCurrentlyDisplayedInFrame())
832 Document* document = this->document();
836 if (!document->securityOrigin()->canAccessLocalStorage(0)) {
841 Page* page = document->page();
842 // FIXME: We should consider supporting access/modification to local storage
843 // after calling window.close(). See <https://bugs.webkit.org/show_bug.cgi?id=135330>.
844 if (!page || !page->isClosing()) {
845 if (m_localStorage) {
846 if (!m_localStorage->area().canAccessStorage(m_frame)) {
850 return m_localStorage.get();
857 if (page->isClosing())
860 if (!page->settings().localStorageEnabled())
863 RefPtr<StorageArea> storageArea = page->storageNamespaceProvider().localStorageArea(*document);
865 if (!storageArea->canAccessStorage(m_frame)) {
870 m_localStorage = Storage::create(m_frame, storageArea.release());
871 return m_localStorage.get();
874 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow& source, ExceptionCode& ec)
876 MessagePortArray ports;
879 postMessage(message, &ports, targetOrigin, source, ec);
882 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow& source, ExceptionCode& ec)
884 if (!isCurrentlyDisplayedInFrame())
887 Document* sourceDocument = source.document();
889 // Compute the target origin. We need to do this synchronously in order
890 // to generate the SYNTAX_ERR exception correctly.
891 RefPtr<SecurityOrigin> target;
892 if (targetOrigin == "/") {
895 target = sourceDocument->securityOrigin();
896 } else if (targetOrigin != "*") {
897 target = SecurityOrigin::createFromString(targetOrigin);
898 // It doesn't make sense target a postMessage at a unique origin
899 // because there's no way to represent a unique origin in a string.
900 if (target->isUnique()) {
906 std::unique_ptr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
910 // Capture the source of the message. We need to do this synchronously
911 // in order to capture the source of the message correctly.
914 String sourceOrigin = sourceDocument->securityOrigin()->toString();
916 // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
917 RefPtr<ScriptCallStack> stackTrace;
918 if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
919 stackTrace = createScriptCallStack(JSMainThreadExecState::currentState(), ScriptCallStack::maxCallStackSizeToCapture);
921 // Schedule the message.
922 PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, &source, WTF::move(channels), target.get(), stackTrace.release());
923 timer->startOneShot(0);
926 void DOMWindow::postMessageTimerFired(PostMessageTimer& timer)
928 if (!document() || !isCurrentlyDisplayedInFrame())
931 dispatchMessageEventWithOriginCheck(timer.targetOrigin(), timer.event(document()), timer.stackTrace());
934 void DOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event> event, PassRefPtr<ScriptCallStack> stackTrace)
936 if (intendedTargetOrigin) {
937 // Check target origin now since the target document may have changed since the timer was scheduled.
938 if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
939 String message = "Unable to post message to " + intendedTargetOrigin->toString() +
940 ". Recipient has origin " + document()->securityOrigin()->toString() + ".\n";
941 console()->addMessage(MessageSource::Security, MessageLevel::Error, message, stackTrace);
946 dispatchEvent(event);
949 DOMSelection* DOMWindow::getSelection()
951 if (!isCurrentlyDisplayedInFrame() || !m_frame)
954 return m_frame->document()->getSelection();
957 Element* DOMWindow::frameElement() const
962 return m_frame->ownerElement();
965 void DOMWindow::focus(ScriptExecutionContext* context)
970 Page* page = m_frame->page();
974 bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed() || !m_frame->settings().windowFocusRestricted();
976 ASSERT(isMainThread());
977 Document& activeDocument = downcast<Document>(*context);
978 if (opener() && opener() != this && activeDocument.domWindow() == opener())
982 // If we're a top level window, bring the window to the front.
983 if (m_frame->isMainFrame() && allowFocus)
984 page->chrome().focus();
989 // Clear the current frame's focused node if a new frame is about to be focused.
990 Frame* focusedFrame = page->focusController().focusedFrame();
991 if (focusedFrame && focusedFrame != m_frame)
992 focusedFrame->document()->setFocusedElement(0);
994 m_frame->eventHandler().focusDocumentView();
997 void DOMWindow::blur()
1002 Page* page = m_frame->page();
1006 if (m_frame->settings().windowFocusRestricted())
1009 if (!m_frame->isMainFrame())
1012 page->chrome().unfocus();
1015 void DOMWindow::close(ScriptExecutionContext* context)
1020 Page* page = m_frame->page();
1024 if (!m_frame->isMainFrame())
1028 ASSERT(isMainThread());
1029 if (!downcast<Document>(*context).canNavigate(m_frame))
1033 bool allowScriptsToCloseWindows = m_frame->settings().allowScriptsToCloseWindows();
1035 if (!(page->openedByDOM() || page->backForward().count() <= 1 || allowScriptsToCloseWindows)) {
1036 console()->addMessage(MessageSource::JS, MessageLevel::Warning, ASCIILiteral("Can't close the window since it was not opened by JavaScript"));
1040 if (!m_frame->loader().shouldClose())
1043 page->setIsClosing();
1044 page->chrome().closeWindowSoon();
1047 void DOMWindow::print()
1052 Page* page = m_frame->page();
1056 // Pages are not allowed to bring up a modal print dialog during BeforeUnload dispatch.
1057 if (page->isAnyFrameHandlingBeforeUnloadEvent()) {
1058 printErrorMessage("Use of window.print is not allowed during beforeunload event dispatch.");
1062 if (m_frame->loader().activeDocumentLoader()->isLoading()) {
1063 m_shouldPrintWhenFinishedLoading = true;
1066 m_shouldPrintWhenFinishedLoading = false;
1067 page->chrome().print(m_frame);
1070 void DOMWindow::stop()
1075 // We must check whether the load is complete asynchronously, because we might still be parsing
1076 // the document until the callstack unwinds.
1077 m_frame->loader().stopForUserCancel(true);
1080 void DOMWindow::alert(const String& message)
1085 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1086 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1087 printErrorMessage("Use of window.alert is not allowed during beforeunload event dispatch.");
1091 m_frame->document()->updateStyleIfNeeded();
1093 Page* page = m_frame->page();
1097 page->chrome().runJavaScriptAlert(m_frame, message);
1100 bool DOMWindow::confirm(const String& message)
1105 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1106 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1107 printErrorMessage("Use of window.confirm is not allowed during beforeunload event dispatch.");
1111 m_frame->document()->updateStyleIfNeeded();
1113 Page* page = m_frame->page();
1117 return page->chrome().runJavaScriptConfirm(m_frame, message);
1120 String DOMWindow::prompt(const String& message, const String& defaultValue)
1125 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
1126 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
1127 printErrorMessage("Use of window.prompt is not allowed during beforeunload event dispatch.");
1131 m_frame->document()->updateStyleIfNeeded();
1133 Page* page = m_frame->page();
1138 if (page->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
1144 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
1146 if (stringToEncode.isNull())
1149 if (!stringToEncode.containsOnlyLatin1()) {
1150 ec = INVALID_CHARACTER_ERR;
1154 return base64Encode(stringToEncode.latin1());
1157 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
1159 if (encodedString.isNull())
1162 if (!encodedString.containsOnlyLatin1()) {
1163 ec = INVALID_CHARACTER_ERR;
1168 if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacterOrExcessPadding)) {
1169 ec = INVALID_CHARACTER_ERR;
1173 return String(out.data(), out.size());
1176 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1178 if (!isCurrentlyDisplayedInFrame())
1181 // FIXME (13016): Support wholeWord, searchInFrames and showDialog.
1182 FindOptions options = (backwards ? Backwards : 0) | (caseSensitive ? 0 : CaseInsensitive) | (wrap ? WrapAround : 0);
1183 return m_frame->editor().findString(string, options);
1186 bool DOMWindow::offscreenBuffering() const
1191 int DOMWindow::outerHeight() const
1199 Page* page = m_frame->page();
1203 return static_cast<int>(page->chrome().windowRect().height());
1207 int DOMWindow::outerWidth() const
1215 Page* page = m_frame->page();
1219 return static_cast<int>(page->chrome().windowRect().width());
1223 int DOMWindow::innerHeight() const
1228 FrameView* view = m_frame->view();
1232 return view->mapFromLayoutToCSSUnits(static_cast<int>(view->unobscuredContentRectIncludingScrollbars().height()));
1235 int DOMWindow::innerWidth() const
1240 FrameView* view = m_frame->view();
1244 return view->mapFromLayoutToCSSUnits(static_cast<int>(view->unobscuredContentRectIncludingScrollbars().width()));
1247 int DOMWindow::screenX() const
1252 Page* page = m_frame->page();
1256 return static_cast<int>(page->chrome().windowRect().x());
1259 int DOMWindow::screenY() const
1264 Page* page = m_frame->page();
1268 return static_cast<int>(page->chrome().windowRect().y());
1271 int DOMWindow::scrollX() const
1276 FrameView* view = m_frame->view();
1280 int scrollX = view->contentsScrollPosition().x();
1284 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1286 return view->mapFromLayoutToCSSUnits(view->contentsScrollPosition().x());
1289 int DOMWindow::scrollY() const
1294 FrameView* view = m_frame->view();
1298 int scrollY = view->contentsScrollPosition().y();
1302 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1304 return view->mapFromLayoutToCSSUnits(view->contentsScrollPosition().y());
1307 bool DOMWindow::closed() const
1312 unsigned DOMWindow::length() const
1314 if (!isCurrentlyDisplayedInFrame())
1317 return m_frame->tree().scopedChildCount();
1320 String DOMWindow::name() const
1325 return m_frame->tree().name();
1328 void DOMWindow::setName(const String& string)
1333 m_frame->tree().setName(string);
1336 void DOMWindow::setStatus(const String& string)
1343 Page* page = m_frame->page();
1347 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1348 page->chrome().setStatusbarText(m_frame, m_status);
1351 void DOMWindow::setDefaultStatus(const String& string)
1353 m_defaultStatus = string;
1358 Page* page = m_frame->page();
1362 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1363 page->chrome().setStatusbarText(m_frame, m_defaultStatus);
1366 DOMWindow* DOMWindow::self() const
1371 return m_frame->document()->domWindow();
1374 DOMWindow* DOMWindow::opener() const
1379 Frame* opener = m_frame->loader().opener();
1383 return opener->document()->domWindow();
1386 DOMWindow* DOMWindow::parent() const
1391 Frame* parent = m_frame->tree().parent();
1393 return parent->document()->domWindow();
1395 return m_frame->document()->domWindow();
1398 DOMWindow* DOMWindow::top() const
1403 Page* page = m_frame->page();
1407 return m_frame->tree().top().document()->domWindow();
1410 Document* DOMWindow::document() const
1412 ScriptExecutionContext* context = ContextDestructionObserver::scriptExecutionContext();
1413 return downcast<Document>(context);
1416 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1418 if (!isCurrentlyDisplayedInFrame())
1421 m_media = StyleMedia::create(m_frame);
1422 return m_media.get();
1425 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* element, const String& pseudoElt) const
1430 return CSSComputedStyleDeclaration::create(element, false, pseudoElt);
1433 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement, bool authorOnly) const
1435 if (!isCurrentlyDisplayedInFrame())
1438 unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
1439 CSSSelector::PseudoElementType pseudoType = CSSSelector::parsePseudoElementType(pseudoElement.substringSharingImpl(colonStart));
1440 if (pseudoType == CSSSelector::PseudoElementUnknown && !pseudoElement.isEmpty())
1443 unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
1445 rulesToInclude |= StyleResolver::UAAndUserCSSRules;
1446 if (m_frame->settings().crossOriginCheckInGetMatchedCSSRulesDisabled())
1447 rulesToInclude |= StyleResolver::CrossOriginCSSRules;
1449 PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
1451 auto matchedRules = m_frame->document()->ensureStyleResolver().pseudoStyleRulesForElement(element, pseudoId, rulesToInclude);
1452 if (matchedRules.isEmpty())
1455 RefPtr<StaticCSSRuleList> ruleList = StaticCSSRuleList::create();
1456 for (unsigned i = 0; i < matchedRules.size(); ++i)
1457 ruleList->rules().append(matchedRules[i]->createCSSOMWrapper());
1459 return ruleList.release();
1462 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1470 document()->updateLayoutIgnorePendingStylesheets();
1472 FloatPoint pagePoint(p->x(), p->y());
1473 pagePoint = node->convertToPage(pagePoint);
1474 return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1477 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1485 document()->updateLayoutIgnorePendingStylesheets();
1487 FloatPoint nodePoint(p->x(), p->y());
1488 nodePoint = node->convertFromPage(nodePoint);
1489 return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1492 double DOMWindow::devicePixelRatio() const
1497 Page* page = m_frame->page();
1501 return page->deviceScaleFactor();
1504 void DOMWindow::scrollBy(int x, int y) const
1506 if (!isCurrentlyDisplayedInFrame())
1509 document()->updateLayoutIgnorePendingStylesheets();
1511 FrameView* view = m_frame->view();
1515 IntSize scaledOffset(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
1516 view->setContentsScrollPosition(view->contentsScrollPosition() + scaledOffset);
1519 void DOMWindow::scrollTo(int x, int y) const
1521 if (!isCurrentlyDisplayedInFrame())
1524 RefPtr<FrameView> view = m_frame->view();
1528 if (!x && !y && view->contentsScrollPosition() == IntPoint(0, 0))
1531 document()->updateLayoutIgnorePendingStylesheets();
1533 IntPoint layoutPos(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
1534 view->setContentsScrollPosition(layoutPos);
1537 bool DOMWindow::allowedToChangeWindowGeometry() const
1541 if (!m_frame->page())
1543 if (!m_frame->isMainFrame())
1545 // Prevent web content from tricking the user into initiating a drag.
1546 if (m_frame->eventHandler().mousePressed())
1551 void DOMWindow::moveBy(float x, float y) const
1553 if (!allowedToChangeWindowGeometry())
1556 Page* page = m_frame->page();
1557 FloatRect fr = page->chrome().windowRect();
1558 FloatRect update = fr;
1560 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1561 page->chrome().setWindowRect(adjustWindowRect(page, update));
1564 void DOMWindow::moveTo(float x, float y) const
1566 if (!allowedToChangeWindowGeometry())
1569 Page* page = m_frame->page();
1570 FloatRect fr = page->chrome().windowRect();
1571 FloatRect sr = screenAvailableRect(page->mainFrame().view());
1572 fr.setLocation(sr.location());
1573 FloatRect update = fr;
1575 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1576 page->chrome().setWindowRect(adjustWindowRect(page, update));
1579 void DOMWindow::resizeBy(float x, float y) const
1581 if (!allowedToChangeWindowGeometry())
1584 Page* page = m_frame->page();
1585 FloatRect fr = page->chrome().windowRect();
1586 FloatSize dest = fr.size() + FloatSize(x, y);
1587 FloatRect update(fr.location(), dest);
1588 page->chrome().setWindowRect(adjustWindowRect(page, update));
1591 void DOMWindow::resizeTo(float width, float height) const
1593 if (!allowedToChangeWindowGeometry())
1596 Page* page = m_frame->page();
1597 FloatRect fr = page->chrome().windowRect();
1598 FloatSize dest = FloatSize(width, height);
1599 FloatRect update(fr.location(), dest);
1600 page->chrome().setWindowRect(adjustWindowRect(page, update));
1603 int DOMWindow::setTimeout(std::unique_ptr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1605 ScriptExecutionContext* context = scriptExecutionContext();
1607 ec = INVALID_ACCESS_ERR;
1610 return DOMTimer::install(*context, WTF::move(action), timeout, true);
1613 void DOMWindow::clearTimeout(int timeoutId)
1617 Document* document = m_frame->document();
1618 if (timeoutId > 0 && document) {
1619 DOMTimer* timer = document->findTimeout(timeoutId);
1620 if (timer && WebThreadContainsObservedContentModifier(timer)) {
1621 WebThreadRemoveObservedContentModifier(timer);
1623 if (!WebThreadCountOfObservedContentModifiers()) {
1624 if (Page* page = m_frame->page())
1625 page->chrome().client().observedContentChange(m_frame);
1631 ScriptExecutionContext* context = scriptExecutionContext();
1634 DOMTimer::removeById(*context, timeoutId);
1637 int DOMWindow::setInterval(std::unique_ptr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1639 ScriptExecutionContext* context = scriptExecutionContext();
1641 ec = INVALID_ACCESS_ERR;
1644 return DOMTimer::install(*context, WTF::move(action), timeout, false);
1647 void DOMWindow::clearInterval(int timeoutId)
1649 ScriptExecutionContext* context = scriptExecutionContext();
1652 DOMTimer::removeById(*context, timeoutId);
1655 #if ENABLE(REQUEST_ANIMATION_FRAME)
1656 int DOMWindow::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
1658 callback->m_useLegacyTimeBase = false;
1659 if (Document* d = document())
1660 return d->requestAnimationFrame(callback);
1664 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
1666 callback->m_useLegacyTimeBase = true;
1667 if (Document* d = document())
1668 return d->requestAnimationFrame(callback);
1672 void DOMWindow::cancelAnimationFrame(int id)
1674 if (Document* d = document())
1675 d->cancelAnimationFrame(id);
1679 DOMWindowCSS* DOMWindow::css()
1682 m_css = DOMWindowCSS::create();
1686 static void didAddStorageEventListener(DOMWindow* window)
1688 // Creating these WebCore::Storage objects informs the system that we'd like to receive
1689 // notifications about storage events that might be triggered in other processes. Rather
1690 // than subscribe to these notifications explicitly, we subscribe to them implicitly to
1691 // simplify the work done by the system.
1692 window->localStorage(IGNORE_EXCEPTION);
1693 window->sessionStorage(IGNORE_EXCEPTION);
1696 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1698 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1701 if (Document* document = this->document()) {
1702 document->addListenerTypeIfNeeded(eventType);
1703 if (eventNames().isWheelEventType(eventType))
1704 document->didAddWheelEventHandler(*document);
1705 else if (eventNames().isTouchEventType(eventType))
1706 document->didAddTouchEventHandler(*document);
1707 else if (eventType == eventNames().storageEvent)
1708 didAddStorageEventListener(this);
1711 if (eventType == eventNames().unloadEvent)
1712 addUnloadEventListener(this);
1713 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1714 addBeforeUnloadEventListener(this);
1715 #if ENABLE(DEVICE_ORIENTATION)
1717 else if (eventType == eventNames().devicemotionEvent && document())
1718 document()->deviceMotionController()->addDeviceEventListener(this);
1719 else if (eventType == eventNames().deviceorientationEvent && document())
1720 document()->deviceOrientationController()->addDeviceEventListener(this);
1722 else if (eventType == eventNames().devicemotionEvent && RuntimeEnabledFeatures::sharedFeatures().deviceMotionEnabled()) {
1723 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1724 controller->addDeviceEventListener(this);
1725 } else if (eventType == eventNames().deviceorientationEvent && RuntimeEnabledFeatures::sharedFeatures().deviceOrientationEnabled()) {
1726 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1727 controller->addDeviceEventListener(this);
1729 #endif // PLATFORM(IOS)
1730 #endif // ENABLE(DEVICE_ORIENTATION)
1732 else if (eventType == eventNames().scrollEvent)
1733 incrementScrollEventListenersCount();
1735 #if ENABLE(IOS_TOUCH_EVENTS)
1736 else if (eventNames().isTouchEventType(eventType))
1737 ++m_touchEventListenerCount;
1739 #if ENABLE(IOS_GESTURE_EVENTS)
1740 else if (eventNames().isGestureEventType(eventType))
1741 ++m_touchEventListenerCount;
1744 else if (eventNames().isGamepadEventType(eventType))
1745 incrementGamepadEventListenerCount();
1747 #if ENABLE(PROXIMITY_EVENTS)
1748 else if (eventType == eventNames().webkitdeviceproximityEvent) {
1749 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1750 controller->addDeviceEventListener(this);
1758 void DOMWindow::incrementScrollEventListenersCount()
1760 Document* document = this->document();
1761 if (++m_scrollEventListenerCount == 1 && document == &document->topDocument()) {
1762 Frame* frame = this->frame();
1763 if (frame && frame->page())
1764 frame->page()->chrome().client().setNeedsScrollNotifications(frame, true);
1768 void DOMWindow::decrementScrollEventListenersCount()
1770 Document* document = this->document();
1771 if (!--m_scrollEventListenerCount && document == &document->topDocument()) {
1772 Frame* frame = this->frame();
1773 if (frame && frame->page() && !document->inPageCache())
1774 frame->page()->chrome().client().setNeedsScrollNotifications(frame, false);
1779 void DOMWindow::resetAllGeolocationPermission()
1781 // FIXME: Remove PLATFORM(IOS)-guard once we upstream the iOS changes to Geolocation.cpp.
1782 #if ENABLE(GEOLOCATION) && PLATFORM(IOS)
1784 NavigatorGeolocation::from(m_navigator.get())->resetAllGeolocationPermission();
1788 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1790 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1793 if (Document* document = this->document()) {
1794 if (eventNames().isWheelEventType(eventType))
1795 document->didRemoveWheelEventHandler(*document);
1796 else if (eventNames().isTouchEventType(eventType))
1797 document->didRemoveTouchEventHandler(*document);
1800 if (eventType == eventNames().unloadEvent)
1801 removeUnloadEventListener(this);
1802 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1803 removeBeforeUnloadEventListener(this);
1804 #if ENABLE(DEVICE_ORIENTATION)
1806 else if (eventType == eventNames().devicemotionEvent && document())
1807 document()->deviceMotionController()->removeDeviceEventListener(this);
1808 else if (eventType == eventNames().deviceorientationEvent && document())
1809 document()->deviceOrientationController()->removeDeviceEventListener(this);
1811 else if (eventType == eventNames().devicemotionEvent) {
1812 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1813 controller->removeDeviceEventListener(this);
1814 } else if (eventType == eventNames().deviceorientationEvent) {
1815 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1816 controller->removeDeviceEventListener(this);
1818 #endif // PLATFORM(IOS)
1819 #endif // ENABLE(DEVICE_ORIENTATION)
1821 else if (eventType == eventNames().scrollEvent)
1822 decrementScrollEventListenersCount();
1824 #if ENABLE(IOS_TOUCH_EVENTS)
1825 else if (eventNames().isTouchEventType(eventType)) {
1826 ASSERT(m_touchEventListenerCount > 0);
1827 --m_touchEventListenerCount;
1830 #if ENABLE(IOS_GESTURE_EVENTS)
1831 else if (eventNames().isGestureEventType(eventType)) {
1832 ASSERT(m_touchEventListenerCount > 0);
1833 --m_touchEventListenerCount;
1837 else if (eventNames().isGamepadEventType(eventType))
1838 decrementGamepadEventListenerCount();
1840 #if ENABLE(PROXIMITY_EVENTS)
1841 else if (eventType == eventNames().webkitdeviceproximityEvent) {
1842 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1843 controller->removeDeviceEventListener(this);
1850 void DOMWindow::dispatchLoadEvent()
1852 RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1853 if (m_frame && m_frame->loader().documentLoader() && !m_frame->loader().documentLoader()->timing().loadEventStart()) {
1854 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1855 // the event, so protect it to prevent writing the end time into freed memory.
1856 RefPtr<DocumentLoader> documentLoader = m_frame->loader().documentLoader();
1857 DocumentLoadTiming& timing = documentLoader->timing();
1858 timing.markLoadEventStart();
1859 dispatchEvent(loadEvent, document());
1860 timing.markLoadEventEnd();
1862 dispatchEvent(loadEvent, document());
1864 // For load events, send a separate load event to the enclosing frame only.
1865 // This is a DOM extension and is independent of bubbling/capturing rules of
1867 Element* ownerElement = m_frame ? m_frame->ownerElement() : nullptr;
1869 ownerElement->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
1871 InspectorInstrumentation::loadEventFired(frame());
1874 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1876 Ref<EventTarget> protect(*this);
1877 RefPtr<Event> event = prpEvent;
1879 // Pausing a page may trigger pagehide and pageshow events. WebCore also implicitly fires these
1880 // events when closing a WebView. Here we keep track of the state of the page to prevent duplicate,
1881 // unbalanced events per the definition of the pageshow event:
1882 // <http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pageshow>.
1883 if (event->eventInterface() == PageTransitionEventInterfaceType) {
1884 if (event->type() == eventNames().pageshowEvent) {
1885 if (m_lastPageStatus == PageStatusShown)
1886 return true; // Event was previously dispatched; do not fire a duplicate event.
1887 m_lastPageStatus = PageStatusShown;
1888 } else if (event->type() == eventNames().pagehideEvent) {
1889 if (m_lastPageStatus == PageStatusHidden)
1890 return true; // Event was previously dispatched; do not fire a duplicate event.
1891 m_lastPageStatus = PageStatusHidden;
1895 event->setTarget(prpTarget ? prpTarget : this);
1896 event->setCurrentTarget(this);
1897 event->setEventPhase(Event::AT_TARGET);
1899 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, *this);
1901 bool result = fireEventListeners(event.get());
1903 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1908 void DOMWindow::removeAllEventListeners()
1910 EventTarget::removeAllEventListeners();
1912 #if ENABLE(DEVICE_ORIENTATION)
1914 if (Document* document = this->document()) {
1915 document->deviceMotionController()->removeAllDeviceEventListeners(this);
1916 document->deviceOrientationController()->removeAllDeviceEventListeners(this);
1919 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
1920 controller->removeAllDeviceEventListeners(this);
1921 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
1922 controller->removeAllDeviceEventListeners(this);
1923 #endif // PLATFORM(IOS)
1924 #endif // ENABLE(DEVICE_ORIENTATION)
1927 if (m_scrollEventListenerCount) {
1928 m_scrollEventListenerCount = 1;
1929 decrementScrollEventListenersCount();
1933 #if ENABLE(IOS_TOUCH_EVENTS) || ENABLE(IOS_GESTURE_EVENTS)
1934 m_touchEventListenerCount = 0;
1937 #if ENABLE(TOUCH_EVENTS)
1938 if (Document* document = this->document())
1939 document->didRemoveEventTargetNode(*document);
1942 #if ENABLE(PROXIMITY_EVENTS)
1943 if (DeviceProximityController* controller = DeviceProximityController::from(page()))
1944 controller->removeAllDeviceEventListeners(this);
1947 removeAllUnloadEventListeners(this);
1948 removeAllBeforeUnloadEventListeners(this);
1951 void DOMWindow::captureEvents()
1956 void DOMWindow::releaseEvents()
1961 void DOMWindow::finishedLoading()
1963 if (m_shouldPrintWhenFinishedLoading) {
1964 m_shouldPrintWhenFinishedLoading = false;
1969 void DOMWindow::setLocation(const String& urlString, DOMWindow& activeWindow, DOMWindow& firstWindow, SetLocationLocking locking)
1971 if (!isCurrentlyDisplayedInFrame())
1974 Document* activeDocument = activeWindow.document();
1975 if (!activeDocument)
1978 if (!activeDocument->canNavigate(m_frame))
1981 Frame* firstFrame = firstWindow.frame();
1985 URL completedURL = firstFrame->document()->completeURL(urlString);
1986 if (completedURL.isNull())
1989 if (isInsecureScriptAccess(activeWindow, completedURL))
1992 // We want a new history item if we are processing a user gesture.
1993 LockHistory lockHistory = (locking != LockHistoryBasedOnGestureState || !ScriptController::processingUserGesture()) ? LockHistory::Yes : LockHistory::No;
1994 LockBackForwardList lockBackForwardList = (locking != LockHistoryBasedOnGestureState) ? LockBackForwardList::Yes : LockBackForwardList::No;
1995 m_frame->navigationScheduler().scheduleLocationChange(activeDocument->securityOrigin(),
1996 // FIXME: What if activeDocument()->frame() is 0?
1997 completedURL, activeDocument->frame()->loader().outgoingReferrer(),
1998 lockHistory, lockBackForwardList);
2001 void DOMWindow::printErrorMessage(const String& message)
2003 if (message.isEmpty())
2006 if (PageConsoleClient* pageConsole = console())
2007 pageConsole->addMessage(MessageSource::JS, MessageLevel::Error, message);
2010 String DOMWindow::crossDomainAccessErrorMessage(const DOMWindow& activeWindow)
2012 const URL& activeWindowURL = activeWindow.document()->url();
2013 if (activeWindowURL.isNull())
2016 ASSERT(!activeWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()));
2018 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
2019 SecurityOrigin* activeOrigin = activeWindow.document()->securityOrigin();
2020 SecurityOrigin* targetOrigin = document()->securityOrigin();
2021 String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
2023 // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
2024 URL activeURL = activeWindow.document()->url();
2025 URL targetURL = document()->url();
2026 if (document()->isSandboxed(SandboxOrigin) || activeWindow.document()->isSandboxed(SandboxOrigin)) {
2027 message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL).get().toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL).get().toString() + "\". ";
2028 if (document()->isSandboxed(SandboxOrigin) && activeWindow.document()->isSandboxed(SandboxOrigin))
2029 return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
2030 if (document()->isSandboxed(SandboxOrigin))
2031 return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
2032 return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
2035 // 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:'.
2036 if (targetOrigin->protocol() != activeOrigin->protocol())
2037 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";
2039 // 'document.domain' errors.
2040 if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
2041 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.";
2042 if (activeOrigin->domainWasSetInDOM())
2043 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.";
2044 if (targetOrigin->domainWasSetInDOM())
2045 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.";
2048 return message + "Protocols, domains, and ports must match.";
2051 bool DOMWindow::isInsecureScriptAccess(DOMWindow& activeWindow, const String& urlString)
2053 if (!protocolIsJavaScript(urlString))
2056 // If this DOMWindow isn't currently active in the Frame, then there's no
2057 // way we should allow the access.
2058 // FIXME: Remove this check if we're able to disconnect DOMWindow from
2059 // Frame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
2060 if (isCurrentlyDisplayedInFrame()) {
2061 // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
2062 if (&activeWindow == this)
2065 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
2066 // Can we name the SecurityOrigin function better to make this more clear?
2067 if (activeWindow.document()->securityOrigin()->canAccess(document()->securityOrigin()))
2071 printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
2075 PassRefPtr<Frame> DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures, DOMWindow& activeWindow, Frame* firstFrame, Frame* openerFrame, std::function<void (DOMWindow&)> prepareDialogFunction)
2077 Frame* activeFrame = activeWindow.frame();
2079 URL completedURL = urlString.isEmpty() ? URL(ParsedURLString, emptyString()) : firstFrame->document()->completeURL(urlString);
2080 if (!completedURL.isEmpty() && !completedURL.isValid()) {
2081 // Don't expose client code to invalid URLs.
2082 activeWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.string() + "'.\n");
2086 // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
2087 String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->loader().outgoingReferrer());
2089 ResourceRequest request(completedURL, referrer);
2090 FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader().outgoingOrigin());
2091 FrameLoadRequest frameRequest(activeWindow.document()->securityOrigin(), request, frameName);
2093 // We pass the opener frame for the lookupFrame in case the active frame is different from
2094 // the opener frame, and the name references a frame relative to the opener frame.
2096 RefPtr<Frame> newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
2100 newFrame->loader().setOpener(openerFrame);
2101 newFrame->page()->setOpenedByDOM();
2103 if (newFrame->document()->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
2104 return newFrame.release();
2106 if (prepareDialogFunction)
2107 prepareDialogFunction(*newFrame->document()->domWindow());
2110 newFrame->loader().changeLocation(activeWindow.document()->securityOrigin(), completedURL, referrer, LockHistory::No, LockBackForwardList::No);
2111 else if (!urlString.isEmpty()) {
2112 LockHistory lockHistory = ScriptController::processingUserGesture() ? LockHistory::No : LockHistory::Yes;
2113 newFrame->navigationScheduler().scheduleLocationChange(activeWindow.document()->securityOrigin(), completedURL, referrer, lockHistory, LockBackForwardList::No);
2116 // Navigating the new frame could result in it being detached from its page by a navigation policy delegate.
2117 if (!newFrame->page())
2120 return newFrame.release();
2123 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
2124 DOMWindow& activeWindow, DOMWindow& firstWindow)
2126 if (!isCurrentlyDisplayedInFrame())
2128 Document* activeDocument = activeWindow.document();
2129 if (!activeDocument)
2131 Frame* firstFrame = firstWindow.frame();
2135 #if ENABLE(CONTENT_EXTENSIONS)
2137 && firstFrame->document()
2138 && firstFrame->mainFrame().page()
2139 && firstFrame->mainFrame().page()->userContentController()
2140 && firstFrame->mainFrame().document()) {
2141 ResourceLoadInfo resourceLoadInfo = {firstFrame->document()->completeURL(urlString), firstFrame->mainFrame().document()->url(), ResourceType::Popup};
2142 Vector<ContentExtensions::Action> actions = firstFrame->mainFrame().page()->userContentController()->actionsForResourceLoad(resourceLoadInfo);
2143 for (const ContentExtensions::Action& action : actions) {
2144 if (action.type() == ContentExtensions::ActionType::BlockLoad)
2150 if (!firstWindow.allowPopUp()) {
2151 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
2152 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
2153 if (frameName.isEmpty() || !m_frame->tree().find(frameName))
2157 // Get the target frame for the special cases of _top and _parent.
2158 // In those cases, we schedule a location change right now and return early.
2159 Frame* targetFrame = nullptr;
2160 if (frameName == "_top")
2161 targetFrame = &m_frame->tree().top();
2162 else if (frameName == "_parent") {
2163 if (Frame* parent = m_frame->tree().parent())
2164 targetFrame = parent;
2166 targetFrame = m_frame;
2169 if (!activeDocument->canNavigate(targetFrame))
2172 URL completedURL = firstFrame->document()->completeURL(urlString);
2174 if (targetFrame->document()->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
2175 return targetFrame->document()->domWindow();
2177 if (urlString.isEmpty())
2178 return targetFrame->document()->domWindow();
2180 // For whatever reason, Firefox uses the first window rather than the active window to
2181 // determine the outgoing referrer. We replicate that behavior here.
2182 LockHistory lockHistory = ScriptController::processingUserGesture() ? LockHistory::No : LockHistory::Yes;
2183 targetFrame->navigationScheduler().scheduleLocationChange(activeDocument->securityOrigin(), completedURL, firstFrame->loader().outgoingReferrer(),
2184 lockHistory, LockBackForwardList::No);
2185 return targetFrame->document()->domWindow();
2188 WindowFeatures windowFeatures(windowFeaturesString);
2189 RefPtr<Frame> result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
2190 return result ? result->document()->domWindow() : nullptr;
2193 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString, DOMWindow& activeWindow, DOMWindow& firstWindow, std::function<void (DOMWindow&)> prepareDialogFunction)
2195 if (!isCurrentlyDisplayedInFrame())
2197 Frame* activeFrame = activeWindow.frame();
2200 Frame* firstFrame = firstWindow.frame();
2204 // Pages are not allowed to cause modal alerts during BeforeUnload dispatch.
2205 if (page() && page()->isAnyFrameHandlingBeforeUnloadEvent()) {
2206 printErrorMessage("Use of window.showModalDialog is not allowed during beforeunload event dispatch.");
2210 if (!canShowModalDialogNow(m_frame) || !firstWindow.allowPopUp())
2213 WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view()));
2214 RefPtr<Frame> dialogFrame = createWindow(urlString, emptyAtom, windowFeatures, activeWindow, firstFrame, m_frame, WTF::move(prepareDialogFunction));
2217 dialogFrame->page()->chrome().runModal();
2220 void DOMWindow::enableSuddenTermination()
2222 if (Page* page = this->page())
2223 page->chrome().enableSuddenTermination();
2226 void DOMWindow::disableSuddenTermination()
2228 if (Page* page = this->page())
2229 page->chrome().disableSuddenTermination();
2232 } // namespace WebCore