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"
40 #include "DOMApplicationCache.h"
41 #include "DOMSelection.h"
42 #include "DOMSettableTokenList.h"
43 #include "DOMStringList.h"
45 #include "DOMTokenList.h"
47 #include "DatabaseCallback.h"
48 #include "DeviceMotionController.h"
49 #include "DeviceOrientationController.h"
51 #include "DocumentLoader.h"
53 #include "EventException.h"
54 #include "EventListener.h"
55 #include "EventNames.h"
56 #include "ExceptionCode.h"
57 #include "FloatRect.h"
59 #include "FrameLoadRequest.h"
60 #include "FrameLoader.h"
61 #include "FrameTree.h"
62 #include "FrameView.h"
63 #include "HTMLFrameOwnerElement.h"
65 #include "IDBFactory.h"
66 #include "IDBFactoryBackendInterface.h"
67 #include "InspectorController.h"
68 #include "InspectorInstrumentation.h"
71 #include "MediaQueryList.h"
72 #include "MediaQueryMatcher.h"
73 #include "MessageEvent.h"
74 #include "Navigator.h"
75 #include "NotificationCenter.h"
77 #include "PageGroup.h"
78 #include "PageTransitionEvent.h"
79 #include "Performance.h"
80 #include "PlatformScreen.h"
81 #include "PlatformString.h"
83 #include "SecurityOrigin.h"
84 #include "SerializedScriptValue.h"
87 #include "StorageArea.h"
88 #include "StorageNamespace.h"
89 #include "StyleMedia.h"
90 #include "SuddenTermination.h"
91 #include "WebKitPoint.h"
92 #include "WindowFeatures.h"
94 #include <wtf/CurrentTime.h>
95 #include <wtf/MathExtras.h>
96 #include <wtf/text/StringConcatenate.h>
98 #if ENABLE(FILE_SYSTEM)
99 #include "AsyncFileSystem.h"
100 #include "DOMFileSystem.h"
101 #include "ErrorCallback.h"
102 #include "FileError.h"
103 #include "FileSystemCallback.h"
104 #include "FileSystemCallbacks.h"
105 #include "LocalFileSystem.h"
113 class PostMessageTimer : public TimerBase {
115 PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin)
118 , m_origin(sourceOrigin)
120 , m_channels(channels)
121 , m_targetOrigin(targetOrigin)
125 PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
127 OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
128 return MessageEvent::create(messagePorts.release(), m_message, m_origin, "", m_source);
130 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
135 m_window->postMessageTimerFired(this);
138 RefPtr<DOMWindow> m_window;
139 RefPtr<SerializedScriptValue> m_message;
141 RefPtr<DOMWindow> m_source;
142 OwnPtr<MessagePortChannelArray> m_channels;
143 RefPtr<SecurityOrigin> m_targetOrigin;
146 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
148 static DOMWindowSet& windowsWithUnloadEventListeners()
150 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
151 return windowsWithUnloadEventListeners;
154 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
156 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
157 return windowsWithBeforeUnloadEventListeners;
160 static void addUnloadEventListener(DOMWindow* domWindow)
162 DOMWindowSet& set = windowsWithUnloadEventListeners();
164 disableSuddenTermination();
168 static void removeUnloadEventListener(DOMWindow* domWindow)
170 DOMWindowSet& set = windowsWithUnloadEventListeners();
171 DOMWindowSet::iterator it = set.find(domWindow);
176 enableSuddenTermination();
179 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
181 DOMWindowSet& set = windowsWithUnloadEventListeners();
182 DOMWindowSet::iterator it = set.find(domWindow);
187 enableSuddenTermination();
190 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
192 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
194 disableSuddenTermination();
198 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
200 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
201 DOMWindowSet::iterator it = set.find(domWindow);
206 enableSuddenTermination();
209 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
211 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
212 DOMWindowSet::iterator it = set.find(domWindow);
217 enableSuddenTermination();
220 static bool allowsBeforeUnloadListeners(DOMWindow* window)
222 ASSERT_ARG(window, window);
223 Frame* frame = window->frame();
226 Page* page = frame->page();
229 return frame == page->mainFrame();
232 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
234 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
238 static bool alreadyDispatched = false;
239 ASSERT(!alreadyDispatched);
240 if (alreadyDispatched)
243 Vector<RefPtr<DOMWindow> > windows;
244 DOMWindowSet::iterator end = set.end();
245 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
246 windows.append(it->first);
248 size_t size = windows.size();
249 for (size_t i = 0; i < size; ++i) {
250 DOMWindow* window = windows[i].get();
251 if (!set.contains(window))
254 Frame* frame = window->frame();
258 if (!frame->loader()->shouldClose())
262 enableSuddenTermination();
264 alreadyDispatched = true;
269 unsigned DOMWindow::pendingUnloadEventListeners() const
271 return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
274 void DOMWindow::dispatchAllPendingUnloadEvents()
276 DOMWindowSet& set = windowsWithUnloadEventListeners();
280 static bool alreadyDispatched = false;
281 ASSERT(!alreadyDispatched);
282 if (alreadyDispatched)
285 Vector<RefPtr<DOMWindow> > windows;
286 DOMWindowSet::iterator end = set.end();
287 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
288 windows.append(it->first);
290 size_t size = windows.size();
291 for (size_t i = 0; i < size; ++i) {
292 DOMWindow* window = windows[i].get();
293 if (!set.contains(window))
296 window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
297 window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
300 enableSuddenTermination();
302 alreadyDispatched = true;
306 // 1) Validates the pending changes are not changing to NaN
307 // 2) Constrains the window rect to no smaller than 100 in each dimension and no
308 // bigger than the the float rect's dimensions.
309 // 3) Constrain window rect to within the top and left boundaries of the screen rect
310 // 4) Constraint the window rect to within the bottom and right boundaries of the
312 // 5) Translate the window rect coordinates to be within the coordinate space of
314 void DOMWindow::adjustWindowRect(const FloatRect& screen, FloatRect& window, const FloatRect& pendingChanges)
316 // Make sure we're in a valid state before adjusting dimensions.
317 ASSERT(isfinite(screen.x()));
318 ASSERT(isfinite(screen.y()));
319 ASSERT(isfinite(screen.width()));
320 ASSERT(isfinite(screen.height()));
321 ASSERT(isfinite(window.x()));
322 ASSERT(isfinite(window.y()));
323 ASSERT(isfinite(window.width()));
324 ASSERT(isfinite(window.height()));
326 // Update window values if new requested values are not NaN.
327 if (!isnan(pendingChanges.x()))
328 window.setX(pendingChanges.x());
329 if (!isnan(pendingChanges.y()))
330 window.setY(pendingChanges.y());
331 if (!isnan(pendingChanges.width()))
332 window.setWidth(pendingChanges.width());
333 if (!isnan(pendingChanges.height()))
334 window.setHeight(pendingChanges.height());
336 // Resize the window to between 100 and the screen width and height.
337 window.setWidth(min(max(100.0f, window.width()), screen.width()));
338 window.setHeight(min(max(100.0f, window.height()), screen.height()));
340 // Constrain the window position to the screen.
341 window.setX(max(screen.x(), min(window.x(), screen.right() - window.width())));
342 window.setY(max(screen.y(), min(window.y(), screen.bottom() - window.height())));
345 // FIXME: We can remove this function once V8 showModalDialog is changed to use DOMWindow.
346 void DOMWindow::parseModalDialogFeatures(const String& string, HashMap<String, String>& map)
348 WindowFeatures::parseDialogFeatures(string, map);
351 bool DOMWindow::allowPopUp(Frame* firstFrame)
355 if (ScriptController::processingUserGesture())
358 Settings* settings = firstFrame->settings();
359 return settings && settings->javaScriptCanOpenWindowsAutomatically();
362 bool DOMWindow::allowPopUp()
364 return m_frame && allowPopUp(m_frame);
367 bool DOMWindow::canShowModalDialog(const Frame* frame)
371 Page* page = frame->page();
374 return page->chrome()->canRunModal();
377 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
381 Page* page = frame->page();
384 return page->chrome()->canRunModalNow();
387 DOMWindow::DOMWindow(Frame* frame)
388 : m_shouldPrintWhenFinishedLoading(false)
393 DOMWindow::~DOMWindow()
396 m_frame->clearFormerDOMWindow(this);
398 removeAllUnloadEventListeners(this);
399 removeAllBeforeUnloadEventListeners(this);
402 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
407 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
409 return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
412 void DOMWindow::disconnectFrame()
418 void DOMWindow::clear()
421 m_screen->disconnectFrame();
425 m_selection->disconnectFrame();
429 m_history->disconnectFrame();
433 m_locationbar->disconnectFrame();
437 m_menubar->disconnectFrame();
441 m_personalbar->disconnectFrame();
445 m_scrollbars->disconnectFrame();
449 m_statusbar->disconnectFrame();
453 m_toolbar->disconnectFrame();
457 m_console->disconnectFrame();
461 m_navigator->disconnectFrame();
464 #if ENABLE(WEB_TIMING)
466 m_performance->disconnectFrame();
471 m_location->disconnectFrame();
475 m_media->disconnectFrame();
478 #if ENABLE(DOM_STORAGE)
479 if (m_sessionStorage)
480 m_sessionStorage->disconnectFrame();
481 m_sessionStorage = 0;
484 m_localStorage->disconnectFrame();
488 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
489 if (m_applicationCache)
490 m_applicationCache->disconnectFrame();
491 m_applicationCache = 0;
494 #if ENABLE(NOTIFICATIONS)
496 m_notifications->disconnectFrame();
500 #if ENABLE(INDEXED_DATABASE)
505 #if ENABLE(ORIENTATION_EVENTS)
506 int DOMWindow::orientation() const
511 return m_frame->orientation();
515 Screen* DOMWindow::screen() const
518 m_screen = Screen::create(m_frame);
519 return m_screen.get();
522 History* DOMWindow::history() const
525 m_history = History::create(m_frame);
526 return m_history.get();
529 BarInfo* DOMWindow::locationbar() const
532 m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
533 return m_locationbar.get();
536 BarInfo* DOMWindow::menubar() const
539 m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
540 return m_menubar.get();
543 BarInfo* DOMWindow::personalbar() const
546 m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
547 return m_personalbar.get();
550 BarInfo* DOMWindow::scrollbars() const
553 m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
554 return m_scrollbars.get();
557 BarInfo* DOMWindow::statusbar() const
560 m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
561 return m_statusbar.get();
564 BarInfo* DOMWindow::toolbar() const
567 m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
568 return m_toolbar.get();
571 Console* DOMWindow::console() const
574 m_console = Console::create(m_frame);
575 return m_console.get();
578 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
579 DOMApplicationCache* DOMWindow::applicationCache() const
581 if (!m_applicationCache)
582 m_applicationCache = DOMApplicationCache::create(m_frame);
583 return m_applicationCache.get();
587 Navigator* DOMWindow::navigator() const
590 m_navigator = Navigator::create(m_frame);
591 return m_navigator.get();
594 #if ENABLE(WEB_TIMING)
595 Performance* DOMWindow::performance() const
598 m_performance = Performance::create(m_frame);
599 return m_performance.get();
603 Location* DOMWindow::location() const
606 m_location = Location::create(m_frame);
607 return m_location.get();
610 #if ENABLE(DOM_STORAGE)
611 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
613 if (m_sessionStorage)
614 return m_sessionStorage.get();
616 Document* document = this->document();
620 if (!document->securityOrigin()->canAccessLocalStorage()) {
625 Page* page = document->page();
629 RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
630 #if ENABLE(INSPECTOR)
631 page->inspectorController()->didUseDOMStorage(storageArea.get(), false, m_frame);
634 m_sessionStorage = Storage::create(m_frame, storageArea.release());
635 return m_sessionStorage.get();
638 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
641 return m_localStorage.get();
643 Document* document = this->document();
647 if (!document->securityOrigin()->canAccessLocalStorage()) {
652 Page* page = document->page();
656 if (!page->settings()->localStorageEnabled())
659 RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
660 #if ENABLE(INSPECTOR)
661 page->inspectorController()->didUseDOMStorage(storageArea.get(), true, m_frame);
664 m_localStorage = Storage::create(m_frame, storageArea.release());
665 return m_localStorage.get();
669 #if ENABLE(NOTIFICATIONS)
670 NotificationCenter* DOMWindow::webkitNotifications() const
673 return m_notifications.get();
675 Document* document = this->document();
679 Page* page = document->page();
683 NotificationPresenter* provider = page->chrome()->notificationPresenter();
685 m_notifications = NotificationCenter::create(document, provider);
687 return m_notifications.get();
691 void DOMWindow::pageDestroyed()
693 #if ENABLE(NOTIFICATIONS)
694 // Clearing Notifications requests involves accessing the client so it must be done
695 // before the frame is detached.
697 m_notifications->disconnectFrame();
702 #if ENABLE(INDEXED_DATABASE)
703 IDBFactory* DOMWindow::webkitIndexedDB() const
706 return m_idbFactory.get();
708 Document* document = this->document();
712 // FIXME: See if access is allowed.
714 Page* page = document->page();
718 // FIXME: See if indexedDatabase access is allowed.
720 m_idbFactory = IDBFactory::create(page->group().idbFactory());
721 return m_idbFactory.get();
725 #if ENABLE(FILE_SYSTEM)
726 void DOMWindow::requestFileSystem(int type, long long size, PassRefPtr<FileSystemCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
728 Document* document = this->document();
732 if (!AsyncFileSystem::isAvailable() || !document->securityOrigin()->canAccessFileSystem()) {
733 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
737 AsyncFileSystem::Type fileSystemType = static_cast<AsyncFileSystem::Type>(type);
738 if (fileSystemType != AsyncFileSystem::Temporary && fileSystemType != AsyncFileSystem::Persistent) {
739 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
743 LocalFileSystem::localFileSystem().requestFileSystem(document, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, document), false);
746 COMPILE_ASSERT(static_cast<int>(DOMWindow::TEMPORARY) == static_cast<int>(AsyncFileSystem::Temporary), enum_mismatch);
747 COMPILE_ASSERT(static_cast<int>(DOMWindow::PERSISTENT) == static_cast<int>(AsyncFileSystem::Persistent), enum_mismatch);
751 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
753 MessagePortArray ports;
756 postMessage(message, &ports, targetOrigin, source, ec);
759 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
764 // Compute the target origin. We need to do this synchronously in order
765 // to generate the SYNTAX_ERR exception correctly.
766 RefPtr<SecurityOrigin> target;
767 if (targetOrigin != "*") {
768 target = SecurityOrigin::createFromString(targetOrigin);
769 if (target->isEmpty()) {
775 OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
779 // Capture the source of the message. We need to do this synchronously
780 // in order to capture the source of the message correctly.
781 Document* sourceDocument = source->document();
784 String sourceOrigin = sourceDocument->securityOrigin()->toString();
786 // Schedule the message.
787 PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get());
788 timer->startOneShot(0);
791 void DOMWindow::postMessageTimerFired(PostMessageTimer* t)
793 OwnPtr<PostMessageTimer> timer(t);
798 if (timer->targetOrigin()) {
799 // Check target origin now since the target document may have changed since the simer was scheduled.
800 if (!timer->targetOrigin()->isSameSchemeHostPort(document()->securityOrigin())) {
801 String message = makeString("Unable to post message to ", timer->targetOrigin()->toString(),
802 ". Recipient has origin ", document()->securityOrigin()->toString(), ".\n");
803 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 0, String());
808 dispatchEvent(timer->event(document()));
811 DOMSelection* DOMWindow::getSelection()
814 m_selection = DOMSelection::create(m_frame);
815 return m_selection.get();
818 Element* DOMWindow::frameElement() const
823 return m_frame->ownerElement();
826 void DOMWindow::focus()
831 Page* page = m_frame->page();
835 // If we're a top level window, bring the window to the front.
836 if (m_frame == page->mainFrame())
837 page->chrome()->focus();
842 m_frame->eventHandler()->focusDocumentView();
845 void DOMWindow::blur()
850 Page* page = m_frame->page();
854 if (m_frame != page->mainFrame())
857 page->chrome()->unfocus();
860 void DOMWindow::close(ScriptExecutionContext* context)
865 Page* page = m_frame->page();
869 if (m_frame != page->mainFrame())
873 ASSERT(WTF::isMainThread());
874 Frame* activeFrame = static_cast<Document*>(context)->frame();
878 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
882 Settings* settings = m_frame->settings();
883 bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
885 if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
888 if (!m_frame->loader()->shouldClose())
891 page->chrome()->closeWindowSoon();
894 void DOMWindow::print()
899 Page* page = m_frame->page();
903 if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
904 m_shouldPrintWhenFinishedLoading = true;
907 m_shouldPrintWhenFinishedLoading = false;
908 page->chrome()->print(m_frame);
911 void DOMWindow::stop()
916 // We must check whether the load is complete asynchronously, because we might still be parsing
917 // the document until the callstack unwinds.
918 m_frame->loader()->stopForUserCancel(true);
921 void DOMWindow::alert(const String& message)
926 m_frame->document()->updateStyleIfNeeded();
928 Page* page = m_frame->page();
932 page->chrome()->runJavaScriptAlert(m_frame, message);
935 bool DOMWindow::confirm(const String& message)
940 m_frame->document()->updateStyleIfNeeded();
942 Page* page = m_frame->page();
946 return page->chrome()->runJavaScriptConfirm(m_frame, message);
949 String DOMWindow::prompt(const String& message, const String& defaultValue)
954 m_frame->document()->updateStyleIfNeeded();
956 Page* page = m_frame->page();
961 if (page->chrome()->runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
967 static bool isSafeToConvertCharList(const String& string)
969 for (unsigned i = 0; i < string.length(); i++) {
970 if (string[i] > 0xFF)
977 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
979 if (stringToEncode.isNull())
982 if (!isSafeToConvertCharList(stringToEncode)) {
983 ec = INVALID_CHARACTER_ERR;
988 in.append(stringToEncode.characters(), stringToEncode.length());
991 base64Encode(in, out);
993 return String(out.data(), out.size());
996 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
998 if (encodedString.isNull())
1001 if (!isSafeToConvertCharList(encodedString)) {
1002 ec = INVALID_CHARACTER_ERR;
1007 if (!base64Decode(encodedString, out, FailOnInvalidCharacter)) {
1008 ec = INVALID_CHARACTER_ERR;
1012 return String(out.data(), out.size());
1015 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1020 // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1021 return m_frame->editor()->findString(string, !backwards, caseSensitive, wrap, false);
1024 bool DOMWindow::offscreenBuffering() const
1029 int DOMWindow::outerHeight() const
1034 Page* page = m_frame->page();
1038 return static_cast<int>(page->chrome()->windowRect().height());
1041 int DOMWindow::outerWidth() const
1046 Page* page = m_frame->page();
1050 return static_cast<int>(page->chrome()->windowRect().width());
1053 int DOMWindow::innerHeight() const
1058 FrameView* view = m_frame->view();
1062 #if PLATFORM(ANDROID)
1063 return static_cast<int>(view->actualHeight() / m_frame->pageZoomFactor());
1065 return static_cast<int>(view->height() / m_frame->pageZoomFactor());
1069 int DOMWindow::innerWidth() const
1074 FrameView* view = m_frame->view();
1078 #if PLATFORM(ANDROID)
1079 return static_cast<int>(view->actualWidth() / m_frame->pageZoomFactor());
1081 return static_cast<int>(view->width() / m_frame->pageZoomFactor());
1085 int DOMWindow::screenX() const
1090 Page* page = m_frame->page();
1094 return static_cast<int>(page->chrome()->windowRect().x());
1097 int DOMWindow::screenY() const
1102 Page* page = m_frame->page();
1106 return static_cast<int>(page->chrome()->windowRect().y());
1109 int DOMWindow::scrollX() const
1114 FrameView* view = m_frame->view();
1118 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1120 #if PLATFORM(ANDROID)
1121 return static_cast<int>(view->actualScrollX() / m_frame->pageZoomFactor());
1123 return static_cast<int>(view->scrollX() / m_frame->pageZoomFactor());
1127 int DOMWindow::scrollY() const
1132 FrameView* view = m_frame->view();
1136 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1138 #if PLATFORM(ANDROID)
1139 return static_cast<int>(view->actualScrollY() / m_frame->pageZoomFactor());
1141 return static_cast<int>(view->scrollY() / m_frame->pageZoomFactor());
1145 bool DOMWindow::closed() const
1150 unsigned DOMWindow::length() const
1155 return m_frame->tree()->childCount();
1158 String DOMWindow::name() const
1163 return m_frame->tree()->name();
1166 void DOMWindow::setName(const String& string)
1171 m_frame->tree()->setName(string);
1174 void DOMWindow::setStatus(const String& string)
1181 Page* page = m_frame->page();
1185 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1186 page->chrome()->setStatusbarText(m_frame, m_status);
1189 void DOMWindow::setDefaultStatus(const String& string)
1191 m_defaultStatus = string;
1196 Page* page = m_frame->page();
1200 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1201 page->chrome()->setStatusbarText(m_frame, m_defaultStatus);
1204 DOMWindow* DOMWindow::self() const
1209 return m_frame->domWindow();
1212 DOMWindow* DOMWindow::opener() const
1217 Frame* opener = m_frame->loader()->opener();
1221 return opener->domWindow();
1224 DOMWindow* DOMWindow::parent() const
1229 Frame* parent = m_frame->tree()->parent(true);
1231 return parent->domWindow();
1233 return m_frame->domWindow();
1236 DOMWindow* DOMWindow::top() const
1241 Page* page = m_frame->page();
1245 return m_frame->tree()->top(true)->domWindow();
1248 Document* DOMWindow::document() const
1250 // FIXME: This function shouldn't need a frame to work.
1254 // 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.
1255 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
1256 if (m_frame->domWindow() != this)
1259 ASSERT(m_frame->document());
1260 return m_frame->document();
1263 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1266 m_media = StyleMedia::create(m_frame);
1267 return m_media.get();
1270 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1275 return computedStyle(elt, false, pseudoElt);
1278 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* elt, const String&, bool authorOnly) const
1283 Settings* settings = m_frame->settings();
1284 return m_frame->document()->styleSelector()->styleRulesForElement(elt, authorOnly, false, settings && settings->crossOriginCheckInGetMatchedCSSRulesDisabled() ? AllCSSRules : SameOriginCSSRulesOnly);
1287 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1292 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1294 FloatPoint pagePoint(p->x(), p->y());
1295 pagePoint = node->convertToPage(pagePoint);
1296 return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1299 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1304 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1306 FloatPoint nodePoint(p->x(), p->y());
1307 nodePoint = node->convertFromPage(nodePoint);
1308 return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1311 double DOMWindow::devicePixelRatio() const
1316 Page* page = m_frame->page();
1320 return page->chrome()->scaleFactor();
1323 #if ENABLE(DATABASE)
1324 PassRefPtr<Database> DOMWindow::openDatabase(const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)
1326 RefPtr<Database> database = 0;
1327 if (m_frame && AbstractDatabase::isAvailable() && m_frame->document()->securityOrigin()->canAccessDatabase())
1328 database = Database::openDatabase(m_frame->document(), name, version, displayName, estimatedSize, creationCallback, ec);
1330 if (!database && !ec)
1337 void DOMWindow::scrollBy(int x, int y) const
1342 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1344 RefPtr<FrameView> view = m_frame->view();
1348 view->scrollBy(IntSize(x, y));
1351 void DOMWindow::scrollTo(int x, int y) const
1356 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1358 FrameView* view = m_frame->view();
1362 int zoomedX = static_cast<int>(x * m_frame->pageZoomFactor());
1363 int zoomedY = static_cast<int>(y * m_frame->pageZoomFactor());
1364 view->setScrollPosition(IntPoint(zoomedX, zoomedY));
1367 void DOMWindow::moveBy(float x, float y) const
1372 Page* page = m_frame->page();
1376 if (m_frame != page->mainFrame())
1379 FloatRect fr = page->chrome()->windowRect();
1380 FloatRect update = fr;
1382 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1383 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1384 page->chrome()->setWindowRect(fr);
1387 void DOMWindow::moveTo(float x, float y) const
1392 Page* page = m_frame->page();
1396 if (m_frame != page->mainFrame())
1399 FloatRect fr = page->chrome()->windowRect();
1400 FloatRect sr = screenAvailableRect(page->mainFrame()->view());
1401 fr.setLocation(sr.location());
1402 FloatRect update = fr;
1404 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1405 adjustWindowRect(sr, fr, update);
1406 page->chrome()->setWindowRect(fr);
1409 void DOMWindow::resizeBy(float x, float y) const
1414 Page* page = m_frame->page();
1418 if (m_frame != page->mainFrame())
1421 FloatRect fr = page->chrome()->windowRect();
1422 FloatSize dest = fr.size() + FloatSize(x, y);
1423 FloatRect update(fr.location(), dest);
1424 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1425 page->chrome()->setWindowRect(fr);
1428 void DOMWindow::resizeTo(float width, float height) const
1433 Page* page = m_frame->page();
1437 if (m_frame != page->mainFrame())
1440 FloatRect fr = page->chrome()->windowRect();
1441 FloatSize dest = FloatSize(width, height);
1442 FloatRect update(fr.location(), dest);
1443 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1444 page->chrome()->setWindowRect(fr);
1447 int DOMWindow::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1449 ScriptExecutionContext* context = scriptExecutionContext();
1451 ec = INVALID_ACCESS_ERR;
1454 return DOMTimer::install(context, action, timeout, true);
1457 void DOMWindow::clearTimeout(int timeoutId)
1459 ScriptExecutionContext* context = scriptExecutionContext();
1462 DOMTimer::removeById(context, timeoutId);
1465 int DOMWindow::setInterval(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1467 ScriptExecutionContext* context = scriptExecutionContext();
1469 ec = INVALID_ACCESS_ERR;
1472 return DOMTimer::install(context, action, timeout, false);
1475 void DOMWindow::clearInterval(int timeoutId)
1477 ScriptExecutionContext* context = scriptExecutionContext();
1480 DOMTimer::removeById(context, timeoutId);
1483 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1485 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1488 if (Document* document = this->document())
1489 document->addListenerTypeIfNeeded(eventType);
1491 if (eventType == eventNames().unloadEvent)
1492 addUnloadEventListener(this);
1493 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1494 addBeforeUnloadEventListener(this);
1495 #if ENABLE(DEVICE_ORIENTATION)
1496 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1497 frame()->page()->deviceMotionController()->addListener(this);
1498 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1499 frame()->page()->deviceOrientationController()->addListener(this);
1505 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1507 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1510 if (eventType == eventNames().unloadEvent)
1511 removeUnloadEventListener(this);
1512 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1513 removeBeforeUnloadEventListener(this);
1514 #if ENABLE(DEVICE_ORIENTATION)
1515 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1516 frame()->page()->deviceMotionController()->removeListener(this);
1517 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1518 frame()->page()->deviceOrientationController()->removeListener(this);
1524 void DOMWindow::dispatchLoadEvent()
1526 RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1527 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1528 // the event, so protect it to prevent writing the end time into freed memory.
1529 if (RefPtr<DocumentLoader> documentLoader = m_frame ? m_frame->loader()->documentLoader() : 0) {
1530 DocumentLoadTiming* timing = documentLoader->timing();
1531 dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1533 dispatchEvent(loadEvent, document());
1535 // For load events, send a separate load event to the enclosing frame only.
1536 // This is a DOM extension and is independent of bubbling/capturing rules of
1538 Element* ownerElement = document()->ownerElement();
1540 RefPtr<Event> ownerEvent = Event::create(eventNames().loadEvent, false, false);
1541 ownerEvent->setTarget(ownerElement);
1542 ownerElement->dispatchGenericEvent(ownerEvent.release());
1545 #if ENABLE(INSPECTOR)
1546 if (!frame() || !frame()->page())
1549 if (InspectorController* controller = frame()->page()->inspectorController())
1550 controller->mainResourceFiredLoadEvent(frame()->loader()->documentLoader(), url());
1554 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1556 RefPtr<EventTarget> protect = this;
1557 RefPtr<Event> event = prpEvent;
1559 event->setTarget(prpTarget ? prpTarget : this);
1560 event->setCurrentTarget(this);
1561 event->setEventPhase(Event::AT_TARGET);
1563 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1565 bool result = fireEventListeners(event.get());
1567 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1572 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1576 *startTime = currentTime();
1577 dispatchEvent(event, target);
1578 *endTime = currentTime();
1579 ASSERT(*endTime >= *startTime);
1582 void DOMWindow::removeAllEventListeners()
1584 EventTarget::removeAllEventListeners();
1586 #if ENABLE(DEVICE_ORIENTATION)
1587 if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1588 frame()->page()->deviceMotionController()->removeAllListeners(this);
1589 if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1590 frame()->page()->deviceOrientationController()->removeAllListeners(this);
1593 removeAllUnloadEventListeners(this);
1594 removeAllBeforeUnloadEventListeners(this);
1597 void DOMWindow::captureEvents()
1602 void DOMWindow::releaseEvents()
1607 void DOMWindow::finishedLoading()
1609 if (m_shouldPrintWhenFinishedLoading) {
1610 m_shouldPrintWhenFinishedLoading = false;
1615 EventTargetData* DOMWindow::eventTargetData()
1617 return &m_eventTargetData;
1620 EventTargetData* DOMWindow::ensureEventTargetData()
1622 return &m_eventTargetData;
1626 String DOMWindow::createObjectURL(Blob* blob)
1628 return scriptExecutionContext()->createPublicBlobURL(blob).string();
1631 void DOMWindow::revokeObjectURL(const String& blobURLString)
1633 scriptExecutionContext()->revokePublicBlobURL(KURL(KURL(), blobURLString));
1637 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1638 void DOMWindow::clearDOMStorage()
1640 if (m_sessionStorage)
1641 m_sessionStorage->disconnectFrame();
1642 m_sessionStorage = 0;
1645 m_localStorage->disconnectFrame();
1650 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
1652 Frame* activeFrame = activeWindow->frame();
1656 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
1659 Frame* firstFrame = firstWindow->frame();
1663 KURL completedURL = firstFrame->document()->completeURL(urlString);
1664 if (completedURL.isNull())
1667 if (isInsecureScriptAccess(activeWindow, urlString))
1670 // We want a new history item if we are processing a user gesture.
1671 m_frame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1672 completedURL, activeFrame->loader()->outgoingReferrer(),
1673 locking != LockHistoryBasedOnGestureState || !activeFrame->script()->anyPageIsProcessingUserGesture(),
1674 locking != LockHistoryBasedOnGestureState);
1677 void DOMWindow::printErrorMessage(const String& message)
1679 if (message.isEmpty())
1682 Settings* settings = m_frame->settings();
1685 if (settings->privateBrowsingEnabled())
1688 // FIXME: Add arguments so that we can provide a correct source URL and line number.
1689 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1692 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
1694 const KURL& activeWindowURL = activeWindow->url();
1695 if (activeWindowURL.isNull())
1698 // FIXME: This error message should contain more specifics of why the same origin check has failed.
1699 // Perhaps we should involve the security origin object in composing it.
1700 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1701 return makeString("Unsafe JavaScript attempt to access frame with URL ", m_url.string(),
1702 " from frame with URL ", activeWindowURL.string(), ". Domains, protocols and ports must match.\n");
1705 bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
1707 if (!protocolIsJavaScript(urlString))
1710 // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
1711 if (activeWindow == this)
1714 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1715 // Can we name the SecurityOrigin function better to make this more clear?
1716 if (activeWindow->securityOrigin()->canAccess(securityOrigin()))
1719 printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
1723 Frame* DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
1724 DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, PrepareDialogFunction function, void* functionContext)
1726 Frame* activeFrame = activeWindow->frame();
1728 // FIXME: It's much better for client API if a new window starts with a URL, here where we
1729 // know what URL we are going to open. Unfortunately, this code passes the empty string
1730 // for the URL, but there's a reason for that. Before loading we have to set up the opener,
1731 // openedByDOM, and dialogArguments values. Also, to decide whether to use the URL we currently
1732 // do an isInsecureScriptAccess call using the window we create, which can't be done before
1733 // creating it. We'd have to resolve all those issues to pass the URL instead of an empty string.
1735 // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1736 String referrer = firstFrame->loader()->outgoingReferrer();
1738 ResourceRequest request(KURL(), referrer);
1739 FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1740 FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1742 // We pass the opener frame for the lookupFrame in case the active frame is different from
1743 // the opener frame, and the name references a frame relative to the opener frame.
1745 Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1749 newFrame->loader()->setOpener(openerFrame);
1750 newFrame->page()->setOpenedByDOM();
1752 if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1756 function(newFrame->domWindow(), functionContext);
1758 KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1761 newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1762 else if (!urlString.isEmpty()) {
1763 newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1764 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1770 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1771 DOMWindow* activeWindow, DOMWindow* firstWindow)
1775 Frame* activeFrame = activeWindow->frame();
1778 Frame* firstFrame = firstWindow->frame();
1782 if (!firstWindow->allowPopUp()) {
1783 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1784 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1785 if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1789 // Get the target frame for the special cases of _top and _parent.
1790 // In those cases, we schedule a location change right now and return early.
1791 Frame* targetFrame = 0;
1792 if (frameName == "_top")
1793 targetFrame = m_frame->tree()->top();
1794 else if (frameName == "_parent") {
1795 if (Frame* parent = m_frame->tree()->parent())
1796 targetFrame = parent;
1798 targetFrame = m_frame;
1801 if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1804 if (isInsecureScriptAccess(activeWindow, urlString))
1805 return targetFrame->domWindow();
1807 if (urlString.isEmpty())
1808 return targetFrame->domWindow();
1810 // For whatever reason, Firefox uses the first window rather than the active window to
1811 // determine the outgoing referrer. We replicate that behavior here.
1812 targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1813 firstFrame->document()->completeURL(urlString).string(),
1814 firstFrame->loader()->outgoingReferrer(),
1815 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1817 return targetFrame->domWindow();
1820 WindowFeatures windowFeatures(windowFeaturesString);
1821 FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1822 windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1823 Page* page = m_frame->page();
1824 DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1825 windowFeatures.x = windowRect.x();
1826 windowFeatures.y = windowRect.y();
1827 windowFeatures.height = windowRect.height();
1828 windowFeatures.width = windowRect.width();
1830 Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1831 return result ? result->domWindow() : 0;
1834 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1835 DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1839 Frame* activeFrame = activeWindow->frame();
1842 Frame* firstFrame = firstWindow->frame();
1846 if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1849 Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1850 activeWindow, firstFrame, m_frame, function, functionContext);
1854 dialogFrame->page()->chrome()->runModal();
1857 } // namespace WebCore