2 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5 * Copyright (C) 2009 Adam Barth. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
17 * its contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "NavigationScheduler.h"
35 #include "BackForwardController.h"
36 #include "DOMWindow.h"
37 #include "DocumentLoader.h"
39 #include "FormState.h"
40 #include "FormSubmission.h"
42 #include "FrameLoadRequest.h"
43 #include "FrameLoader.h"
44 #include "FrameLoaderStateMachine.h"
45 #include "HTMLFormElement.h"
46 #include "HTMLFrameOwnerElement.h"
47 #include "HistoryItem.h"
49 #include "UserGestureIndicator.h"
50 #include <wtf/CurrentTime.h>
54 unsigned NavigationDisablerForBeforeUnload::s_navigationDisableCount = 0;
56 class ScheduledNavigation {
57 WTF_MAKE_NONCOPYABLE(ScheduledNavigation); WTF_MAKE_FAST_ALLOCATED;
59 ScheduledNavigation(double delay, bool lockHistory, bool lockBackForwardList, bool wasDuringLoad, bool isLocationChange)
61 , m_lockHistory(lockHistory)
62 , m_lockBackForwardList(lockBackForwardList)
63 , m_wasDuringLoad(wasDuringLoad)
64 , m_isLocationChange(isLocationChange)
65 , m_wasUserGesture(ScriptController::processingUserGesture())
68 virtual ~ScheduledNavigation() { }
70 virtual void fire(Frame*) = 0;
72 virtual bool shouldStartTimer(Frame*) { return true; }
73 virtual void didStartTimer(Frame*, Timer<NavigationScheduler>*) { }
74 virtual void didStopTimer(Frame*, bool /* newLoadInProgress */) { }
76 double delay() const { return m_delay; }
77 bool lockHistory() const { return m_lockHistory; }
78 bool lockBackForwardList() const { return m_lockBackForwardList; }
79 bool wasDuringLoad() const { return m_wasDuringLoad; }
80 bool isLocationChange() const { return m_isLocationChange; }
81 bool wasUserGesture() const { return m_wasUserGesture; }
84 void clearUserGesture() { m_wasUserGesture = false; }
89 bool m_lockBackForwardList;
91 bool m_isLocationChange;
92 bool m_wasUserGesture;
95 class ScheduledURLNavigation : public ScheduledNavigation {
97 ScheduledURLNavigation(double delay, SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool duringLoad, bool isLocationChange)
98 : ScheduledNavigation(delay, lockHistory, lockBackForwardList, duringLoad, isLocationChange)
99 , m_securityOrigin(securityOrigin)
101 , m_referrer(referrer)
102 , m_haveToldClient(false)
106 virtual void fire(Frame* frame)
108 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
109 frame->loader()->changeLocation(m_securityOrigin.get(), KURL(ParsedURLString, m_url), m_referrer, lockHistory(), lockBackForwardList(), false);
112 virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
114 if (m_haveToldClient)
116 m_haveToldClient = true;
118 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
119 frame->loader()->clientRedirected(KURL(ParsedURLString, m_url), delay(), currentTime() + timer->nextFireInterval(), lockBackForwardList());
122 virtual void didStopTimer(Frame* frame, bool newLoadInProgress)
124 if (!m_haveToldClient)
127 // Do not set a UserGestureIndicator because
128 // clientRedirectCancelledOrFinished() is also called from many places
129 // inside FrameLoader, where the gesture state is not set and is in
130 // fact unavailable. We need to be consistent with them, otherwise the
131 // gesture state will sometimes be set and sometimes not within
132 // dispatchDidCancelClientRedirect().
133 frame->loader()->clientRedirectCancelledOrFinished(newLoadInProgress);
136 SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); }
137 String url() const { return m_url; }
138 String referrer() const { return m_referrer; }
141 RefPtr<SecurityOrigin> m_securityOrigin;
144 bool m_haveToldClient;
147 class ScheduledRedirect : public ScheduledURLNavigation {
149 ScheduledRedirect(double delay, SecurityOrigin* securityOrigin, const String& url, bool lockHistory, bool lockBackForwardList)
150 : ScheduledURLNavigation(delay, securityOrigin, url, String(), lockHistory, lockBackForwardList, false, false)
155 virtual bool shouldStartTimer(Frame* frame) { return frame->loader()->allAncestorsAreComplete(); }
157 virtual void fire(Frame* frame)
159 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
160 bool refresh = equalIgnoringFragmentIdentifier(frame->document()->url(), KURL(ParsedURLString, url()));
161 frame->loader()->changeLocation(securityOrigin(), KURL(ParsedURLString, url()), referrer(), lockHistory(), lockBackForwardList(), refresh);
165 class ScheduledLocationChange : public ScheduledURLNavigation {
167 ScheduledLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool duringLoad)
168 : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, lockHistory, lockBackForwardList, duringLoad, true) { }
171 class ScheduledRefresh : public ScheduledURLNavigation {
173 ScheduledRefresh(SecurityOrigin* securityOrigin, const String& url, const String& referrer)
174 : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, true, true, false, true)
178 virtual void fire(Frame* frame)
180 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
181 frame->loader()->changeLocation(securityOrigin(), KURL(ParsedURLString, url()), referrer(), lockHistory(), lockBackForwardList(), true);
185 class ScheduledHistoryNavigation : public ScheduledNavigation {
187 explicit ScheduledHistoryNavigation(int historySteps)
188 : ScheduledNavigation(0, false, false, false, true)
189 , m_historySteps(historySteps)
193 virtual void fire(Frame* frame)
195 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
197 if (!m_historySteps) {
198 // Special case for go(0) from a frame -> reload only the frame
199 // To follow Firefox and IE's behavior, history reload can only navigate the self frame.
200 frame->loader()->urlSelected(frame->document()->url(), "_self", 0, lockHistory(), lockBackForwardList(), SendReferrer);
203 // go(i!=0) from a frame navigates into the history of the frame only,
204 // in both IE and NS (but not in Mozilla). We can't easily do that.
205 frame->page()->backForward()->goBackOrForward(m_historySteps);
212 class ScheduledFormSubmission : public ScheduledNavigation {
214 ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList, bool duringLoad)
215 : ScheduledNavigation(0, submission->lockHistory(), lockBackForwardList, duringLoad, true)
216 , m_submission(submission)
217 , m_haveToldClient(false)
219 ASSERT(m_submission->state());
222 virtual void fire(Frame* frame)
224 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
226 // The submitForm function will find a target frame before using the redirection timer.
227 // Now that the timer has fired, we need to repeat the security check which normally is done when
228 // selecting a target, in case conditions have changed. Other code paths avoid this by targeting
229 // without leaving a time window. If we fail the check just silently drop the form submission.
230 Frame* requestingFrame = m_submission->state()->sourceFrame();
231 if (!requestingFrame->loader()->shouldAllowNavigation(frame))
233 FrameLoadRequest frameRequest(requestingFrame->document()->securityOrigin());
234 m_submission->populateFrameLoadRequest(frameRequest);
235 frame->loader()->loadFrameRequest(frameRequest, lockHistory(), lockBackForwardList(), m_submission->event(), m_submission->state(), SendReferrer);
238 virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
240 if (m_haveToldClient)
242 m_haveToldClient = true;
244 UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
245 frame->loader()->clientRedirected(m_submission->requestURL(), delay(), currentTime() + timer->nextFireInterval(), lockBackForwardList());
248 virtual void didStopTimer(Frame* frame, bool newLoadInProgress)
250 if (!m_haveToldClient)
253 // Do not set a UserGestureIndicator because
254 // clientRedirectCancelledOrFinished() is also called from many places
255 // inside FrameLoader, where the gesture state is not set and is in
256 // fact unavailable. We need to be consistent with them, otherwise the
257 // gesture state will sometimes be set and sometimes not within
258 // dispatchDidCancelClientRedirect().
259 frame->loader()->clientRedirectCancelledOrFinished(newLoadInProgress);
263 RefPtr<FormSubmission> m_submission;
264 bool m_haveToldClient;
267 NavigationScheduler::NavigationScheduler(Frame* frame)
269 , m_timer(this, &NavigationScheduler::timerFired)
273 NavigationScheduler::~NavigationScheduler()
277 bool NavigationScheduler::redirectScheduledDuringLoad()
279 return m_redirect && m_redirect->wasDuringLoad();
282 bool NavigationScheduler::locationChangePending()
284 return m_redirect && m_redirect->isLocationChange();
287 void NavigationScheduler::clear()
293 inline bool NavigationScheduler::shouldScheduleNavigation() const
295 return m_frame->page();
298 inline bool NavigationScheduler::shouldScheduleNavigation(const String& url) const
300 return shouldScheduleNavigation() && (protocolIsJavaScript(url) || NavigationDisablerForBeforeUnload::isNavigationAllowed());
303 void NavigationScheduler::scheduleRedirect(double delay, const String& url)
305 if (!shouldScheduleNavigation(url))
307 if (delay < 0 || delay > INT_MAX / 1000)
312 // We want a new back/forward list item if the refresh timeout is > 1 second.
313 if (!m_redirect || delay <= m_redirect->delay())
314 schedule(adoptPtr(new ScheduledRedirect(delay, m_frame->document()->securityOrigin(), url, true, delay <= 1)));
317 bool NavigationScheduler::mustLockBackForwardList(Frame* targetFrame)
319 // Non-user navigation before the page has finished firing onload should not create a new back/forward item.
320 // See https://webkit.org/b/42861 for the original motivation for this.
321 if (!ScriptController::processingUserGesture() && targetFrame->loader()->documentLoader() && !targetFrame->loader()->documentLoader()->wasOnloadHandled())
324 // Navigation of a subframe during loading of an ancestor frame does not create a new back/forward item.
325 // The definition of "during load" is any time before all handlers for the load event have been run.
326 // See https://bugs.webkit.org/show_bug.cgi?id=14957 for the original motivation for this.
327 for (Frame* ancestor = targetFrame->tree()->parent(); ancestor; ancestor = ancestor->tree()->parent()) {
328 Document* document = ancestor->document();
329 if (!ancestor->loader()->isComplete() || (document && document->processingLoadEvent()))
335 void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList)
337 if (!shouldScheduleNavigation(url))
342 lockBackForwardList = lockBackForwardList || mustLockBackForwardList(m_frame);
344 FrameLoader* loader = m_frame->loader();
346 // If the URL we're going to navigate to is the same as the current one, except for the
347 // fragment part, we don't need to schedule the location change.
348 KURL parsedURL(ParsedURLString, url);
349 if (parsedURL.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(m_frame->document()->url(), parsedURL)) {
350 loader->changeLocation(securityOrigin, m_frame->document()->completeURL(url), referrer, lockHistory, lockBackForwardList);
354 // Handle a location change of a page with no document as a special case.
355 // This may happen when a frame changes the location of another frame.
356 bool duringLoad = !loader->stateMachine()->committedFirstRealDocumentLoad();
358 schedule(adoptPtr(new ScheduledLocationChange(securityOrigin, url, referrer, lockHistory, lockBackForwardList, duringLoad)));
361 void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
363 ASSERT(m_frame->page());
365 // FIXME: Do we need special handling for form submissions where the URL is the same
366 // as the current one except for the fragment part? See scheduleLocationChange above.
368 // Handle a location change of a page with no document as a special case.
369 // This may happen when a frame changes the location of another frame.
370 bool duringLoad = !m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad();
372 // If this is a child frame and the form submission was triggered by a script, lock the back/forward list
373 // to match IE and Opera.
374 // See https://bugs.webkit.org/show_bug.cgi?id=32383 for the original motivation for this.
375 bool lockBackForwardList = mustLockBackForwardList(m_frame)
376 || (submission->state()->formSubmissionTrigger() == SubmittedByJavaScript
377 && m_frame->tree()->parent() && !ScriptController::processingUserGesture());
379 schedule(adoptPtr(new ScheduledFormSubmission(submission, lockBackForwardList, duringLoad)));
382 void NavigationScheduler::scheduleRefresh()
384 if (!shouldScheduleNavigation())
386 const KURL& url = m_frame->document()->url();
390 schedule(adoptPtr(new ScheduledRefresh(m_frame->document()->securityOrigin(), url.string(), m_frame->loader()->outgoingReferrer())));
393 void NavigationScheduler::scheduleHistoryNavigation(int steps)
395 if (!shouldScheduleNavigation())
398 // Invalid history navigations (such as history.forward() during a new load) have the side effect of cancelling any scheduled
399 // redirects. We also avoid the possibility of cancelling the current load by avoiding the scheduled redirection altogether.
400 BackForwardController* backForward = m_frame->page()->backForward();
401 if (steps > backForward->forwardCount() || -steps > backForward->backCount()) {
406 // In all other cases, schedule the history traversal to occur asynchronously.
407 schedule(adoptPtr(new ScheduledHistoryNavigation(steps)));
410 void NavigationScheduler::timerFired(Timer<NavigationScheduler>*)
412 if (!m_frame->page())
414 if (m_frame->page()->defersLoading())
417 OwnPtr<ScheduledNavigation> redirect(m_redirect.release());
418 redirect->fire(m_frame);
421 void NavigationScheduler::schedule(PassOwnPtr<ScheduledNavigation> redirect)
423 ASSERT(m_frame->page());
425 // If a redirect was scheduled during a load, then stop the current load.
426 // Otherwise when the current load transitions from a provisional to a
427 // committed state, pending redirects may be cancelled.
428 if (redirect->wasDuringLoad()) {
429 if (DocumentLoader* provisionalDocumentLoader = m_frame->loader()->provisionalDocumentLoader())
430 provisionalDocumentLoader->stopLoading();
431 m_frame->loader()->stopLoading(UnloadEventPolicyUnloadAndPageHide);
435 m_redirect = redirect;
437 if (!m_frame->loader()->isComplete() && m_redirect->isLocationChange())
438 m_frame->loader()->completed();
443 void NavigationScheduler::startTimer()
448 ASSERT(m_frame->page());
449 if (m_timer.isActive())
451 if (!m_redirect->shouldStartTimer(m_frame))
454 m_timer.startOneShot(m_redirect->delay());
455 m_redirect->didStartTimer(m_frame, &m_timer);
458 void NavigationScheduler::cancel(bool newLoadInProgress)
462 OwnPtr<ScheduledNavigation> redirect(m_redirect.release());
464 redirect->didStopTimer(m_frame, newLoadInProgress);
467 } // namespace WebCore