2 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "DOMWindow.h"
30 #include "AbstractDatabase.h"
31 #include "BackForwardController.h"
34 #include "BeforeUnloadEvent.h"
35 #include "CSSComputedStyleDeclaration.h"
36 #include "CSSRuleList.h"
37 #include "CSSStyleSelector.h"
41 #include "DOMApplicationCache.h"
42 #include "DOMSelection.h"
43 #include "DOMSettableTokenList.h"
44 #include "DOMStringList.h"
46 #include "DOMTokenList.h"
49 #include "DatabaseCallback.h"
50 #include "DeviceMotionController.h"
51 #include "DeviceOrientationController.h"
53 #include "DocumentLoader.h"
55 #include "EventException.h"
56 #include "EventListener.h"
57 #include "EventNames.h"
58 #include "ExceptionCode.h"
59 #include "FloatRect.h"
61 #include "FrameLoadRequest.h"
62 #include "FrameLoader.h"
63 #include "FrameTree.h"
64 #include "FrameView.h"
65 #include "HTMLFrameOwnerElement.h"
67 #include "IDBFactory.h"
68 #include "IDBFactoryBackendInterface.h"
69 #include "InspectorInstrumentation.h"
72 #include "MediaQueryList.h"
73 #include "MediaQueryMatcher.h"
74 #include "MessageEvent.h"
75 #include "Navigator.h"
76 #include "NotificationCenter.h"
78 #include "PageGroup.h"
79 #include "PageTransitionEvent.h"
80 #include "Performance.h"
81 #include "PlatformScreen.h"
82 #include "PlatformString.h"
84 #include "SecurityOrigin.h"
85 #include "SerializedScriptValue.h"
88 #include "StorageArea.h"
89 #include "StorageNamespace.h"
90 #include "StyleMedia.h"
91 #include "SuddenTermination.h"
92 #include "WebKitPoint.h"
93 #include "WindowFeatures.h"
95 #include <wtf/CurrentTime.h>
96 #include <wtf/MathExtras.h>
97 #include <wtf/text/StringConcatenate.h>
99 #if ENABLE(FILE_SYSTEM)
100 #include "AsyncFileSystem.h"
101 #include "DOMFileSystem.h"
102 #include "ErrorCallback.h"
103 #include "FileError.h"
104 #include "FileSystemCallback.h"
105 #include "FileSystemCallbacks.h"
106 #include "LocalFileSystem.h"
109 #if ENABLE(REQUEST_ANIMATION_FRAME)
110 #include "RequestAnimationFrameCallback.h"
118 class PostMessageTimer : public TimerBase {
120 PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin)
123 , m_origin(sourceOrigin)
125 , m_channels(channels)
126 , m_targetOrigin(targetOrigin)
130 PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
132 OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
133 return MessageEvent::create(messagePorts.release(), m_message, m_origin, "", m_source);
135 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
140 m_window->postMessageTimerFired(this);
143 RefPtr<DOMWindow> m_window;
144 RefPtr<SerializedScriptValue> m_message;
146 RefPtr<DOMWindow> m_source;
147 OwnPtr<MessagePortChannelArray> m_channels;
148 RefPtr<SecurityOrigin> m_targetOrigin;
151 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
153 static DOMWindowSet& windowsWithUnloadEventListeners()
155 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
156 return windowsWithUnloadEventListeners;
159 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
161 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
162 return windowsWithBeforeUnloadEventListeners;
165 static void addUnloadEventListener(DOMWindow* domWindow)
167 DOMWindowSet& set = windowsWithUnloadEventListeners();
169 disableSuddenTermination();
173 static void removeUnloadEventListener(DOMWindow* domWindow)
175 DOMWindowSet& set = windowsWithUnloadEventListeners();
176 DOMWindowSet::iterator it = set.find(domWindow);
181 enableSuddenTermination();
184 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
186 DOMWindowSet& set = windowsWithUnloadEventListeners();
187 DOMWindowSet::iterator it = set.find(domWindow);
192 enableSuddenTermination();
195 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
197 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
199 disableSuddenTermination();
203 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
205 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
206 DOMWindowSet::iterator it = set.find(domWindow);
211 enableSuddenTermination();
214 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
216 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
217 DOMWindowSet::iterator it = set.find(domWindow);
222 enableSuddenTermination();
225 static bool allowsBeforeUnloadListeners(DOMWindow* window)
227 ASSERT_ARG(window, window);
228 Frame* frame = window->frame();
231 Page* page = frame->page();
234 return frame == page->mainFrame();
237 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
239 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
243 static bool alreadyDispatched = false;
244 ASSERT(!alreadyDispatched);
245 if (alreadyDispatched)
248 Vector<RefPtr<DOMWindow> > windows;
249 DOMWindowSet::iterator end = set.end();
250 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
251 windows.append(it->first);
253 size_t size = windows.size();
254 for (size_t i = 0; i < size; ++i) {
255 DOMWindow* window = windows[i].get();
256 if (!set.contains(window))
259 Frame* frame = window->frame();
263 if (!frame->loader()->shouldClose())
267 enableSuddenTermination();
269 alreadyDispatched = true;
274 unsigned DOMWindow::pendingUnloadEventListeners() const
276 return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
279 void DOMWindow::dispatchAllPendingUnloadEvents()
281 DOMWindowSet& set = windowsWithUnloadEventListeners();
285 static bool alreadyDispatched = false;
286 ASSERT(!alreadyDispatched);
287 if (alreadyDispatched)
290 Vector<RefPtr<DOMWindow> > windows;
291 DOMWindowSet::iterator end = set.end();
292 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
293 windows.append(it->first);
295 size_t size = windows.size();
296 for (size_t i = 0; i < size; ++i) {
297 DOMWindow* window = windows[i].get();
298 if (!set.contains(window))
301 window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
302 window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
305 enableSuddenTermination();
307 alreadyDispatched = true;
311 // 1) Validates the pending changes are not changing to NaN
312 // 2) Constrains the window rect to no smaller than 100 in each dimension and no
313 // bigger than the the float rect's dimensions.
314 // 3) Constrain window rect to within the top and left boundaries of the screen rect
315 // 4) Constraint the window rect to within the bottom and right boundaries of the
317 // 5) Translate the window rect coordinates to be within the coordinate space of
319 void DOMWindow::adjustWindowRect(const FloatRect& screen, FloatRect& window, const FloatRect& pendingChanges)
321 // Make sure we're in a valid state before adjusting dimensions.
322 ASSERT(isfinite(screen.x()));
323 ASSERT(isfinite(screen.y()));
324 ASSERT(isfinite(screen.width()));
325 ASSERT(isfinite(screen.height()));
326 ASSERT(isfinite(window.x()));
327 ASSERT(isfinite(window.y()));
328 ASSERT(isfinite(window.width()));
329 ASSERT(isfinite(window.height()));
331 // Update window values if new requested values are not NaN.
332 if (!isnan(pendingChanges.x()))
333 window.setX(pendingChanges.x());
334 if (!isnan(pendingChanges.y()))
335 window.setY(pendingChanges.y());
336 if (!isnan(pendingChanges.width()))
337 window.setWidth(pendingChanges.width());
338 if (!isnan(pendingChanges.height()))
339 window.setHeight(pendingChanges.height());
341 // Resize the window to between 100 and the screen width and height.
342 window.setWidth(min(max(100.0f, window.width()), screen.width()));
343 window.setHeight(min(max(100.0f, window.height()), screen.height()));
345 // Constrain the window position to the screen.
346 window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
347 window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
350 // FIXME: We can remove this function once V8 showModalDialog is changed to use DOMWindow.
351 void DOMWindow::parseModalDialogFeatures(const String& string, HashMap<String, String>& map)
353 WindowFeatures::parseDialogFeatures(string, map);
356 bool DOMWindow::allowPopUp(Frame* firstFrame)
360 if (ScriptController::processingUserGesture())
363 Settings* settings = firstFrame->settings();
364 return settings && settings->javaScriptCanOpenWindowsAutomatically();
367 bool DOMWindow::allowPopUp()
369 return m_frame && allowPopUp(m_frame);
372 bool DOMWindow::canShowModalDialog(const Frame* frame)
376 Page* page = frame->page();
379 return page->chrome()->canRunModal();
382 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
386 Page* page = frame->page();
389 return page->chrome()->canRunModalNow();
392 DOMWindow::DOMWindow(Frame* frame)
393 : m_shouldPrintWhenFinishedLoading(false)
398 DOMWindow::~DOMWindow()
401 m_frame->clearFormerDOMWindow(this);
403 removeAllUnloadEventListeners(this);
404 removeAllBeforeUnloadEventListeners(this);
407 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
412 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
414 return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
417 void DOMWindow::disconnectFrame()
423 void DOMWindow::clear()
426 m_screen->disconnectFrame();
430 m_selection->disconnectFrame();
434 m_history->disconnectFrame();
440 m_locationbar->disconnectFrame();
444 m_menubar->disconnectFrame();
448 m_personalbar->disconnectFrame();
452 m_scrollbars->disconnectFrame();
456 m_statusbar->disconnectFrame();
460 m_toolbar->disconnectFrame();
464 m_console->disconnectFrame();
468 m_navigator->disconnectFrame();
471 #if ENABLE(WEB_TIMING)
473 m_performance->disconnectFrame();
478 m_location->disconnectFrame();
482 m_media->disconnectFrame();
485 #if ENABLE(DOM_STORAGE)
486 if (m_sessionStorage)
487 m_sessionStorage->disconnectFrame();
488 m_sessionStorage = 0;
491 m_localStorage->disconnectFrame();
495 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
496 if (m_applicationCache)
497 m_applicationCache->disconnectFrame();
498 m_applicationCache = 0;
501 #if ENABLE(NOTIFICATIONS)
503 m_notifications->disconnectFrame();
507 #if ENABLE(INDEXED_DATABASE)
512 #if ENABLE(ORIENTATION_EVENTS)
513 int DOMWindow::orientation() const
518 return m_frame->orientation();
522 Screen* DOMWindow::screen() const
525 m_screen = Screen::create(m_frame);
526 return m_screen.get();
529 History* DOMWindow::history() const
532 m_history = History::create(m_frame);
533 return m_history.get();
536 Crypto* DOMWindow::crypto() const
539 m_crypto = Crypto::create();
540 return m_crypto.get();
543 BarInfo* DOMWindow::locationbar() const
546 m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
547 return m_locationbar.get();
550 BarInfo* DOMWindow::menubar() const
553 m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
554 return m_menubar.get();
557 BarInfo* DOMWindow::personalbar() const
560 m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
561 return m_personalbar.get();
564 BarInfo* DOMWindow::scrollbars() const
567 m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
568 return m_scrollbars.get();
571 BarInfo* DOMWindow::statusbar() const
574 m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
575 return m_statusbar.get();
578 BarInfo* DOMWindow::toolbar() const
581 m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
582 return m_toolbar.get();
585 Console* DOMWindow::console() const
588 m_console = Console::create(m_frame);
589 return m_console.get();
592 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
593 DOMApplicationCache* DOMWindow::applicationCache() const
595 if (!m_applicationCache)
596 m_applicationCache = DOMApplicationCache::create(m_frame);
597 return m_applicationCache.get();
601 Navigator* DOMWindow::navigator() const
604 m_navigator = Navigator::create(m_frame);
605 return m_navigator.get();
608 #if ENABLE(WEB_TIMING)
609 Performance* DOMWindow::performance() const
612 m_performance = Performance::create(m_frame);
613 return m_performance.get();
617 Location* DOMWindow::location() const
620 m_location = Location::create(m_frame);
621 return m_location.get();
624 #if ENABLE(DOM_STORAGE)
625 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
627 if (m_sessionStorage)
628 return m_sessionStorage.get();
630 Document* document = this->document();
634 if (!document->securityOrigin()->canAccessLocalStorage()) {
639 Page* page = document->page();
643 RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
644 InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), false, m_frame);
646 m_sessionStorage = Storage::create(m_frame, storageArea.release());
647 return m_sessionStorage.get();
650 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
653 return m_localStorage.get();
655 Document* document = this->document();
659 if (!document->securityOrigin()->canAccessLocalStorage()) {
664 Page* page = document->page();
668 if (!page->settings()->localStorageEnabled())
671 RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
672 InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), true, m_frame);
674 m_localStorage = Storage::create(m_frame, storageArea.release());
675 return m_localStorage.get();
679 #if ENABLE(NOTIFICATIONS)
680 NotificationCenter* DOMWindow::webkitNotifications() const
683 return m_notifications.get();
685 Document* document = this->document();
689 Page* page = document->page();
693 NotificationPresenter* provider = page->chrome()->notificationPresenter();
695 m_notifications = NotificationCenter::create(document, provider);
697 return m_notifications.get();
701 void DOMWindow::pageDestroyed()
703 #if ENABLE(NOTIFICATIONS)
704 // Clearing Notifications requests involves accessing the client so it must be done
705 // before the frame is detached.
707 m_notifications->disconnectFrame();
712 #if ENABLE(INDEXED_DATABASE)
713 IDBFactory* DOMWindow::webkitIndexedDB() const
716 return m_idbFactory.get();
718 Document* document = this->document();
722 // FIXME: See if access is allowed.
724 Page* page = document->page();
728 // FIXME: See if indexedDatabase access is allowed.
730 m_idbFactory = IDBFactory::create(page->group().idbFactory());
731 return m_idbFactory.get();
735 #if ENABLE(FILE_SYSTEM)
736 void DOMWindow::requestFileSystem(int type, long long size, PassRefPtr<FileSystemCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
738 Document* document = this->document();
742 if (!AsyncFileSystem::isAvailable() || !document->securityOrigin()->canAccessFileSystem()) {
743 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
747 AsyncFileSystem::Type fileSystemType = static_cast<AsyncFileSystem::Type>(type);
748 if (fileSystemType != AsyncFileSystem::Temporary && fileSystemType != AsyncFileSystem::Persistent) {
749 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
753 LocalFileSystem::localFileSystem().requestFileSystem(document, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, document), false);
756 COMPILE_ASSERT(static_cast<int>(DOMWindow::TEMPORARY) == static_cast<int>(AsyncFileSystem::Temporary), enum_mismatch);
757 COMPILE_ASSERT(static_cast<int>(DOMWindow::PERSISTENT) == static_cast<int>(AsyncFileSystem::Persistent), enum_mismatch);
761 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
763 MessagePortArray ports;
766 postMessage(message, &ports, targetOrigin, source, ec);
769 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
774 // Compute the target origin. We need to do this synchronously in order
775 // to generate the SYNTAX_ERR exception correctly.
776 RefPtr<SecurityOrigin> target;
777 if (targetOrigin != "*") {
778 target = SecurityOrigin::createFromString(targetOrigin);
779 if (target->isEmpty()) {
785 OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
789 // Capture the source of the message. We need to do this synchronously
790 // in order to capture the source of the message correctly.
791 Document* sourceDocument = source->document();
794 String sourceOrigin = sourceDocument->securityOrigin()->toString();
796 // Schedule the message.
797 PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get());
798 timer->startOneShot(0);
801 void DOMWindow::postMessageTimerFired(PostMessageTimer* t)
803 OwnPtr<PostMessageTimer> timer(t);
808 if (timer->targetOrigin()) {
809 // Check target origin now since the target document may have changed since the simer was scheduled.
810 if (!timer->targetOrigin()->isSameSchemeHostPort(document()->securityOrigin())) {
811 String message = makeString("Unable to post message to ", timer->targetOrigin()->toString(),
812 ". Recipient has origin ", document()->securityOrigin()->toString(), ".\n");
813 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 0, String());
818 dispatchEvent(timer->event(document()));
821 DOMSelection* DOMWindow::getSelection()
824 m_selection = DOMSelection::create(m_frame);
825 return m_selection.get();
828 Element* DOMWindow::frameElement() const
833 return m_frame->ownerElement();
836 void DOMWindow::focus()
841 Page* page = m_frame->page();
845 // If we're a top level window, bring the window to the front.
846 if (m_frame == page->mainFrame())
847 page->chrome()->focus();
852 m_frame->eventHandler()->focusDocumentView();
855 void DOMWindow::blur()
860 Page* page = m_frame->page();
864 if (m_frame != page->mainFrame())
867 page->chrome()->unfocus();
870 void DOMWindow::close(ScriptExecutionContext* context)
875 Page* page = m_frame->page();
879 if (m_frame != page->mainFrame())
883 ASSERT(WTF::isMainThread());
884 Frame* activeFrame = static_cast<Document*>(context)->frame();
888 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
892 Settings* settings = m_frame->settings();
893 bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
895 if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
898 if (!m_frame->loader()->shouldClose())
901 page->chrome()->closeWindowSoon();
904 void DOMWindow::print()
909 Page* page = m_frame->page();
913 if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
914 m_shouldPrintWhenFinishedLoading = true;
917 m_shouldPrintWhenFinishedLoading = false;
918 page->chrome()->print(m_frame);
921 void DOMWindow::stop()
926 // We must check whether the load is complete asynchronously, because we might still be parsing
927 // the document until the callstack unwinds.
928 m_frame->loader()->stopForUserCancel(true);
931 void DOMWindow::alert(const String& message)
936 m_frame->document()->updateStyleIfNeeded();
938 Page* page = m_frame->page();
942 page->chrome()->runJavaScriptAlert(m_frame, message);
945 bool DOMWindow::confirm(const String& message)
950 m_frame->document()->updateStyleIfNeeded();
952 Page* page = m_frame->page();
956 return page->chrome()->runJavaScriptConfirm(m_frame, message);
959 String DOMWindow::prompt(const String& message, const String& defaultValue)
964 m_frame->document()->updateStyleIfNeeded();
966 Page* page = m_frame->page();
971 if (page->chrome()->runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
977 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
979 if (stringToEncode.isNull())
982 if (!stringToEncode.containsOnlyLatin1()) {
983 ec = INVALID_CHARACTER_ERR;
987 return base64Encode(stringToEncode.latin1());
990 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
992 if (encodedString.isNull())
995 if (!encodedString.containsOnlyLatin1()) {
996 ec = INVALID_CHARACTER_ERR;
1001 if (!base64Decode(encodedString, out, FailOnInvalidCharacter)) {
1002 ec = INVALID_CHARACTER_ERR;
1006 return String(out.data(), out.size());
1009 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1014 // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1015 return m_frame->editor()->findString(string, !backwards, caseSensitive, wrap, false);
1018 bool DOMWindow::offscreenBuffering() const
1023 int DOMWindow::outerHeight() const
1028 Page* page = m_frame->page();
1032 return static_cast<int>(page->chrome()->windowRect().height());
1035 int DOMWindow::outerWidth() const
1040 Page* page = m_frame->page();
1044 return static_cast<int>(page->chrome()->windowRect().width());
1047 int DOMWindow::innerHeight() const
1052 FrameView* view = m_frame->view();
1056 #if PLATFORM(ANDROID)
1057 return static_cast<int>(view->actualHeight() / m_frame->pageZoomFactor());
1059 return static_cast<int>(view->height() / m_frame->pageZoomFactor());
1063 int DOMWindow::innerWidth() const
1068 FrameView* view = m_frame->view();
1072 #if PLATFORM(ANDROID)
1073 return static_cast<int>(view->actualWidth() / m_frame->pageZoomFactor());
1075 return static_cast<int>(view->width() / m_frame->pageZoomFactor());
1079 int DOMWindow::screenX() const
1084 Page* page = m_frame->page();
1088 return static_cast<int>(page->chrome()->windowRect().x());
1091 int DOMWindow::screenY() const
1096 Page* page = m_frame->page();
1100 return static_cast<int>(page->chrome()->windowRect().y());
1103 int DOMWindow::scrollX() const
1108 FrameView* view = m_frame->view();
1112 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1114 #if PLATFORM(ANDROID)
1115 return static_cast<int>(view->actualScrollX() / m_frame->pageZoomFactor());
1117 return static_cast<int>(view->scrollX() / m_frame->pageZoomFactor());
1121 int DOMWindow::scrollY() const
1126 FrameView* view = m_frame->view();
1130 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1132 #if PLATFORM(ANDROID)
1133 return static_cast<int>(view->actualScrollY() / m_frame->pageZoomFactor());
1135 return static_cast<int>(view->scrollY() / m_frame->pageZoomFactor());
1139 bool DOMWindow::closed() const
1144 unsigned DOMWindow::length() const
1149 return m_frame->tree()->childCount();
1152 String DOMWindow::name() const
1157 return m_frame->tree()->name();
1160 void DOMWindow::setName(const String& string)
1165 m_frame->tree()->setName(string);
1168 void DOMWindow::setStatus(const String& string)
1175 Page* page = m_frame->page();
1179 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1180 page->chrome()->setStatusbarText(m_frame, m_status);
1183 void DOMWindow::setDefaultStatus(const String& string)
1185 m_defaultStatus = string;
1190 Page* page = m_frame->page();
1194 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1195 page->chrome()->setStatusbarText(m_frame, m_defaultStatus);
1198 DOMWindow* DOMWindow::self() const
1203 return m_frame->domWindow();
1206 DOMWindow* DOMWindow::opener() const
1211 Frame* opener = m_frame->loader()->opener();
1215 return opener->domWindow();
1218 DOMWindow* DOMWindow::parent() const
1223 Frame* parent = m_frame->tree()->parent(true);
1225 return parent->domWindow();
1227 return m_frame->domWindow();
1230 DOMWindow* DOMWindow::top() const
1235 Page* page = m_frame->page();
1239 return m_frame->tree()->top(true)->domWindow();
1242 Document* DOMWindow::document() const
1244 // FIXME: This function shouldn't need a frame to work.
1248 // The m_frame pointer is not zeroed out when the window is put into b/f cache, so it can hold an unrelated document/window pair.
1249 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
1250 if (m_frame->domWindow() != this)
1253 ASSERT(m_frame->document());
1254 return m_frame->document();
1257 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1260 m_media = StyleMedia::create(m_frame);
1261 return m_media.get();
1264 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1269 return computedStyle(elt, false, pseudoElt);
1272 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* elt, const String&, bool authorOnly) const
1277 Settings* settings = m_frame->settings();
1278 return m_frame->document()->styleSelector()->styleRulesForElement(elt, authorOnly, false, settings && settings->crossOriginCheckInGetMatchedCSSRulesDisabled() ? AllCSSRules : SameOriginCSSRulesOnly);
1281 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1286 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1288 FloatPoint pagePoint(p->x(), p->y());
1289 pagePoint = node->convertToPage(pagePoint);
1290 return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1293 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1298 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1300 FloatPoint nodePoint(p->x(), p->y());
1301 nodePoint = node->convertFromPage(nodePoint);
1302 return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1305 double DOMWindow::devicePixelRatio() const
1310 Page* page = m_frame->page();
1314 return page->chrome()->scaleFactor();
1317 #if ENABLE(DATABASE)
1318 PassRefPtr<Database> DOMWindow::openDatabase(const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)
1320 RefPtr<Database> database = 0;
1321 if (m_frame && AbstractDatabase::isAvailable() && m_frame->document()->securityOrigin()->canAccessDatabase())
1322 database = Database::openDatabase(m_frame->document(), name, version, displayName, estimatedSize, creationCallback, ec);
1324 if (!database && !ec)
1331 void DOMWindow::scrollBy(int x, int y) const
1336 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1338 RefPtr<FrameView> view = m_frame->view();
1342 view->scrollBy(IntSize(x, y));
1345 void DOMWindow::scrollTo(int x, int y) const
1350 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1352 RefPtr<FrameView> view = m_frame->view();
1356 int zoomedX = static_cast<int>(x * m_frame->pageZoomFactor());
1357 int zoomedY = static_cast<int>(y * m_frame->pageZoomFactor());
1358 view->setScrollPosition(IntPoint(zoomedX, zoomedY));
1361 void DOMWindow::moveBy(float x, float y) const
1366 Page* page = m_frame->page();
1370 if (m_frame != page->mainFrame())
1373 FloatRect fr = page->chrome()->windowRect();
1374 FloatRect update = fr;
1376 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1377 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1378 page->chrome()->setWindowRect(fr);
1381 void DOMWindow::moveTo(float x, float y) const
1386 Page* page = m_frame->page();
1390 if (m_frame != page->mainFrame())
1393 FloatRect fr = page->chrome()->windowRect();
1394 FloatRect sr = screenAvailableRect(page->mainFrame()->view());
1395 fr.setLocation(sr.location());
1396 FloatRect update = fr;
1398 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1399 adjustWindowRect(sr, fr, update);
1400 page->chrome()->setWindowRect(fr);
1403 void DOMWindow::resizeBy(float x, float y) const
1408 Page* page = m_frame->page();
1412 if (m_frame != page->mainFrame())
1415 FloatRect fr = page->chrome()->windowRect();
1416 FloatSize dest = fr.size() + FloatSize(x, y);
1417 FloatRect update(fr.location(), dest);
1418 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1419 page->chrome()->setWindowRect(fr);
1422 void DOMWindow::resizeTo(float width, float height) const
1427 Page* page = m_frame->page();
1431 if (m_frame != page->mainFrame())
1434 FloatRect fr = page->chrome()->windowRect();
1435 FloatSize dest = FloatSize(width, height);
1436 FloatRect update(fr.location(), dest);
1437 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1438 page->chrome()->setWindowRect(fr);
1441 int DOMWindow::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1443 ScriptExecutionContext* context = scriptExecutionContext();
1445 ec = INVALID_ACCESS_ERR;
1448 return DOMTimer::install(context, action, timeout, true);
1451 void DOMWindow::clearTimeout(int timeoutId)
1453 ScriptExecutionContext* context = scriptExecutionContext();
1456 DOMTimer::removeById(context, timeoutId);
1459 int DOMWindow::setInterval(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1461 ScriptExecutionContext* context = scriptExecutionContext();
1463 ec = INVALID_ACCESS_ERR;
1466 return DOMTimer::install(context, action, timeout, false);
1469 void DOMWindow::clearInterval(int timeoutId)
1471 ScriptExecutionContext* context = scriptExecutionContext();
1474 DOMTimer::removeById(context, timeoutId);
1477 #if ENABLE(REQUEST_ANIMATION_FRAME)
1478 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* e)
1480 if (Document* d = document())
1481 return d->webkitRequestAnimationFrame(callback, e);
1485 void DOMWindow::webkitCancelRequestAnimationFrame(int id)
1487 if (Document* d = document())
1488 d->webkitCancelRequestAnimationFrame(id);
1492 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1494 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1497 if (Document* document = this->document())
1498 document->addListenerTypeIfNeeded(eventType);
1500 if (eventType == eventNames().unloadEvent)
1501 addUnloadEventListener(this);
1502 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1503 addBeforeUnloadEventListener(this);
1504 #if ENABLE(DEVICE_ORIENTATION)
1505 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1506 frame()->page()->deviceMotionController()->addListener(this);
1507 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1508 frame()->page()->deviceOrientationController()->addListener(this);
1514 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1516 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1519 if (eventType == eventNames().unloadEvent)
1520 removeUnloadEventListener(this);
1521 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1522 removeBeforeUnloadEventListener(this);
1523 #if ENABLE(DEVICE_ORIENTATION)
1524 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1525 frame()->page()->deviceMotionController()->removeListener(this);
1526 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1527 frame()->page()->deviceOrientationController()->removeListener(this);
1533 void DOMWindow::dispatchLoadEvent()
1535 RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1536 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1537 // the event, so protect it to prevent writing the end time into freed memory.
1538 if (RefPtr<DocumentLoader> documentLoader = m_frame ? m_frame->loader()->documentLoader() : 0) {
1539 DocumentLoadTiming* timing = documentLoader->timing();
1540 dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1542 dispatchEvent(loadEvent, document());
1544 // For load events, send a separate load event to the enclosing frame only.
1545 // This is a DOM extension and is independent of bubbling/capturing rules of
1547 Element* ownerElement = document()->ownerElement();
1549 RefPtr<Event> ownerEvent = Event::create(eventNames().loadEvent, false, false);
1550 ownerEvent->setTarget(ownerElement);
1551 ownerElement->dispatchGenericEvent(ownerEvent.release());
1554 InspectorInstrumentation::loadEventFired(frame(), url());
1557 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1559 RefPtr<EventTarget> protect = this;
1560 RefPtr<Event> event = prpEvent;
1562 event->setTarget(prpTarget ? prpTarget : this);
1563 event->setCurrentTarget(this);
1564 event->setEventPhase(Event::AT_TARGET);
1566 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1568 bool result = fireEventListeners(event.get());
1570 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1575 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1579 *startTime = currentTime();
1580 dispatchEvent(event, target);
1581 *endTime = currentTime();
1584 void DOMWindow::removeAllEventListeners()
1586 EventTarget::removeAllEventListeners();
1588 #if ENABLE(DEVICE_ORIENTATION)
1589 if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1590 frame()->page()->deviceMotionController()->removeAllListeners(this);
1591 if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1592 frame()->page()->deviceOrientationController()->removeAllListeners(this);
1595 removeAllUnloadEventListeners(this);
1596 removeAllBeforeUnloadEventListeners(this);
1599 void DOMWindow::captureEvents()
1604 void DOMWindow::releaseEvents()
1609 void DOMWindow::finishedLoading()
1611 if (m_shouldPrintWhenFinishedLoading) {
1612 m_shouldPrintWhenFinishedLoading = false;
1617 EventTargetData* DOMWindow::eventTargetData()
1619 return &m_eventTargetData;
1622 EventTargetData* DOMWindow::ensureEventTargetData()
1624 return &m_eventTargetData;
1627 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1628 void DOMWindow::clearDOMStorage()
1630 if (m_sessionStorage)
1631 m_sessionStorage->disconnectFrame();
1632 m_sessionStorage = 0;
1635 m_localStorage->disconnectFrame();
1640 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
1645 Frame* activeFrame = activeWindow->frame();
1649 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
1652 Frame* firstFrame = firstWindow->frame();
1656 KURL completedURL = firstFrame->document()->completeURL(urlString);
1657 if (completedURL.isNull())
1660 if (isInsecureScriptAccess(activeWindow, urlString))
1663 // We want a new history item if we are processing a user gesture.
1664 m_frame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1665 completedURL, activeFrame->loader()->outgoingReferrer(),
1666 locking != LockHistoryBasedOnGestureState || !activeFrame->script()->anyPageIsProcessingUserGesture(),
1667 locking != LockHistoryBasedOnGestureState);
1670 void DOMWindow::printErrorMessage(const String& message)
1672 if (message.isEmpty())
1675 Settings* settings = m_frame->settings();
1678 if (settings->privateBrowsingEnabled())
1681 // FIXME: Add arguments so that we can provide a correct source URL and line number.
1682 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1685 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
1687 const KURL& activeWindowURL = activeWindow->url();
1688 if (activeWindowURL.isNull())
1691 // FIXME: This error message should contain more specifics of why the same origin check has failed.
1692 // Perhaps we should involve the security origin object in composing it.
1693 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1694 return makeString("Unsafe JavaScript attempt to access frame with URL ", m_url.string(),
1695 " from frame with URL ", activeWindowURL.string(), ". Domains, protocols and ports must match.\n");
1698 bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
1700 if (!protocolIsJavaScript(urlString))
1703 // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
1704 if (activeWindow == this)
1707 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1708 // Can we name the SecurityOrigin function better to make this more clear?
1709 if (activeWindow->securityOrigin()->canAccess(securityOrigin()))
1712 printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
1716 Frame* DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
1717 DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, PrepareDialogFunction function, void* functionContext)
1719 Frame* activeFrame = activeWindow->frame();
1721 // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1722 String referrer = firstFrame->loader()->outgoingReferrer();
1724 KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1725 ResourceRequest request(completedURL, referrer);
1726 FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1727 FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1729 // We pass the opener frame for the lookupFrame in case the active frame is different from
1730 // the opener frame, and the name references a frame relative to the opener frame.
1732 Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1736 newFrame->loader()->setOpener(openerFrame);
1737 newFrame->page()->setOpenedByDOM();
1739 if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1743 function(newFrame->domWindow(), functionContext);
1746 newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1747 else if (!urlString.isEmpty()) {
1748 newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1749 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1755 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1756 DOMWindow* activeWindow, DOMWindow* firstWindow)
1760 Frame* activeFrame = activeWindow->frame();
1763 Frame* firstFrame = firstWindow->frame();
1767 if (!firstWindow->allowPopUp()) {
1768 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1769 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1770 if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1774 // Get the target frame for the special cases of _top and _parent.
1775 // In those cases, we schedule a location change right now and return early.
1776 Frame* targetFrame = 0;
1777 if (frameName == "_top")
1778 targetFrame = m_frame->tree()->top();
1779 else if (frameName == "_parent") {
1780 if (Frame* parent = m_frame->tree()->parent())
1781 targetFrame = parent;
1783 targetFrame = m_frame;
1786 if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1789 if (isInsecureScriptAccess(activeWindow, urlString))
1790 return targetFrame->domWindow();
1792 if (urlString.isEmpty())
1793 return targetFrame->domWindow();
1795 // For whatever reason, Firefox uses the first window rather than the active window to
1796 // determine the outgoing referrer. We replicate that behavior here.
1797 targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1798 firstFrame->document()->completeURL(urlString).string(),
1799 firstFrame->loader()->outgoingReferrer(),
1800 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1802 return targetFrame->domWindow();
1805 WindowFeatures windowFeatures(windowFeaturesString);
1806 FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1807 windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1808 Page* page = m_frame->page();
1809 DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1810 windowFeatures.x = windowRect.x();
1811 windowFeatures.y = windowRect.y();
1812 windowFeatures.height = windowRect.height();
1813 windowFeatures.width = windowRect.width();
1815 Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1816 return result ? result->domWindow() : 0;
1819 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1820 DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1824 Frame* activeFrame = activeWindow->frame();
1827 Frame* firstFrame = firstWindow->frame();
1831 if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1834 Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1835 activeWindow, firstFrame, m_frame, function, functionContext);
1839 dialogFrame->page()->chrome()->runModal();
1843 DOMURL* DOMWindow::webkitURL() const
1846 m_domURL = DOMURL::create(this->scriptExecutionContext());
1847 return m_domURL.get();
1851 } // namespace WebCore