2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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) 2008 Alp Toker <alp@atoker.com>
6 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
7 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
8 * Copyright (C) 2011 Google Inc. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
20 * its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
27 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "FrameLoader.h"
38 #include "AXObjectCache.h"
39 #include "ApplicationCacheHost.h"
40 #include "BackForwardController.h"
41 #include "BeforeUnloadEvent.h"
42 #include "CachedPage.h"
43 #include "CachedResourceLoader.h"
45 #include "ChromeClient.h"
47 #include "ContentSecurityPolicy.h"
48 #include "DOMImplementation.h"
49 #include "DOMWindow.h"
50 #include "DatabaseManager.h"
52 #include "DocumentLoadTiming.h"
53 #include "DocumentLoader.h"
55 #include "EditorClient.h"
58 #include "EventHandler.h"
59 #include "EventNames.h"
60 #include "FloatRect.h"
61 #include "FormState.h"
62 #include "FormSubmission.h"
64 #include "FrameLoadRequest.h"
65 #include "FrameLoaderClient.h"
66 #include "FrameNetworkingContext.h"
67 #include "FrameTree.h"
68 #include "FrameView.h"
69 #include "HTMLAnchorElement.h"
70 #include "HTMLFormElement.h"
71 #include "HTMLInputElement.h"
72 #include "HTMLNames.h"
73 #include "HTMLObjectElement.h"
74 #include "HTMLParserIdioms.h"
75 #include "HTTPParsers.h"
76 #include "HistoryController.h"
77 #include "HistoryItem.h"
78 #include "IconController.h"
79 #include "InspectorController.h"
80 #include "InspectorInstrumentation.h"
81 #include "LoaderStrategy.h"
83 #include "MIMETypeRegistry.h"
84 #include "MemoryCache.h"
86 #include "PageActivityAssertionToken.h"
87 #include "PageCache.h"
88 #include "PageTransitionEvent.h"
89 #include "PlatformStrategies.h"
90 #include "PluginData.h"
91 #include "PluginDatabase.h"
92 #include "PluginDocument.h"
93 #include "PolicyChecker.h"
94 #include "ProgressTracker.h"
95 #include "ResourceHandle.h"
96 #include "ResourceRequest.h"
97 #include "SchemeRegistry.h"
98 #include "ScriptCallStack.h"
99 #include "ScriptController.h"
100 #include "ScriptSourceCode.h"
101 #include "ScrollAnimator.h"
102 #include "SecurityOrigin.h"
103 #include "SecurityPolicy.h"
104 #include "SegmentedString.h"
105 #include "SerializedScriptValue.h"
106 #include "Settings.h"
107 #include "TextResourceDecoder.h"
108 #include "WindowFeatures.h"
109 #include "XMLDocumentParser.h"
110 #include <wtf/CurrentTime.h>
111 #include <wtf/StdLibExtras.h>
112 #include <wtf/text/CString.h>
113 #include <wtf/text/WTFString.h>
115 #if ENABLE(SHARED_WORKERS)
116 #include "SharedWorkerRepository.h"
120 #include "SVGDocument.h"
121 #include "SVGLocatable.h"
122 #include "SVGNames.h"
123 #include "SVGPreserveAspectRatio.h"
124 #include "SVGSVGElement.h"
125 #include "SVGViewElement.h"
126 #include "SVGViewSpec.h"
129 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
136 using namespace HTMLNames;
139 using namespace SVGNames;
142 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
143 static double storedTimeOfLastCompletedLoad;
145 bool isBackForwardLoadType(FrameLoadType type)
148 case FrameLoadTypeStandard:
149 case FrameLoadTypeReload:
150 case FrameLoadTypeReloadFromOrigin:
151 case FrameLoadTypeSame:
152 case FrameLoadTypeRedirectWithLockedBackForwardList:
153 case FrameLoadTypeReplace:
155 case FrameLoadTypeBack:
156 case FrameLoadTypeForward:
157 case FrameLoadTypeIndexedBackForward:
160 ASSERT_NOT_REACHED();
164 // This is not in the FrameLoader class to emphasize that it does not depend on
165 // private FrameLoader data, and to avoid increasing the number of public functions
166 // with access to private data. Since only this .cpp file needs it, making it
167 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
170 static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
172 return frame->document() && frame->document()->isSandboxed(mask);
175 class FrameLoader::FrameProgressTracker {
177 static PassOwnPtr<FrameProgressTracker> create(Frame* frame) { return adoptPtr(new FrameProgressTracker(frame)); }
178 ~FrameProgressTracker()
180 ASSERT(!m_inProgress || m_frame->page());
182 m_frame->page()->progress()->progressCompleted(m_frame);
185 void progressStarted()
187 ASSERT(m_frame->page());
189 m_frame->page()->progress()->progressStarted(m_frame);
193 void progressCompleted()
195 ASSERT(m_inProgress);
196 ASSERT(m_frame->page());
197 m_inProgress = false;
198 m_frame->page()->progress()->progressCompleted(m_frame);
202 FrameProgressTracker(Frame* frame)
204 , m_inProgress(false)
212 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
215 , m_policyChecker(adoptPtr(new PolicyChecker(frame)))
216 , m_history(adoptPtr(new HistoryController(frame)))
218 , m_subframeLoader(frame)
219 , m_icon(adoptPtr(new IconController(frame)))
220 , m_mixedContentChecker(frame)
221 , m_state(FrameStateProvisional)
222 , m_loadType(FrameLoadTypeStandard)
223 , m_delegateIsHandlingProvisionalLoadError(false)
224 , m_quickRedirectComing(false)
225 , m_sentRedirectNotification(false)
226 , m_inStopAllLoaders(false)
227 , m_isExecutingJavaScriptFormAction(false)
228 , m_didCallImplicitClose(true)
229 , m_wasUnloadEventEmitted(false)
230 , m_pageDismissalEventBeingDispatched(NoDismissal)
231 , m_isComplete(false)
232 , m_needsClear(false)
233 , m_checkTimer(this, &FrameLoader::checkTimerFired)
234 , m_shouldCallCheckCompleted(false)
235 , m_shouldCallCheckLoadComplete(false)
237 , m_didPerformFirstNavigation(false)
238 , m_loadingFromCachedPage(false)
239 , m_suppressOpenerInNewFrame(false)
240 , m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
241 , m_forcedSandboxFlags(SandboxNone)
245 FrameLoader::~FrameLoader()
249 HashSet<Frame*>::iterator end = m_openedFrames.end();
250 for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
251 (*it)->loader().m_opener = 0;
253 m_client->frameLoaderDestroyed();
255 if (m_networkingContext)
256 m_networkingContext->invalidate();
259 void FrameLoader::init()
261 // This somewhat odd set of steps gives the frame an initial empty document.
262 setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData()).get());
263 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
264 m_provisionalDocumentLoader->startLoadingMainResource();
265 m_frame->document()->cancelParsing();
266 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
268 m_networkingContext = m_client->createNetworkingContext();
269 m_progressTracker = FrameProgressTracker::create(m_frame);
272 void FrameLoader::setDefersLoading(bool defers)
274 if (m_documentLoader)
275 m_documentLoader->setDefersLoading(defers);
276 if (m_provisionalDocumentLoader)
277 m_provisionalDocumentLoader->setDefersLoading(defers);
278 if (m_policyDocumentLoader)
279 m_policyDocumentLoader->setDefersLoading(defers);
280 history()->setDefersLoading(defers);
283 m_frame->navigationScheduler()->startTimer();
284 startCheckCompleteTimer();
288 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
290 urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
291 0, lockHistory, lockBackForwardList, MaybeSendReferrer, ReplaceDocumentIfJavaScriptURL);
294 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer)
296 urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
297 triggeringEvent, lockHistory, lockBackForwardList, shouldSendReferrer, DoNotReplaceDocumentIfJavaScriptURL);
300 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
301 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
302 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
304 ASSERT(!m_suppressOpenerInNewFrame);
306 RefPtr<Frame> protect(m_frame);
307 FrameLoadRequest frameRequest(passedRequest);
309 if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
312 if (frameRequest.frameName().isEmpty())
313 frameRequest.setFrameName(m_frame->document()->baseTarget());
315 if (shouldSendReferrer == NeverSendReferrer)
316 m_suppressOpenerInNewFrame = true;
317 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
319 loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, shouldSendReferrer);
321 m_suppressOpenerInNewFrame = false;
324 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
326 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
328 // FIXME: Find a good spot for these.
329 ASSERT(submission->data());
330 ASSERT(submission->state());
331 ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == m_frame);
333 if (!m_frame->page())
336 if (submission->action().isEmpty())
339 if (isDocumentSandboxed(m_frame, SandboxForms)) {
340 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
341 m_frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().stringCenterEllipsizedToLength() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
345 if (protocolIsJavaScript(submission->action())) {
346 if (!m_frame->document()->contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
348 m_isExecutingJavaScriptFormAction = true;
349 m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
350 m_isExecutingJavaScriptFormAction = false;
354 Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
356 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
359 // FIXME: targetFrame can be 0 for two distinct reasons:
360 // 1. The frame was not found by name, so we should try opening a new window.
361 // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
362 // Continuing form submission makes no sense in the latter case.
363 // There is a repeat check after timer fires, so this is not a correctness issue.
365 targetFrame = m_frame;
367 submission->clearTarget();
369 if (!targetFrame->page())
372 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
374 // We do not want to submit more than one form from the same page, nor do we want to submit a single
375 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
376 // The flag is reset in each time we start handle a new mouse or key down event, and
377 // also in setView since this part may get reused for a page from the back/forward cache.
378 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
380 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
381 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
382 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
384 if (m_frame->tree()->isDescendantOf(targetFrame)) {
385 if (m_submittedFormURL == submission->requestURL())
387 m_submittedFormURL = submission->requestURL();
390 submission->data()->generateFiles(m_frame->document());
391 submission->setReferrer(outgoingReferrer());
392 submission->setOrigin(outgoingOrigin());
394 targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
397 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
399 if (m_frame->document() && m_frame->document()->parser())
400 m_frame->document()->parser()->stopParsing();
402 if (unloadEventPolicy != UnloadEventPolicyNone) {
403 if (m_frame->document()) {
404 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
405 Element* currentFocusedElement = m_frame->document()->focusedElement();
406 if (currentFocusedElement && currentFocusedElement->toInputElement())
407 currentFocusedElement->toInputElement()->endEditing();
408 if (m_pageDismissalEventBeingDispatched == NoDismissal) {
409 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
410 m_pageDismissalEventBeingDispatched = PageHideDismissal;
411 m_frame->document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
414 // FIXME: update Page Visibility state here.
415 // https://bugs.webkit.org/show_bug.cgi?id=116770
417 if (!m_frame->document()->inPageCache()) {
418 RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
419 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
420 // while dispatching the event, so protect it to prevent writing the end
421 // time into freed memory.
422 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
423 m_pageDismissalEventBeingDispatched = UnloadDismissal;
424 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
425 DocumentLoadTiming* timing = documentLoader->timing();
426 ASSERT(timing->navigationStart());
427 timing->markUnloadEventStart();
428 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
429 timing->markUnloadEventEnd();
431 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
434 m_pageDismissalEventBeingDispatched = NoDismissal;
435 if (m_frame->document())
436 m_frame->document()->updateStyleIfNeeded();
437 m_wasUnloadEventEmitted = true;
441 // Dispatching the unload event could have made m_frame->document() null.
442 if (m_frame->document() && !m_frame->document()->inPageCache()) {
443 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
444 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
445 && m_frame->document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
447 if (!keepEventListeners)
448 m_frame->document()->removeAllEventListeners();
452 m_isComplete = true; // to avoid calling completed() in finishedParsing()
453 m_didCallImplicitClose = true; // don't want that one either
455 if (m_frame->document() && m_frame->document()->parsing()) {
457 m_frame->document()->setParsing(false);
460 if (Document* doc = m_frame->document()) {
461 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
462 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
463 doc->setReadyState(Document::Complete);
465 #if ENABLE(SQL_DATABASE)
466 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
467 DatabaseManager::manager().stopDatabases(doc, 0);
471 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
472 m_frame->navigationScheduler()->cancel();
475 void FrameLoader::stop()
477 // http://bugs.webkit.org/show_bug.cgi?id=10854
478 // The frame's last ref may be removed and it will be deleted by checkCompleted().
479 RefPtr<Frame> protector(m_frame);
481 if (DocumentParser* parser = m_frame->document()->parser()) {
482 parser->stopParsing();
486 icon()->stopLoader();
489 void FrameLoader::willTransitionToCommitted()
491 // This function is called when a frame is still fully in place (not cached, not detached), but will be replaced.
493 if (m_frame->editor().hasComposition()) {
494 // The text was already present in DOM, so it's better to confirm than to cancel the composition.
495 m_frame->editor().confirmComposition();
496 if (EditorClient* editorClient = m_frame->editor().client())
497 editorClient->respondToChangedSelection(m_frame);
501 bool FrameLoader::closeURL()
503 history()->saveDocumentState();
505 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
506 Document* currentDocument = m_frame->document();
507 stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
509 m_frame->editor().clearUndoRedoOperations();
513 bool FrameLoader::didOpenURL()
515 if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
516 // A redirect was scheduled before the document was created.
517 // This can happen when one frame changes another frame's location.
521 m_frame->navigationScheduler()->cancel();
522 m_frame->editor().clearLastEditCommand();
524 m_isComplete = false;
525 m_didCallImplicitClose = false;
527 // If we are still in the process of initializing an empty document then
528 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
529 // since it may cause clients to attempt to render the frame.
530 if (!m_stateMachine.creatingInitialEmptyDocument()) {
531 DOMWindow* window = m_frame->document()->domWindow();
532 window->setStatus(String());
533 window->setDefaultStatus(String());
541 void FrameLoader::didExplicitOpen()
543 m_isComplete = false;
544 m_didCallImplicitClose = false;
546 // Calling document.open counts as committing the first real document load.
547 if (!m_stateMachine.committedFirstRealDocumentLoad())
548 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
550 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
551 // from a subsequent window.document.open / window.document.write call.
552 // Canceling redirection here works for all cases because document.open
553 // implicitly precedes document.write.
554 m_frame->navigationScheduler()->cancel();
558 void FrameLoader::cancelAndClear()
560 m_frame->navigationScheduler()->cancel();
565 clear(m_frame->document(), false);
566 m_frame->script()->updatePlatformScriptObjects();
569 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
571 m_frame->editor().clear();
575 m_needsClear = false;
577 if (!m_frame->document()->inPageCache()) {
578 m_frame->document()->cancelParsing();
579 m_frame->document()->stopActiveDOMObjects();
580 if (m_frame->document()->attached()) {
581 m_frame->document()->prepareForDestruction();
582 m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
586 // Do this after detaching the document so that the unload event works.
587 if (clearWindowProperties) {
588 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->document()->domWindow());
589 m_frame->document()->domWindow()->resetUnlessSuspendedForPageCache();
590 m_frame->script()->clearWindowShell(newDocument->domWindow(), m_frame->document()->inPageCache());
593 m_frame->selection()->prepareForDestruction();
594 m_frame->eventHandler().clear();
595 if (clearFrameView && m_frame->view())
596 m_frame->view()->clear();
598 // Do not drop the document before the ScriptController and view are cleared
599 // as some destructors might still try to access the document.
600 m_frame->setDocument(0);
602 m_subframeLoader.clear();
604 if (clearScriptObjects)
605 m_frame->script()->clearScriptObjects();
607 m_frame->script()->enableEval();
609 m_frame->navigationScheduler()->clear();
612 m_shouldCallCheckCompleted = false;
613 m_shouldCallCheckLoadComplete = false;
615 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
616 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
619 void FrameLoader::receivedFirstData()
621 dispatchDidCommitLoad();
622 dispatchDidClearWindowObjectsInAllWorlds();
623 dispatchGlobalObjectAvailableInAllWorlds();
625 if (m_documentLoader) {
626 StringWithDirection ptitle = m_documentLoader->title();
627 // If we have a title let the WebView know about it.
628 if (!ptitle.isNull())
629 m_client->dispatchDidReceiveTitle(ptitle);
632 if (!m_documentLoader)
634 if (m_frame->document()->isViewSource())
639 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
642 url = m_frame->document()->url().string();
644 url = m_frame->document()->completeURL(url).string();
646 m_frame->navigationScheduler()->scheduleRedirect(delay, url);
649 void FrameLoader::setOutgoingReferrer(const KURL& url)
651 m_outgoingReferrer = url.strippedForUseAsReferrer();
654 void FrameLoader::didBeginDocument(bool dispatch)
657 m_isComplete = false;
658 m_didCallImplicitClose = false;
659 m_frame->document()->setReadyState(Document::Loading);
661 if (m_pendingStateObject) {
662 m_frame->document()->statePopped(m_pendingStateObject.get());
663 m_pendingStateObject.clear();
667 dispatchDidClearWindowObjectsInAllWorlds();
669 updateFirstPartyForCookies();
670 m_frame->document()->initContentSecurityPolicy();
672 Settings* settings = m_frame->document()->settings();
674 m_frame->document()->cachedResourceLoader()->setImagesEnabled(settings->areImagesEnabled());
675 m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings->loadsImagesAutomatically());
678 if (m_documentLoader) {
679 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
680 if (!dnsPrefetchControl.isEmpty())
681 m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
683 String policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy");
684 if (!policyValue.isEmpty())
685 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Enforce);
687 policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy-Report-Only");
688 if (!policyValue.isEmpty())
689 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Report);
691 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
692 if (!policyValue.isEmpty())
693 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedEnforce);
695 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
696 if (!policyValue.isEmpty())
697 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedReport);
699 String headerContentLanguage = m_documentLoader->response().httpHeaderField("Content-Language");
700 if (!headerContentLanguage.isEmpty()) {
701 size_t commaIndex = headerContentLanguage.find(',');
702 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
703 headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
704 if (!headerContentLanguage.isEmpty())
705 m_frame->document()->setContentLanguage(headerContentLanguage);
709 history()->restoreDocumentState();
712 void FrameLoader::finishedParsing()
714 m_frame->injectUserScripts(InjectAtDocumentEnd);
716 if (m_stateMachine.creatingInitialEmptyDocument())
719 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
720 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
721 // Null-checking the FrameView indicates whether or not we're in the destructor.
722 RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
724 m_client->dispatchDidFinishDocumentLoad();
728 if (!m_frame->view())
729 return; // We are being destroyed by something checkCompleted called.
731 // Check if the scrollbars are really needed for the content.
732 // If not, remove them, relayout, and repaint.
733 m_frame->view()->restoreScrollbar();
734 scrollToFragmentWithParentBoundary(m_frame->document()->url());
737 void FrameLoader::loadDone()
742 bool FrameLoader::allChildrenAreComplete() const
744 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
745 if (!child->loader().m_isComplete)
751 bool FrameLoader::allAncestorsAreComplete() const
753 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
754 if (!ancestor->loader().m_isComplete)
760 void FrameLoader::checkCompleted()
762 RefPtr<Frame> protect(m_frame);
763 m_shouldCallCheckCompleted = false;
766 m_frame->view()->handleLoadCompleted();
768 // Have we completed before?
772 // Are we still parsing?
773 if (m_frame->document()->parsing())
776 // Still waiting for images/scripts?
777 if (m_frame->document()->cachedResourceLoader()->requestCount())
780 // Still waiting for elements that don't go through a FrameLoader?
781 if (m_frame->document()->isDelayingLoadEvent())
784 // Any frame that hasn't completed yet?
785 if (!allChildrenAreComplete())
790 m_requestedHistoryItem = 0;
791 m_frame->document()->setReadyState(Document::Complete);
793 checkCallImplicitClose(); // if we didn't do it before
795 m_frame->navigationScheduler()->startTimer();
802 m_frame->view()->handleLoadCompleted();
805 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
807 RefPtr<Frame> protect(m_frame);
809 if (Page* page = m_frame->page()) {
810 if (page->defersLoading())
813 if (m_shouldCallCheckCompleted)
815 if (m_shouldCallCheckLoadComplete)
819 void FrameLoader::startCheckCompleteTimer()
821 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
823 if (m_checkTimer.isActive())
825 m_checkTimer.startOneShot(0);
828 void FrameLoader::scheduleCheckCompleted()
830 m_shouldCallCheckCompleted = true;
831 startCheckCompleteTimer();
834 void FrameLoader::scheduleCheckLoadComplete()
836 m_shouldCallCheckLoadComplete = true;
837 startCheckCompleteTimer();
840 void FrameLoader::checkCallImplicitClose()
842 if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
845 if (!allChildrenAreComplete())
846 return; // still got a frame running -> too early
848 m_didCallImplicitClose = true;
849 m_wasUnloadEventEmitted = false;
850 m_frame->document()->implicitClose();
853 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
857 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
858 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);
859 if (subframeArchive) {
860 childFrame->loader().loadArchive(subframeArchive.release());
863 #endif // ENABLE(WEB_ARCHIVE)
865 HistoryItem* parentItem = history()->currentItem();
866 // If we're moving in the back/forward list, we might want to replace the content
867 // of this child frame with whatever was there at that point.
868 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
869 && !m_frame->document()->loadEventFinished()) {
870 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
872 childFrame->loader().loadDifferentDocumentItem(childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
877 childFrame->loader().loadURL(url, referer, "_self", false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
880 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
881 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
883 ArchiveResource* mainResource = archive->mainResource();
884 ASSERT(mainResource);
888 SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
890 ResourceRequest request(mainResource->url());
892 request.applyWebArchiveHackForMail();
895 RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
896 documentLoader->setArchive(archive.get());
897 load(documentLoader.get());
899 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
901 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
903 String mimeType = mimeTypeIn;
905 if (mimeType.isEmpty())
906 mimeType = mimeTypeFromURL(url);
908 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
909 if (mimeType.isEmpty()) {
910 String decodedPath = decodeURLEscapeSequences(url.path());
911 mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(decodedPath.substring(decodedPath.reverseFind('.') + 1));
915 if (mimeType.isEmpty())
916 return ObjectContentFrame; // Go ahead and hope that we can display the content.
918 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
919 bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
921 bool plugInSupportsMIMEType = false;
924 if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
925 return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
927 if (plugInSupportsMIMEType)
928 return WebCore::ObjectContentNetscapePlugin;
930 if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
931 return WebCore::ObjectContentFrame;
933 return WebCore::ObjectContentNone;
936 String FrameLoader::outgoingReferrer() const
938 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
939 // for why we walk the parent chain for srcdoc documents.
940 Frame* frame = m_frame;
941 while (frame->document()->isSrcdocDocument()) {
942 frame = frame->tree()->parent();
943 // Srcdoc documents cannot be top-level documents, by definition,
944 // because they need to be contained in iframes with the srcdoc.
947 return frame->loader().m_outgoingReferrer;
950 String FrameLoader::outgoingOrigin() const
952 return m_frame->document()->securityOrigin()->toString();
955 bool FrameLoader::checkIfFormActionAllowedByCSP(const KURL& url) const
957 if (m_submittedFormURL.isEmpty())
960 return m_frame->document()->contentSecurityPolicy()->allowFormAction(url);
963 Frame* FrameLoader::opener()
968 void FrameLoader::setOpener(Frame* opener)
970 if (m_opener && !opener)
971 m_client->didDisownOpener();
974 m_opener->loader().m_openedFrames.remove(m_frame);
976 opener->loader().m_openedFrames.add(m_frame);
979 if (m_frame->document())
980 m_frame->document()->initSecurityContext();
983 // FIXME: This does not belong in FrameLoader!
984 void FrameLoader::handleFallbackContent()
986 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
987 if (!owner || !owner->hasTagName(objectTag))
989 static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
992 void FrameLoader::provisionalLoadStarted()
994 if (m_stateMachine.firstLayoutDone())
995 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
996 m_frame->navigationScheduler()->cancel(true);
997 m_client->provisionalLoadStarted();
1000 void FrameLoader::resetMultipleFormSubmissionProtection()
1002 m_submittedFormURL = KURL();
1005 void FrameLoader::updateFirstPartyForCookies()
1007 if (m_frame->tree()->parent())
1008 setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
1010 setFirstPartyForCookies(m_frame->document()->url());
1013 void FrameLoader::setFirstPartyForCookies(const KURL& url)
1015 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
1016 frame->document()->setFirstPartyForCookies(url);
1019 // This does the same kind of work that didOpenURL does, except it relies on the fact
1020 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1021 void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
1023 // If we have a state object, we cannot also be a new navigation.
1024 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1026 // Update the data source's request with the new URL to fake the URL change
1027 KURL oldURL = m_frame->document()->url();
1028 m_frame->document()->setURL(url);
1029 setOutgoingReferrer(url);
1030 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1031 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1032 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1033 // based on the current request. Must also happen before we openURL and displace the
1034 // scroll position, since adding the BF item will save away scroll state.
1036 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1037 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1038 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1039 // though its load is not yet done. I think this all works out OK, for one because
1040 // we have already saved away the scroll and doc state for the long slow load,
1041 // but it's not an obvious case.
1043 history()->updateBackForwardListForFragmentScroll();
1046 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1048 history()->updateForSameDocumentNavigation();
1050 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1052 m_frame->eventHandler().stopAutoscrollTimer();
1054 // It's important to model this as a load that starts and immediately finishes.
1055 // Otherwise, the parent frame may think we never finished loading.
1058 // We need to scroll to the fragment whether or not a hash change occurred, since
1059 // the user might have scrolled since the previous navigation.
1060 scrollToFragmentWithParentBoundary(url);
1062 m_isComplete = false;
1065 if (isNewNavigation) {
1066 // This will clear previousItem from the rest of the frame tree that didn't
1067 // doing any loading. We need to make a pass on this now, since for fragment
1068 // navigation we'll not go through a real load and reach Completed state.
1069 checkLoadComplete();
1072 m_client->dispatchDidNavigateWithinPage();
1074 m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1075 m_client->dispatchDidPopStateWithinPage();
1078 m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1079 m_client->dispatchDidChangeLocationWithinPage();
1082 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1083 m_client->didFinishLoad();
1086 bool FrameLoader::isComplete() const
1088 return m_isComplete;
1091 void FrameLoader::completed()
1093 RefPtr<Frame> protect(m_frame);
1095 for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1096 descendant->navigationScheduler()->startTimer();
1098 if (Frame* parent = m_frame->tree()->parent())
1099 parent->loader().checkCompleted();
1101 if (m_frame->view())
1102 m_frame->view()->maintainScrollPositionAtAnchor(0);
1103 m_activityAssertion.clear();
1106 void FrameLoader::started()
1108 if (m_frame && m_frame->page())
1109 m_activityAssertion = m_frame->page()->createActivityToken();
1110 for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1111 frame->loader().m_isComplete = false;
1114 void FrameLoader::prepareForHistoryNavigation()
1116 // If there is no currentItem, but we still want to engage in
1117 // history navigation we need to manufacture one, and update
1118 // the state machine of this frame to impersonate having
1120 RefPtr<HistoryItem> currentItem = history()->currentItem();
1122 currentItem = HistoryItem::create();
1123 currentItem->setLastVisitWasFailure(true);
1124 history()->setCurrentItem(currentItem.get());
1125 frame()->page()->backForward()->setCurrentItem(currentItem.get());
1127 ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1128 stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1129 stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1133 void FrameLoader::prepareForLoadStart()
1135 m_progressTracker->progressStarted();
1136 m_client->dispatchDidStartProvisionalLoad();
1138 // Notify accessibility.
1139 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
1140 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadTypeReload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1141 cache->frameLoadingEventNotification(m_frame, loadingEvent);
1145 void FrameLoader::setupForReplace()
1147 m_client->revertToProvisionalState(m_documentLoader.get());
1148 setState(FrameStateProvisional);
1149 m_provisionalDocumentLoader = m_documentLoader;
1150 m_documentLoader = 0;
1154 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1155 PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
1157 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1158 RefPtr<Frame> protect(m_frame);
1160 KURL url = request.resourceRequest().url();
1162 ASSERT(m_frame->document());
1163 if (!request.requester()->canDisplay(url)) {
1164 reportLocalLoadFailed(m_frame, url.stringCenterEllipsizedToLength());
1168 String argsReferrer = request.resourceRequest().httpReferrer();
1169 if (argsReferrer.isEmpty())
1170 argsReferrer = outgoingReferrer();
1172 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), url, argsReferrer);
1173 if (shouldSendReferrer == NeverSendReferrer)
1174 referrer = String();
1176 FrameLoadType loadType;
1177 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1178 loadType = FrameLoadTypeReload;
1179 else if (lockBackForwardList)
1180 loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1182 loadType = FrameLoadTypeStandard;
1184 if (request.resourceRequest().httpMethod() == "POST")
1185 loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1187 loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1189 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1190 // load if frame names have changed.
1191 Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : m_frame;
1193 sourceFrame = m_frame;
1194 Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(request.frameName());
1195 if (targetFrame && targetFrame != sourceFrame) {
1196 if (Page* page = targetFrame->page())
1197 page->chrome().focus();
1201 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1202 PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1204 if (m_inStopAllLoaders)
1207 RefPtr<FormState> formState = prpFormState;
1208 bool isFormSubmission = formState;
1210 ResourceRequest request(newURL);
1211 if (!referrer.isEmpty()) {
1212 request.setHTTPReferrer(referrer);
1213 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1214 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1216 #if ENABLE(CACHE_PARTITIONING)
1217 if (m_frame->tree()->top() != m_frame)
1218 request.setCachePartition(m_frame->tree()->top()->document()->securityOrigin()->cachePartition());
1220 addExtraFieldsToRequest(request, newLoadType, true);
1221 if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1222 request.setCachePolicy(ReloadIgnoringCacheData);
1224 ASSERT(newLoadType != FrameLoadTypeSame);
1226 // The search for a target frame is done earlier in the case of form submission.
1227 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1228 if (targetFrame && targetFrame != m_frame) {
1229 targetFrame->loader().loadURL(newURL, referrer, "_self", lockHistory, newLoadType, event, formState.release());
1233 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1236 NavigationAction action(request, newLoadType, isFormSubmission, event);
1238 if (!targetFrame && !frameName.isEmpty()) {
1239 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1240 request, formState.release(), frameName, this);
1244 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1246 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1247 const String& httpMethod = request.httpMethod();
1249 // Make sure to do scroll to fragment processing even if the URL is
1250 // exactly the same so pages with '#' links and DHTML side effects
1252 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1253 oldDocumentLoader->setTriggeringAction(action);
1254 policyChecker()->stopCheck();
1255 policyChecker()->setLoadType(newLoadType);
1256 policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1257 callContinueFragmentScrollAfterNavigationPolicy, this);
1259 // must grab this now, since this load may stop the previous load and clear this flag
1260 bool isRedirect = m_quickRedirectComing;
1261 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1263 m_quickRedirectComing = false;
1264 if (m_provisionalDocumentLoader)
1265 m_provisionalDocumentLoader->setIsClientRedirect(true);
1266 } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1267 // Example of this case are sites that reload the same URL with a different cookie
1268 // driving the generated content, or a master frame with links that drive a target
1269 // frame, where the user has clicked on the same link repeatedly.
1270 m_loadType = FrameLoadTypeSame;
1274 SubstituteData FrameLoader::defaultSubstituteDataForURL(const KURL& url)
1276 if (!shouldTreatURLAsSrcdocDocument(url))
1277 return SubstituteData();
1278 String srcdoc = m_frame->ownerElement()->fastGetAttribute(srcdocAttr);
1279 ASSERT(!srcdoc.isNull());
1280 CString encodedSrcdoc = srcdoc.utf8();
1281 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL());
1284 void FrameLoader::load(const FrameLoadRequest& passedRequest)
1286 FrameLoadRequest request(passedRequest);
1288 if (m_inStopAllLoaders)
1291 if (!request.frameName().isEmpty()) {
1292 Frame* frame = findFrameForNavigation(request.frameName());
1294 request.setShouldCheckNewWindowPolicy(false);
1295 if (&frame->loader() != this) {
1296 frame->loader().load(request);
1302 if (request.shouldCheckNewWindowPolicy()) {
1303 policyChecker()->checkNewWindowPolicy(NavigationAction(request.resourceRequest(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request.resourceRequest(), 0, request.frameName(), this);
1307 if (!request.hasSubstituteData())
1308 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1310 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request.resourceRequest(), request.substituteData());
1311 if (request.lockHistory() && m_documentLoader)
1312 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1316 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1318 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1319 if (lockHistory && m_documentLoader)
1320 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1322 loader->setTriggeringAction(action);
1323 if (m_documentLoader)
1324 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1326 loadWithDocumentLoader(loader.get(), type, formState);
1329 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1331 ResourceRequest& r = newDocumentLoader->request();
1332 addExtraFieldsToMainResourceRequest(r);
1335 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1336 r.setCachePolicy(ReloadIgnoringCacheData);
1337 type = FrameLoadTypeSame;
1338 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadTypeReload)
1339 type = FrameLoadTypeReload;
1341 type = FrameLoadTypeStandard;
1343 if (m_documentLoader)
1344 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1346 // When we loading alternate content for an unreachable URL that we're
1347 // visiting in the history list, we treat it as a reload so the history list
1348 // is appropriately maintained.
1350 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1351 // shouldn't a more explicit type of reload be defined, that means roughly
1352 // "load without affecting history" ?
1353 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1354 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1355 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1356 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1357 history()->saveDocumentAndScrollState();
1359 ASSERT(type == FrameLoadTypeStandard);
1360 type = FrameLoadTypeReload;
1363 loadWithDocumentLoader(newDocumentLoader, type, 0);
1366 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1368 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1369 RefPtr<Frame> protect(m_frame);
1371 ASSERT(m_client->hasWebView());
1373 // Unfortunately the view must be non-nil, this is ultimately due
1374 // to parser requiring a FrameView. We should fix this dependency.
1376 ASSERT(m_frame->view());
1378 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1381 if (m_frame->document())
1382 m_previousURL = m_frame->document()->url();
1384 policyChecker()->setLoadType(type);
1385 RefPtr<FormState> formState = prpFormState;
1386 bool isFormSubmission = formState;
1388 const KURL& newURL = loader->request().url();
1389 const String& httpMethod = loader->request().httpMethod();
1391 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker()->loadType(), newURL)) {
1392 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1393 NavigationAction action(loader->request(), policyChecker()->loadType(), isFormSubmission);
1395 oldDocumentLoader->setTriggeringAction(action);
1396 policyChecker()->stopCheck();
1397 policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1398 callContinueFragmentScrollAfterNavigationPolicy, this);
1400 if (Frame* parent = m_frame->tree()->parent())
1401 loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
1403 policyChecker()->stopCheck();
1404 setPolicyDocumentLoader(loader);
1405 if (loader->triggeringAction().isEmpty())
1406 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker()->loadType(), isFormSubmission));
1408 if (Element* ownerElement = m_frame->ownerElement()) {
1409 // We skip dispatching the beforeload event if we've already
1410 // committed a real document load because the event would leak
1411 // subsequent activity by the frame which the parent frame isn't
1412 // supposed to learn. For example, if the child frame navigated to
1413 // a new URL, the parent frame shouldn't learn the URL.
1414 if (!m_stateMachine.committedFirstRealDocumentLoad()
1415 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1416 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1421 policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1422 callContinueLoadAfterNavigationPolicy, this);
1426 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1428 ASSERT(!url.isEmpty());
1432 frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
1435 const ResourceRequest& FrameLoader::initialRequest() const
1437 return activeDocumentLoader()->originalRequest();
1440 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1442 ResourceRequest request(url);
1444 unsigned long identifier;
1445 ResourceError error;
1446 requestFromDelegate(request, identifier, error);
1447 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1449 url = request.url();
1451 return error.isNull();
1454 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1456 KURL unreachableURL = docLoader->unreachableURL();
1458 if (unreachableURL.isEmpty())
1461 if (!isBackForwardLoadType(policyChecker()->loadType()))
1464 // We only treat unreachableURLs specially during the delegate callbacks
1465 // for provisional load errors and navigation policy decisions. The former
1466 // case handles well-formed URLs that can't be loaded, and the latter
1467 // case handles malformed URLs and unknown schemes. Loading alternate content
1468 // at other times behaves like a standard load.
1469 DocumentLoader* compareDocumentLoader = 0;
1470 if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1471 compareDocumentLoader = m_policyDocumentLoader.get();
1472 else if (m_delegateIsHandlingProvisionalLoadError)
1473 compareDocumentLoader = m_provisionalDocumentLoader.get();
1475 return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1478 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1480 if (!m_documentLoader)
1483 ResourceRequest request = m_documentLoader->request();
1484 KURL unreachableURL = m_documentLoader->unreachableURL();
1485 if (!unreachableURL.isEmpty())
1486 request.setURL(unreachableURL);
1488 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1489 // We should ask the user for confirmation in this case.
1490 request.setCachePolicy(ReturnCacheDataElseLoad);
1492 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1493 setPolicyDocumentLoader(loader.get());
1495 loader->setOverrideEncoding(encoding);
1497 loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1500 void FrameLoader::reloadWithOverrideURL(const KURL& overrideUrl, bool endToEndReload)
1502 if (!m_documentLoader)
1505 if (overrideUrl.isEmpty())
1508 ResourceRequest request = m_documentLoader->request();
1509 request.setURL(overrideUrl);
1510 reloadWithRequest(request, endToEndReload);
1513 void FrameLoader::reload(bool endToEndReload)
1515 if (!m_documentLoader)
1518 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1519 // Reloading in this case will lose the current contents (see 4151001).
1520 if (m_documentLoader->request().url().isEmpty())
1523 // Replace error-page URL with the URL we were trying to reach.
1524 ResourceRequest initialRequest = m_documentLoader->request();
1525 KURL unreachableURL = m_documentLoader->unreachableURL();
1526 if (!unreachableURL.isEmpty())
1527 initialRequest.setURL(unreachableURL);
1529 reloadWithRequest(initialRequest, endToEndReload);
1532 void FrameLoader::reloadWithRequest(const ResourceRequest& initialRequest, bool endToEndReload)
1534 ASSERT(m_documentLoader);
1536 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1537 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1538 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1540 ResourceRequest& request = loader->request();
1542 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1543 request.setCachePolicy(ReloadIgnoringCacheData);
1545 // If we're about to re-post, set up action so the application can warn the user.
1546 if (request.httpMethod() == "POST")
1547 loader->setTriggeringAction(NavigationAction(request, NavigationTypeFormResubmitted));
1549 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1551 loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1554 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1556 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1557 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1560 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1561 if (m_inStopAllLoaders)
1564 // Calling stopLoading() on the provisional document loader can blow away
1565 // the frame from underneath.
1566 RefPtr<Frame> protect(m_frame);
1568 m_inStopAllLoaders = true;
1570 policyChecker()->stopCheck();
1572 // If no new load is in progress, we should clear the provisional item from history
1573 // before we call stopLoading.
1574 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1575 history()->setProvisionalItem(0);
1577 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1578 child->loader().stopAllLoaders(clearProvisionalItemPolicy);
1579 if (m_provisionalDocumentLoader)
1580 m_provisionalDocumentLoader->stopLoading();
1581 if (m_documentLoader)
1582 m_documentLoader->stopLoading();
1584 setProvisionalDocumentLoader(0);
1586 m_checkTimer.stop();
1588 m_inStopAllLoaders = false;
1591 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1595 if (deferCheckLoadComplete)
1596 scheduleCheckLoadComplete();
1597 else if (m_frame->page())
1598 checkLoadComplete();
1601 DocumentLoader* FrameLoader::activeDocumentLoader() const
1603 if (m_state == FrameStateProvisional)
1604 return m_provisionalDocumentLoader.get();
1605 return m_documentLoader.get();
1608 bool FrameLoader::isLoading() const
1610 DocumentLoader* docLoader = activeDocumentLoader();
1613 return docLoader->isLoading();
1616 bool FrameLoader::frameHasLoaded() const
1618 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1621 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1623 if (!loader && !m_documentLoader)
1626 ASSERT(loader != m_documentLoader);
1627 ASSERT(!loader || loader->frameLoader() == this);
1629 m_client->prepareForDataSourceReplacement();
1632 // detachChildren() can trigger this frame's unload event, and therefore
1633 // script can run and do just about anything. For example, an unload event that calls
1634 // document.write("") on its parent frame can lead to a recursive detachChildren()
1635 // invocation for this frame. In that case, we can end up at this point with a
1636 // loader that hasn't been deleted but has been detached from its frame. Such a
1637 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1638 // state if we try to use it.
1639 if (loader && !loader->frame())
1642 if (m_documentLoader)
1643 m_documentLoader->detachFromFrame();
1645 m_documentLoader = loader;
1648 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1650 if (m_policyDocumentLoader == loader)
1655 loader->setFrame(m_frame);
1656 if (m_policyDocumentLoader
1657 && m_policyDocumentLoader != m_provisionalDocumentLoader
1658 && m_policyDocumentLoader != m_documentLoader)
1659 m_policyDocumentLoader->detachFromFrame();
1661 m_policyDocumentLoader = loader;
1664 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1666 ASSERT(!loader || !m_provisionalDocumentLoader);
1667 ASSERT(!loader || loader->frameLoader() == this);
1669 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1670 m_provisionalDocumentLoader->detachFromFrame();
1672 m_provisionalDocumentLoader = loader;
1675 double FrameLoader::timeOfLastCompletedLoad()
1677 return storedTimeOfLastCompletedLoad;
1680 void FrameLoader::setState(FrameState newState)
1684 if (newState == FrameStateProvisional)
1685 provisionalLoadStarted();
1686 else if (newState == FrameStateComplete) {
1687 frameLoadCompleted();
1688 storedTimeOfLastCompletedLoad = currentTime();
1689 if (m_documentLoader)
1690 m_documentLoader->stopRecordingResponses();
1694 void FrameLoader::clearProvisionalLoad()
1696 setProvisionalDocumentLoader(0);
1697 m_progressTracker->progressCompleted();
1698 setState(FrameStateComplete);
1701 void FrameLoader::commitProvisionalLoad()
1703 RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1704 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1705 RefPtr<Frame> protect(m_frame);
1707 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1708 m_frame->document() ? m_frame->document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
1709 pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>");
1711 willTransitionToCommitted();
1713 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1714 // We are doing this here because we know for sure that a new page is about to be loaded.
1715 HistoryItem* item = history()->currentItem();
1716 if (!m_frame->tree()->parent() && pageCache()->canCache(m_frame->page()) && !item->isInPageCache())
1717 pageCache()->add(item, m_frame->page());
1719 if (m_loadType != FrameLoadTypeReplace)
1720 closeOldDataSources();
1722 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1723 m_client->makeRepresentation(pdl.get());
1725 transitionToCommitted(cachedPage);
1727 if (pdl && m_documentLoader) {
1728 // Check if the destination page is allowed to access the previous page's timing information.
1729 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1730 m_documentLoader->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_previousURL));
1733 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1734 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1735 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1736 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1737 if (m_sentRedirectNotification)
1738 clientRedirectCancelledOrFinished(false);
1740 if (cachedPage && cachedPage->document()) {
1741 prepareForCachedPageRestore();
1742 cachedPage->restore(m_frame->page());
1744 // The page should be removed from the cache immediately after a restoration in order for the PageCache to be consistent.
1745 pageCache()->remove(history()->currentItem());
1747 dispatchDidCommitLoad();
1749 // If we have a title let the WebView know about it.
1750 StringWithDirection title = m_documentLoader->title();
1751 if (!title.isNull())
1752 m_client->dispatchDidReceiveTitle(title);
1757 pageCache()->remove(history()->currentItem());
1761 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1762 m_frame->document() ? m_frame->document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
1764 if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1765 history()->updateForClientRedirect();
1767 if (m_loadingFromCachedPage) {
1768 m_frame->document()->documentDidResumeFromPageCache();
1770 // Force a layout to update view size and thereby update scrollbars.
1771 m_frame->view()->forceLayout();
1773 const ResponseVector& responses = m_documentLoader->responses();
1774 size_t count = responses.size();
1775 for (size_t i = 0; i < count; i++) {
1776 const ResourceResponse& response = responses[i];
1777 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1778 ResourceError error;
1779 unsigned long identifier;
1780 ResourceRequest request(response.url());
1781 requestFromDelegate(request, identifier, error);
1782 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1783 // However, with today's computers and networking speeds, this won't happen in practice.
1784 // Could be an issue with a giant local file.
1785 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1788 // FIXME: Why only this frame and not parent frames?
1789 checkLoadCompleteForThisFrame();
1793 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1795 ASSERT(m_client->hasWebView());
1796 ASSERT(m_state == FrameStateProvisional);
1798 if (m_state != FrameStateProvisional)
1801 if (FrameView* view = m_frame->view()) {
1802 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
1803 scrollAnimator->cancelAnimations();
1806 m_client->setCopiesOnScroll();
1807 history()->updateForCommit();
1809 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1810 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1811 // or the two will stomp each other.
1812 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1813 if (m_documentLoader)
1815 if (pdl != m_provisionalDocumentLoader)
1818 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1819 if (m_documentLoader)
1820 m_documentLoader->stopLoadingSubresources();
1821 if (m_documentLoader)
1822 m_documentLoader->stopLoadingPlugIns();
1824 setDocumentLoader(m_provisionalDocumentLoader.get());
1825 setProvisionalDocumentLoader(0);
1827 if (pdl != m_documentLoader) {
1828 ASSERT(m_state == FrameStateComplete);
1832 setState(FrameStateCommittedPage);
1834 #if ENABLE(TOUCH_EVENTS)
1835 if (isLoadingMainFrame())
1836 m_frame->page()->chrome().client()->needTouchEvents(false);
1839 // Handle adding the URL to the back/forward list.
1840 DocumentLoader* dl = m_documentLoader.get();
1842 switch (m_loadType) {
1843 case FrameLoadTypeForward:
1844 case FrameLoadTypeBack:
1845 case FrameLoadTypeIndexedBackForward:
1846 if (m_frame->page()) {
1847 // If the first load within a frame is a navigation within a back/forward list that was attached
1848 // without any of the items being loaded then we need to update the history in a similar manner as
1849 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1850 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1851 history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1853 history()->updateForBackForwardNavigation();
1855 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1856 if (history()->currentItem() && !cachedPage)
1857 m_pendingStateObject = history()->currentItem()->stateObject();
1859 // Create a document view for this document, or used the cached view.
1861 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1862 ASSERT(cachedDocumentLoader);
1863 cachedDocumentLoader->setFrame(m_frame);
1864 m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1867 m_client->transitionToCommittedForNewPage();
1871 case FrameLoadTypeReload:
1872 case FrameLoadTypeReloadFromOrigin:
1873 case FrameLoadTypeSame:
1874 case FrameLoadTypeReplace:
1875 history()->updateForReload();
1876 m_client->transitionToCommittedForNewPage();
1879 case FrameLoadTypeStandard:
1880 history()->updateForStandardLoad();
1881 if (m_frame->view())
1882 m_frame->view()->setScrollbarsSuppressed(true);
1883 m_client->transitionToCommittedForNewPage();
1886 case FrameLoadTypeRedirectWithLockedBackForwardList:
1887 history()->updateForRedirectWithLockedBackForwardList();
1888 m_client->transitionToCommittedForNewPage();
1891 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1892 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1894 ASSERT_NOT_REACHED();
1897 m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
1899 // Tell the client we've committed this URL.
1900 ASSERT(m_frame->view());
1902 if (m_stateMachine.creatingInitialEmptyDocument())
1905 if (!m_stateMachine.committedFirstRealDocumentLoad())
1906 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1909 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1911 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1912 // the redirect succeeded. We should either rename this API, or add a new method, like
1913 // -webView:didFinishClientRedirectForFrame:
1914 m_client->dispatchDidCancelClientRedirect();
1916 if (!cancelWithLoadInProgress)
1917 m_quickRedirectComing = false;
1919 m_sentRedirectNotification = false;
1922 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
1924 m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
1926 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
1927 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
1928 m_sentRedirectNotification = true;
1930 // If a "quick" redirect comes in, we set a special mode so we treat the next
1931 // load as part of the original navigation. If we don't have a document loader, we have
1932 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
1933 // Loads triggered by JavaScript form submissions never count as quick redirects.
1934 m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
1937 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
1939 // This function implements the rule: "Don't reload if navigating by fragment within
1940 // the same URL, but do reload if going to a new URL or to the same URL with no
1941 // fragment identifier at all."
1942 if (!destinationURL.hasFragmentIdentifier())
1944 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
1947 void FrameLoader::closeOldDataSources()
1949 // FIXME: Is it important for this traversal to be postorder instead of preorder?
1950 // If so, add helpers for postorder traversal, and use them. If not, then lets not
1951 // use a recursive algorithm here.
1952 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1953 child->loader().closeOldDataSources();
1955 if (m_documentLoader)
1956 m_client->dispatchWillClose();
1958 m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
1961 void FrameLoader::prepareForCachedPageRestore()
1963 ASSERT(!m_frame->tree()->parent());
1964 ASSERT(m_frame->page());
1965 ASSERT(m_frame->page()->mainFrame() == m_frame);
1967 m_frame->navigationScheduler()->cancel();
1969 // We still have to close the previous part page.
1972 // Delete old status bar messages (if it _was_ activated on last URL).
1973 if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
1974 DOMWindow* window = m_frame->document()->domWindow();
1975 window->setStatus(String());
1976 window->setDefaultStatus(String());
1980 void FrameLoader::open(CachedFrameBase& cachedFrame)
1982 m_isComplete = false;
1984 // Don't re-emit the load event.
1985 m_didCallImplicitClose = true;
1987 KURL url = cachedFrame.url();
1989 // FIXME: I suspect this block of code doesn't do anything.
1990 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
1994 Document* document = cachedFrame.document();
1996 ASSERT(document->domWindow());
1998 clear(document, true, true, cachedFrame.isMainFrame());
2000 document->setInPageCache(false);
2002 m_needsClear = true;
2003 m_isComplete = false;
2004 m_didCallImplicitClose = false;
2005 m_outgoingReferrer = url.string();
2007 FrameView* view = cachedFrame.view();
2009 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2011 view->setWasScrolledByUser(false);
2013 // Use the current ScrollView's frame rect.
2014 if (m_frame->view())
2015 view->setFrameRect(m_frame->view()->frameRect());
2016 m_frame->setView(view);
2018 m_frame->setDocument(document);
2019 document->domWindow()->resumeFromPageCache();
2021 updateFirstPartyForCookies();
2023 cachedFrame.restore();
2026 bool FrameLoader::isHostedByObjectElement() const
2028 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2029 return owner && owner->hasTagName(objectTag);
2032 bool FrameLoader::isLoadingMainFrame() const
2034 Page* page = m_frame->page();
2035 return page && m_frame == page->mainFrame();
2038 bool FrameLoader::isReplacing() const
2040 return m_loadType == FrameLoadTypeReplace;
2043 void FrameLoader::setReplacing()
2045 m_loadType = FrameLoadTypeReplace;
2048 bool FrameLoader::subframeIsLoading() const
2050 // It's most likely that the last added frame is the last to load so we walk backwards.
2051 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2052 FrameLoader& childLoader = child->loader();
2053 DocumentLoader* documentLoader = childLoader.documentLoader();
2054 if (documentLoader && documentLoader->isLoadingInAPISense())
2056 documentLoader = childLoader.provisionalDocumentLoader();
2057 if (documentLoader && documentLoader->isLoadingInAPISense())
2059 documentLoader = childLoader.policyDocumentLoader();
2066 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2068 m_client->willChangeTitle(loader);
2071 FrameLoadType FrameLoader::loadType() const
2076 CachePolicy FrameLoader::subresourceCachePolicy() const
2079 return CachePolicyVerify;
2081 if (m_loadType == FrameLoadTypeReloadFromOrigin)
2082 return CachePolicyReload;
2084 if (Frame* parentFrame = m_frame->tree()->parent()) {
2085 CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
2086 if (parentCachePolicy != CachePolicyVerify)
2087 return parentCachePolicy;
2090 if (m_loadType == FrameLoadTypeReload)
2091 return CachePolicyRevalidate;
2093 const ResourceRequest& request(documentLoader()->request());
2095 if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2096 return CachePolicyRevalidate;
2099 if (request.cachePolicy() == ReturnCacheDataElseLoad)
2100 return CachePolicyHistoryBuffer;
2102 return CachePolicyVerify;
2105 void FrameLoader::checkLoadCompleteForThisFrame()
2107 ASSERT(m_client->hasWebView());
2110 case FrameStateProvisional: {
2111 if (m_delegateIsHandlingProvisionalLoadError)
2114 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2118 // If we've received any errors we may be stuck in the provisional state and actually complete.
2119 const ResourceError& error = pdl->mainDocumentError();
2123 // Check all children first.
2124 RefPtr<HistoryItem> item;
2125 if (Page* page = m_frame->page())
2126 if (isBackForwardLoadType(loadType()))
2127 // Reset the back forward list to the last committed history item at the top level.
2128 item = page->mainFrame()->loader().history()->currentItem();
2130 // Only reset if we aren't already going to a new provisional item.
2131 bool shouldReset = !history()->provisionalItem();
2132 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2133 m_delegateIsHandlingProvisionalLoadError = true;
2134 m_client->dispatchDidFailProvisionalLoad(error);
2135 m_delegateIsHandlingProvisionalLoadError = false;
2137 ASSERT(!pdl->isLoading());
2139 // If we're in the middle of loading multipart data, we need to restore the document loader.
2140 if (isReplacing() && !m_documentLoader.get())
2141 setDocumentLoader(m_provisionalDocumentLoader.get());
2143 // Finish resetting the load state, but only if another load hasn't been started by the
2144 // delegate callback.
2145 if (pdl == m_provisionalDocumentLoader)
2146 clearProvisionalLoad();
2147 else if (activeDocumentLoader()) {
2148 KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2149 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2150 shouldReset = false;
2153 if (shouldReset && item)
2154 if (Page* page = m_frame->page()) {
2155 page->backForward()->setCurrentItem(item.get());
2156 m_frame->loader().client()->updateGlobalHistoryItemForPage();
2161 case FrameStateCommittedPage: {
2162 DocumentLoader* dl = m_documentLoader.get();
2163 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2166 setState(FrameStateComplete);
2168 // FIXME: Is this subsequent work important if we already navigated away?
2169 // Maybe there are bugs because of that, or extra work we can skip because
2170 // the new page is ready.
2172 m_client->forceLayoutForNonHTML();
2174 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2175 if (m_frame->page()) {
2176 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2177 history()->restoreScrollPositionAndViewState();
2180 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2183 m_progressTracker->progressCompleted();
2184 if (Page* page = m_frame->page()) {
2185 if (m_frame == page->mainFrame())
2186 page->resetRelevantPaintedObjectCounter();
2189 const ResourceError& error = dl->mainDocumentError();
2191 AXObjectCache::AXLoadingEvent loadingEvent;
2192 if (!error.isNull()) {
2193 m_client->dispatchDidFailLoad(error);
2194 loadingEvent = AXObjectCache::AXLoadingFailed;
2196 m_client->dispatchDidFinishLoad();
2197 loadingEvent = AXObjectCache::AXLoadingFinished;
2200 // Notify accessibility.
2201 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
2202 cache->frameLoadingEventNotification(m_frame, loadingEvent);
2207 case FrameStateComplete:
2208 m_loadType = FrameLoadTypeStandard;
2209 frameLoadCompleted();
2213 ASSERT_NOT_REACHED();
2216 void FrameLoader::continueLoadAfterWillSubmitForm()
2218 if (!m_provisionalDocumentLoader)
2221 prepareForLoadStart();
2223 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2224 // so we need to null check it again.
2225 if (!m_provisionalDocumentLoader)
2228 DocumentLoader* activeDocLoader = activeDocumentLoader();
2229 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2232 m_loadingFromCachedPage = false;
2233 m_provisionalDocumentLoader->startLoadingMainResource();
2236 static KURL originatingURLFromBackForwardList(Page* page)
2238 // FIXME: Can this logic be replaced with m_frame->document()->firstPartyForCookies()?
2239 // It has the same meaning of "page a user thinks is the current one".
2242 int backCount = page->backForward()->backCount();
2243 for (int backIndex = 0; backIndex <= backCount; backIndex++) {
2244 // FIXME: At one point we had code here to check a "was user gesture" flag.
2245 // Do we need to restore that logic?
2246 HistoryItem* historyItem = page->backForward()->itemAtIndex(-backIndex);
2250 originalURL = historyItem->originalURL();
2251 if (!originalURL.isNull())
2258 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2262 // If there is no referrer, assume that the download was initiated directly, so current document is
2263 // completely unrelated to it. See <rdar://problem/5294691>.
2264 // FIXME: Referrer is not sent in many other cases, so we will often miss this important information.
2265 // Find a better way to decide whether the download was unrelated to current document.
2266 if (!request.httpReferrer().isNull()) {
2267 // find the first item in the history that was originated by the user
2268 originalURL = originatingURLFromBackForwardList(m_frame->page());
2271 if (originalURL.isNull())
2272 originalURL = request.url();
2274 if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
2275 unsigned port = originalURL.port();
2277 // Original URL is needed to show the user where a file was downloaded from. We should make a URL that won't result in downloading the file again.
2278 // FIXME: Using host-only URL is a very heavy-handed approach. We should attempt to provide the actual page where the download was initiated from, as a reminder to the user.
2279 String hostOnlyURLString;
2281 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ":", String::number(port));
2283 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
2285 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2286 request.setFirstPartyForCookies(KURL(KURL(), hostOnlyURLString));
2290 void FrameLoader::didLayout(LayoutMilestones milestones)
2292 #if !ASSERT_DISABLED
2293 if (Page* page = m_frame->page())
2294 ASSERT(page->mainFrame() == m_frame);
2297 m_client->dispatchDidLayout(milestones);
2300 void FrameLoader::didFirstLayout()
2302 if (m_frame->page() && isBackForwardLoadType(m_loadType))
2303 history()->restoreScrollPositionAndViewState();
2305 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2306 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2309 void FrameLoader::frameLoadCompleted()
2311 // Note: Can be called multiple times.
2313 m_client->frameLoadCompleted();
2315 history()->updateForFrameLoadCompleted();
2317 // After a canceled provisional load, firstLayoutDone is false.
2318 // Reset it to true if we're displaying a page.
2319 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2320 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2323 void FrameLoader::detachChildren()
2325 typedef Vector<RefPtr<Frame> > FrameVector;
2326 FrameVector childrenToDetach;
2327 childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2328 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2329 childrenToDetach.append(child);
2330 FrameVector::iterator end = childrenToDetach.end();
2331 for (FrameVector::iterator it = childrenToDetach.begin(); it != end; ++it)
2332 (*it)->loader().detachFromParent();
2335 void FrameLoader::closeAndRemoveChild(Frame* child)
2337 child->tree()->detachFromParent();
2340 if (child->ownerElement() && child->page())
2341 child->page()->decrementSubframeCount();
2342 child->willDetachPage();
2343 child->detachFromPage();
2345 m_frame->tree()->removeChild(child);
2348 // Called every time a resource is completely loaded or an error is received.
2349 void FrameLoader::checkLoadComplete()
2351 ASSERT(m_client->hasWebView());
2353 m_shouldCallCheckLoadComplete = false;
2355 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2356 // is currently needed in order to null out the previous history item for all frames.
2357 if (Page* page = m_frame->page()) {
2358 Vector<RefPtr<Frame>, 10> frames;
2359 for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2360 frames.append(frame);
2361 // To process children before their parents, iterate the vector backwards.
2362 for (size_t i = frames.size(); i; --i)
2363 frames[i - 1]->loader().checkLoadCompleteForThisFrame();
2367 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2370 return m_frame->document()->cachedResourceLoader()->requestCount();
2373 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2374 count += frame->document()->cachedResourceLoader()->requestCount();
2378 String FrameLoader::userAgent(const KURL& url) const
2380 String userAgent = m_client->userAgent(url);
2381 InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2385 void FrameLoader::handledOnloadEvents()
2387 m_client->dispatchDidHandleOnloadEvents();
2389 if (documentLoader())
2390 documentLoader()->handledOnloadEvents();
2393 void FrameLoader::frameDetached()
2396 m_frame->document()->stopActiveDOMObjects();
2400 void FrameLoader::detachFromParent()
2402 RefPtr<Frame> protect(m_frame);
2405 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2407 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2408 // will trigger the unload event handlers of any child frames, and those event
2409 // handlers might start a new subresource load in this frame.
2412 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2414 detachViewsAndDocumentLoader();
2416 m_progressTracker.clear();
2418 if (Frame* parent = m_frame->tree()->parent()) {
2419 parent->loader().closeAndRemoveChild(m_frame);
2420 parent->loader().scheduleCheckCompleted();
2422 m_frame->setView(0);
2423 m_frame->willDetachPage();
2424 m_frame->detachFromPage();
2428 void FrameLoader::detachViewsAndDocumentLoader()
2430 m_client->detachedFromParent2();
2431 setDocumentLoader(0);
2432 m_client->detachedFromParent3();
2435 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2437 addExtraFieldsToRequest(request, m_loadType, false);
2440 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2442 // FIXME: Using m_loadType seems wrong for some callers.
2443 // If we are only preparing to load the main resource, that is previous load's load type!
2444 addExtraFieldsToRequest(request, m_loadType, true);
2447 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2449 // Don't set the cookie policy URL if it's already been set.
2450 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2451 if (request.firstPartyForCookies().isEmpty()) {
2452 if (mainResource && isLoadingMainFrame())
2453 request.setFirstPartyForCookies(request.url());
2454 else if (Document* document = m_frame->document())
2455 request.setFirstPartyForCookies(document->firstPartyForCookies());
2458 // The remaining modifications are only necessary for HTTP and HTTPS.
2459 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2462 applyUserAgent(request);
2464 if (!mainResource) {
2465 if (request.isConditional())
2466 request.setCachePolicy(ReloadIgnoringCacheData);
2467 else if (documentLoader()->isLoadingInAPISense()) {
2468 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2469 // original request cache policy for two reasons:
2470 // 1. For POST requests, we mutate the cache policy for the main resource,
2471 // but we do not want this to apply to subresources
2472 // 2. Delegates that modify the cache policy using willSendRequest: should
2473 // not affect any other resources. Such changes need to be done
2475 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2476 // Back-forward navigations try to load main resource from cache only to avoid re-submitting form data, and start over (with a warning dialog) if that fails.
2477 // This policy is set on initial request too, but should not be inherited.
2478 ResourceRequestCachePolicy subresourceCachePolicy = (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2479 request.setCachePolicy(subresourceCachePolicy);
2481 request.setCachePolicy(UseProtocolCachePolicy);
2483 // FIXME: Other FrameLoader functions have duplicated code for setting cache policy of main request when reloading.
2484 // It seems better to manage it explicitly than to hide the logic inside addExtraFieldsToRequest().
2485 } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2486 request.setCachePolicy(ReloadIgnoringCacheData);
2488 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2489 if (loadType == FrameLoadTypeReload)
2490 request.setHTTPHeaderField("Cache-Control", "max-age=0");
2491 else if (loadType == FrameLoadTypeReloadFromOrigin) {
2492 request.setHTTPHeaderField("Cache-Control", "no-cache");
2493 request.setHTTPHeaderField("Pragma", "no-cache");
2498 request.setHTTPAccept(defaultAcceptHeader);
2500 // Make sure we send the Origin header.
2501 addHTTPOriginIfNeeded(request, String());
2503 // Only set fallback array if it's still empty (later attempts may be incorrect, see bug 117818).
2504 if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
2505 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2506 Settings* settings = m_frame->settings();
2507 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame->document()->encoding(), settings ? settings->defaultTextEncodingName() : String());
2511 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2513 if (!request.httpOrigin().isEmpty())
2514 return; // Request already has an Origin header.
2516 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2517 // For example, if an intranet page has a hyperlink to an external web
2518 // site, we don't want to include the Origin of the request because it
2519 // will leak the internal host name. Similar privacy concerns have lead
2520 // to the widespread suppression of the Referer header at the network
2522 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2525 // For non-GET and non-HEAD methods, always send an Origin header so the
2526 // server knows we support this feature.
2528 if (origin.isEmpty()) {
2529 // If we don't know what origin header to attach, we attach the value
2530 // for an empty origin.
2531 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2535 request.setHTTPOrigin(origin);
2538 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2540 RefPtr<FormState> formState = prpFormState;
2542 // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a
2543 // bunch of parameters that would come in here and then be built back up to a ResourceRequest. In case
2544 // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2545 // from scratch as it did all along.
2546 const KURL& url = inRequest.url();
2547 RefPtr<FormData> formData = inRequest.httpBody();
2548 const String& contentType = inRequest.httpContentType();
2549 String origin = inRequest.httpOrigin();
2551 ResourceRequest workingResourceRequest(url);
2553 if (!referrer.isEmpty())
2554 workingResourceRequest.setHTTPReferrer(referrer);
2555 workingResourceRequest.setHTTPOrigin(origin);
2556 workingResourceRequest.setHTTPMethod("POST");
2557 workingResourceRequest.setHTTPBody(formData);
2558 workingResourceRequest.setHTTPContentType(contentType);
2559 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2561 NavigationAction action(workingResourceRequest, loadType, true, event);
2563 if (!frameName.isEmpty()) {
2564 // The search for a target frame is done earlier in the case of form submission.
2565 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2566 targetFrame->loader().loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2568 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2570 // must grab this now, since this load may stop the previous load and clear this flag
2571 bool isRedirect = m_quickRedirectComing;
2572 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2574 m_quickRedirectComing = false;
2575 if (m_provisionalDocumentLoader)
2576 m_provisionalDocumentLoader->setIsClientRedirect(true);
2581 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2583 ASSERT(m_frame->document());
2584 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), outgoingReferrer());
2586 ResourceRequest initialRequest = request;
2587 initialRequest.setTimeoutInterval(10);
2589 if (!referrer.isEmpty())
2590 initialRequest.setHTTPReferrer(referrer);
2591 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2593 if (Page* page = m_frame->page())
2594 initialRequest.setFirstPartyForCookies(page->mainFrame()->loader().documentLoader()->request().url());
2596 addExtraFieldsToSubresourceRequest(initialRequest);
2598 unsigned long identifier = 0;
2599 ResourceRequest newRequest(initialRequest);
2600 requestFromDelegate(newRequest, identifier, error);
2602 if (error.isNull()) {
2603 ASSERT(!newRequest.isNull());
2605 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2606 platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, data);
2607 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2610 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data.data(), data.size(), -1, error);
2614 const ResourceRequest& FrameLoader::originalRequest() const
2616 return activeDocumentLoader()->originalRequestCopy();
2619 void FrameLoader::receivedMainResourceError(const ResourceError& error)
2621 // Retain because the stop may release the last reference to it.
2622 RefPtr<Frame> protect(m_frame);
2624 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2625 // FIXME: Don't want to do this if an entirely new load is going, so should check
2626 // that both data sources on the frame are either this or nil.
2628 if (m_client->shouldFallBack(error))
2629 handleFallbackContent();
2631 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2632 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2633 m_submittedFormURL = KURL();
2635 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2636 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2637 // so that the existing view (that wenever got far enough to replace) can continue being used.
2638 history()->invalidateCurrentItemCachedPage();
2640 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2641 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2642 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2643 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2645 if (m_sentRedirectNotification)
2646 clientRedirectCancelledOrFinished(false);
2650 if (m_frame->page())
2651 checkLoadComplete();
2654 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2655 const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2657 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2658 loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2661 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2663 m_quickRedirectComing = false;
2665 if (!shouldContinue)
2668 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2669 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2670 m_provisionalDocumentLoader->stopLoading();
2671 setProvisionalDocumentLoader(0);
2674 bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;
2675 loadInSameDocument(request.url(), 0, !isRedirect);
2678 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2680 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2681 // currently displaying a frameset, or if the URL does not have a fragment.
2682 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2684 // FIXME: What about load types other than Standard and Reload?
2686 return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2687 && loadType != FrameLoadTypeReload
2688 && loadType != FrameLoadTypeReloadFromOrigin
2689 && loadType != FrameLoadTypeSame
2690 && !shouldReload(m_frame->document()->url(), url)
2691 // We don't want to just scroll if a link from within a
2692 // frameset is trying to reload the frameset into _top.
2693 && !m_frame->document()->isFrameSet();
2696 void FrameLoader::scrollToFragmentWithParentBoundary(const KURL& url)
2698 FrameView* view = m_frame->view();
2702 // Leaking scroll position to a cross-origin ancestor would permit the so-called "framesniffing" attack.
2703 RefPtr<Frame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame->document()->findUnsafeParentScrollPropagationBoundary() : 0);
2706 boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
2708 view->scrollToFragment(url);
2711 boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
2714 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2715 const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2717 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2718 loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2721 bool FrameLoader::shouldClose()
2723 Page* page = m_frame->page();
2726 if (!page->chrome().canRunBeforeUnloadConfirmPanel())
2729 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2730 Vector<RefPtr<Frame> > targetFrames;
2731 targetFrames.append(m_frame);
2732 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2733 targetFrames.append(child);
2735 bool shouldClose = false;
2737 NavigationDisablerForBeforeUnload navigationDisabler;
2740 for (i = 0; i < targetFrames.size(); i++) {
2741 if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2743 if (!targetFrames[i]->loader().handleBeforeUnloadEvent(page->chrome(), this))
2747 if (i == targetFrames.size())
2752 m_submittedFormURL = KURL();
2754 m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
2758 bool FrameLoader::handleBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
2760 DOMWindow* domWindow = m_frame->document()->domWindow();
2764 RefPtr<Document> document = m_frame->document();
2765 if (!document->body())
2768 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2769 m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2771 // We store the frame's page in a local variable because the frame might get detached inside dispatchEvent.
2772 Page* page = m_frame->page();
2773 page->incrementFrameHandlingBeforeUnloadEventCount();
2774 domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2775 page->decrementFrameHandlingBeforeUnloadEventCount();
2777 m_pageDismissalEventBeingDispatched = NoDismissal;
2779 if (!beforeUnloadEvent->defaultPrevented())
2780 document->defaultEventHandler(beforeUnloadEvent.get());
2781 if (beforeUnloadEvent->result().isNull())
2784 // If the navigating FrameLoader has already shown a beforeunload confirmation panel for the current navigation attempt,
2785 // this frame is not allowed to cause another one to be shown.
2786 if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
2787 document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation.");
2791 // We should only display the beforeunload dialog for an iframe if its SecurityOrigin matches all
2792 // ancestor frame SecurityOrigins up through the navigating FrameLoader.
2793 if (frameLoaderBeingNavigated != this) {
2794 Frame* parentFrame = m_frame->tree()->parent();
2795 while (parentFrame) {
2796 Document* parentDocument = parentFrame->document();
2797 if (!parentDocument)
2799 if (!m_frame->document() || !m_frame->document()->securityOrigin()->canAccess(parentDocument->securityOrigin())) {
2800 document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show beforeunload confirmation dialog on behalf of a frame with different security origin. Protocols, domains, and ports must match.");
2804 if (&parentFrame->loader() == frameLoaderBeingNavigated)
2807 parentFrame = parentFrame->tree()->parent();
2810 // The navigatingFrameLoader should always be in our ancestory.
2811 ASSERT(parentFrame);
2812 ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
2815 frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
2817 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2818 return chrome.runBeforeUnloadConfirmPanel(text, m_frame);
2821 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2823 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2824 // nil policyDataSource because loading the alternate page will have passed
2825 // through this method already, nested; otherwise, policyDataSource should still be set.
2826 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2828 bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2830 // Two reasons we can't continue:
2831 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
2832 // is the user responding Cancel to the form repost nag sheet.
2833 // 2) User responded Cancel to an alert popped up by the before unload event handler.
2834 bool canContinue = shouldContinue && shouldClose();
2837 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
2838 // need to report that the client redirect was cancelled.
2839 if (m_quickRedirectComing)
2840 clientRedirectCancelledOrFinished(false);
2842 setPolicyDocumentLoader(0);
2844 // If the navigation request came from the back/forward menu, and we punt on it, we have the
2845 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
2846 // we only do this when punting a navigation for the target frame or top-level frame.
2847 if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2848 if (Page* page = m_frame->page()) {
2849 Frame* mainFrame = page->mainFrame();
2850 if (HistoryItem* resetItem = mainFrame->loader().history()->currentItem()) {
2851 page->backForward()->setCurrentItem(resetItem);
2852 m_frame->loader().client()->updateGlobalHistoryItemForPage();
2859 FrameLoadType type = policyChecker()->loadType();
2860 // A new navigation is in progress, so don't clear the history's provisional item.
2861 stopAllLoaders(ShouldNotClearProvisionalItem);
2863 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2864 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
2865 if (!m_frame->page())
2868 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2869 if (Page* page = m_frame->page()) {
2870 if (page->mainFrame() == m_frame)
2871 m_frame->page()->inspectorController()->resume();
2875 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2877 setState(FrameStateProvisional);
2879 setPolicyDocumentLoader(0);
2881 if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
2882 loadProvisionalItemFromCachedPage();
2887 m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
2889 continueLoadAfterWillSubmitForm();
2892 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
2893 const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2895 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2896 loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
2899 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
2900 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2902 if (!shouldContinue)
2905 RefPtr<Frame> frame = m_frame;
2906 RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
2910 if (frameName != "_blank")
2911 mainFrame->tree()->setName(frameName);
2913 mainFrame->page()->setOpenedByDOM();
2914 mainFrame->loader().m_client->dispatchShow();
2915 if (!m_suppressOpenerInNewFrame) {
2916 mainFrame->loader().setOpener(frame.get());
2917 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
2919 mainFrame->loader().loadWithNavigationAction(request, NavigationAction(request), false, FrameLoadTypeStandard, formState);
2922 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
2924 ASSERT(!request.isNull());
2927 if (Page* page = m_frame->page()) {
2928 identifier = page->progress()->createUniqueIdentifier();
2929 notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
2932 ResourceRequest newRequest(request);
2933 notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
2935 if (newRequest.isNull())
2936 error = cancelledError(request);
2938 error = ResourceError();
2940 request = newRequest;
2943 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
2945 newRequest = ResourceRequest(resource->url());
2947 Page* page = m_frame->page();
2951 if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
2954 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
2955 if (resource->type() == CachedResource::MainResource)
2958 if (!page->areMemoryCacheClientCallsEnabled()) {
2959 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2960 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
2961 m_documentLoader->didTellClientAboutLoad(resource->url());
2965 if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
2966 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2967 m_documentLoader->didTellClientAboutLoad(resource->url());
2971 unsigned long identifier;
2972 ResourceError error;
2973 requestFromDelegate(newRequest, identifier, error);
2974 InspectorInstrumentation::markResourceAsCached(page, identifier);
2975 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
2978 void FrameLoader::applyUserAgent(ResourceRequest& request)
2980 String userAgent = this->userAgent(request.url());
2981 ASSERT(!userAgent.isNull());
2982 request.setHTTPUserAgent(userAgent);
2985 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
2987 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptions);
2989 Frame* topFrame = m_frame->tree()->top();
2990 if (m_frame == topFrame)
2993 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
2995 switch (disposition) {
2996 case XFrameOptionsSameOrigin: {
2997 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOrigin);
2998 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
2999 if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
3001 for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
3002 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
3003 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOriginWithBadAncestorChain);
3009 case XFrameOptionsDeny:
3011 case XFrameOptionsAllowAll:
3013 case XFrameOptionsConflict:
3014 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.", requestIdentifier);
3016 case XFrameOptionsInvalid:
3017 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
3020 ASSERT_NOT_REACHED();
3025 void FrameLoader::loadProvisionalItemFromCachedPage()
3027 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
3028 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().stringCenterEllipsizedToLength().utf8().data());
3030 prepareForLoadStart();
3032 m_loadingFromCachedPage = true;
3034 // Should have timing data from previous time(s) the page was shown.
3035 ASSERT(provisionalLoader->timing()->navigationStart());
3036 provisionalLoader->resetTiming();
3037 provisionalLoader->timing()->markNavigationStart();
3039 provisionalLoader->setCommitted(true);
3040 commitProvisionalLoad();
3043 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
3045 if (!history()->currentItem())
3047 return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
3050 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
3052 if (!equalIgnoringCase(url.string(), "about:srcdoc"))
3054 HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
3057 if (!ownerElement->hasTagName(iframeTag))
3059 return ownerElement->fastHasAttribute(srcdocAttr);
3062 void FrameLoader::checkDidPerformFirstNavigation()
3064 Page* page = m_frame->page();
3068 if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3069 m_didPerformFirstNavigation = true;
3070 m_client->didPerformFirstNavigation();
3074 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
3076 Frame* frame = m_frame->tree()->find(name);
3078 // From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
3080 // If the source browsing context is the same as the browsing context
3081 // being navigated, and this browsing context has its seamless browsing
3082 // context flag set, and the browsing context being navigated was not
3083 // chosen using an explicit self-navigation override, then find the
3084 // nearest ancestor browsing context that does not have its seamless
3085 // browsing context flag set, and continue these steps as if that
3086 // browsing context was the one that was going to be navigated instead.
3087 if (frame == m_frame && name != "_self" && m_frame->document()->shouldDisplaySeamlesslyWithParent()) {
3088 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
3089 if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
3094 ASSERT(frame != m_frame);
3097 // FIXME: Eventually all callers should supply the actual activeDocument so we can call canNavigate with the right document.
3098 if (!activeDocument)
3099 activeDocument = m_frame->document();
3101 if (!activeDocument->canNavigate(frame))
3107 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3109 ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3111 // Save user view state to the current history item here since we don't do a normal load.
3112 // FIXME: Does form state need to be saved here too?
3113 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3114 if (FrameView* view = m_frame->view())
3115 view->setWasScrolledByUser(false);
3117 history()->setCurrentItem(item);
3119 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3120 loadInSameDocument(item->url(), item->stateObject(), false);
3122 // Restore user view state from the current history item here since we don't do a normal load.
3123 history()->restoreScrollPositionAndViewState();
3126 // FIXME: This function should really be split into a couple pieces, some of
3127 // which should be methods of HistoryController and some of which should be
3128 // methods of FrameLoader.
3129 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
3131 // Remember this item so we can traverse any child items as child frames load
3132 history()->setProvisionalItem(item);
3134 if (CachedPage* cachedPage = pageCache()->get(item)) {
3135 loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
3139 KURL itemURL = item->url();
3140 KURL itemOriginalURL = item->originalURL();
3142 if (documentLoader())
3143 currentURL = documentLoader()->url();
3144 RefPtr<FormData> formData = item->formData();
3146 ResourceRequest request(itemURL);
3148 if (!item->referrer().isNull())
3149 request.setHTTPReferrer(item->referrer());
3151 // If this was a repost that failed the page cache, we might try to repost the form.
3152 NavigationAction action;
3154 formData->generateFiles(m_frame->document());
3156 request.setHTTPMethod("POST");
3157 request.setHTTPBody(formData);
3158 request.setHTTPContentType(item->formContentType());
3159 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3160 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3162 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3163 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3164 addExtraFieldsToRequest(request, loadType, true);
3166 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3167 // We want to know this before talking to the policy delegate, since it affects whether
3168 // we show the DoYouReallyWantToRepost nag.
3170 // This trick has a small bug (3123893) where we might find a cache hit, but then
3171 // have the item vanish when we try to use it in the ensuing nav. This should be
3172 // extremely rare, but in that case the user will get an error on the navigation.
3174 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3175 request.setCachePolicy(ReturnCacheDataDontLoad);
3176 action = NavigationAction(request, loadType, false);
3178 request.setCachePolicy(ReturnCacheDataElseLoad);
3179 action = NavigationAction(request, NavigationTypeFormResubmitted);
3183 case FrameLoadTypeReload:
3184 case FrameLoadTypeReloadFromOrigin:
3185 request.setCachePolicy(ReloadIgnoringCacheData);
3187 case FrameLoadTypeBack:
3188 case FrameLoadTypeForward:
3189 case FrameLoadTypeIndexedBackForward:
3190 // If the first load within a frame is a navigation within a back/forward list that was attached
3191 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3192 if (m_stateMachine.committedFirstRealDocumentLoad())
3193 request.setCachePolicy(ReturnCacheDataElseLoad);
3195 case FrameLoadTypeStandard:
3196 case FrameLoadTypeRedirectWithLockedBackForwardList:
3198 case FrameLoadTypeSame:
3200 ASSERT_NOT_REACHED();
3203 addExtraFieldsToRequest(request, loadType, true);
3205 ResourceRequest requestForOriginalURL(request);
3206 requestForOriginalURL.setURL(itemOriginalURL);
3207 action = NavigationAction(requestForOriginalURL, loadType, false);
3210 loadWithNavigationAction(request, action, false, loadType, 0);
3213 // Loads content into this frame, as specified by history item
3214 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3216 m_requestedHistoryItem = item;
3217 HistoryItem* currentItem = history()->currentItem();
3218 bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3220 if (sameDocumentNavigation)
3221 loadSameDocumentItem(item);
3223 loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
3226 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3228 ASSERT(m_state == FrameStateProvisional);
3229 ASSERT(!m_loadingFromCachedPage);
3230 // We only use cache-only loads to avoid resubmitting forms.
3231 ASSERT(isBackForwardLoadType(m_loadType));
3232 ASSERT(m_history->provisionalItem()->formData());
3233 ASSERT(m_history->provisionalItem() == m_requestedHistoryItem.get());
3235 FrameLoadType loadType = m_loadType;
3236 HistoryItem* item = m_history->provisionalItem();
3238 stopAllLoaders(ShouldNotClearProvisionalItem);
3239 loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
3242 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3244 ResourceError error = m_client->cancelledError(request);
3245 error.setIsCancellation(true);
3249 void FrameLoader::setTitle(const StringWithDirection& title)
3251 documentLoader()->setTitle(title);
3254 String FrameLoader::referrer() const
3256 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3259 void FrameLoader::dispatchDocumentElementAvailable()
3261 m_frame->injectUserScripts(InjectAtDocumentStart);
3262 m_client->documentElementAvailable();
3265 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3267 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3270 Vector<RefPtr<DOMWrapperWorld> > worlds;
3271 ScriptController::getAllWorlds(worlds);
3272 for (size_t i = 0; i < worlds.size(); ++i)
3273 dispatchDidClearWindowObjectInWorld(worlds[i].get());
3276 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3278 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3281 m_client->dispatchDidClearWindowObjectInWorld(world);
3283 #if ENABLE(INSPECTOR)
3284 if (Page* page = m_frame->page())
3285 page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3288 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3291 void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
3293 Vector<RefPtr<DOMWrapperWorld> > worlds;
3294 ScriptController::getAllWorlds(worlds);
3295 for (size_t i = 0; i < worlds.size(); ++i)
3296 m_client->dispatchGlobalObjectAvailable(worlds[i].get());
3299 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3301 SandboxFlags flags = m_forcedSandboxFlags;
3302 if (Frame* parentFrame = m_frame->tree()->parent())
3303 flags |= parentFrame->document()->sandboxFlags();
3304 if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3305 flags |= ownerElement->sandboxFlags();
3309 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3311 m_client->didChangeTitle(loader);
3313 if (loader == m_documentLoader) {
3314 // Must update the entries in the back-forward list too.
3315 history()->setCurrentItemTitle(loader->title());
3316 // This must go through the WebFrame because it has the right notion of the current b/f item.
3317 m_client->setTitle(loader->title(), loader->urlForHistory());
3318 m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3319 m_client->dispatchDidReceiveTitle(loader->title());
3323 void FrameLoader::didChangeIcons(IconType type)
3325 m_client->dispatchDidChangeIcons(type);
3328 void FrameLoader::dispatchDidCommitLoad()
3330 if (m_stateMachine.creatingInitialEmptyDocument())
3333 m_client->dispatchDidCommitLoad();
3335 if (isLoadingMainFrame()) {
3336 m_frame->page()->resetSeenPlugins();
3337 m_frame->page()->resetSeenMediaEngines();
3340 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3342 if (m_frame->page()->mainFrame() == m_frame)
3343 m_frame->page()->featureObserver()->didCommitLoad();
3347 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3349 ASSERT(m_frame->page());
3350 ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3352 if (!m_documentLoader)
3355 Vector<ResourceRequest> pastLoads;
3356 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3358 size_t size = pastLoads.size();
3359 for (size_t i = 0; i < size; ++i) {
3360 CachedResource* resource = memoryCache()->resourceForRequest(pastLoads[i]);
3362 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3363 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3364 // Consider if there's some efficient way of remembering enough to deliver this client call.
3365 // We have the URL, but not the rest of the response or the length.
3369 ResourceRequest request(resource->url());
3370 m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3374 NetworkingContext* FrameLoader::networkingContext() const
3376 return m_networkingContext.get();
3379 void FrameLoader::loadProgressingStatusChanged()
3381 FrameView* view = m_frame->page()->mainFrame()->view();
3382 view->updateLayerFlushThrottlingInAllFrames();
3383 view->adjustTiledBackingCoverage();
3386 void FrameLoader::forcePageTransitionIfNeeded()
3388 m_client->forcePageTransitionIfNeeded();
3391 bool FrameLoaderClient::hasHTMLView() const
3396 PassRefPtr<Frame> createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3398 ASSERT(!features.dialog || request.frameName().isEmpty());
3400 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3401 if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
3402 if (request.frameName() != "_self") {
3403 if (Page* page = frame->page())
3404 page->chrome().focus();
3411 // Sandboxed frames cannot open new auxiliary browsing contexts.
3412 if (isDocumentSandboxed(openerFrame, SandboxPopups)) {
3413 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
3414 openerFrame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().stringCenterEllipsizedToLength() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
3418 // FIXME: Setting the referrer should be the caller's responsibility.
3419 FrameLoadRequest requestWithReferrer = request;
3420 String referrer = SecurityPolicy::generateReferrerHeader(openerFrame->document()->referrerPolicy(), request.resourceRequest().url(), openerFrame->loader().outgoingReferrer());
3421 if (!referrer.isEmpty())
3422 requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
3423 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader().outgoingOrigin());
3425 if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
3430 Page* oldPage = openerFrame->page();
3434 NavigationAction action(requestWithReferrer.resourceRequest());
3435 Page* page = oldPage->chrome().createWindow(openerFrame, requestWithReferrer, features, action);
3439 Frame* frame = page->mainFrame();
3441 frame->loader().forceSandboxFlags(openerFrame->document()->sandboxFlags());
3443 if (request.frameName() != "_blank")
3444 frame->tree()->setName(request.frameName());
3446 page->chrome().setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3447 page->chrome().setStatusbarVisible(features.statusBarVisible);
3448 page->chrome().setScrollbarsVisible(features.scrollbarsVisible);
3449 page->chrome().setMenubarVisible(features.menuBarVisible);
3450 page->chrome().setResizable(features.resizable);
3452 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3453 // specify the size of the viewport. We can only resize the window, so adjust
3454 // for the difference between the window size and the viewport size.
3456 FloatRect windowRect = page->chrome().windowRect();
3457 FloatSize viewportSize = page->chrome().pageRect().size();
3460 windowRect.setX(features.x);
3462 windowRect.setY(features.y);
3463 // Zero width and height mean using default size, not minumum one.
3464 if (features.widthSet && features.width)
3465 windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
3466 if (features.heightSet && features.height)
3467 windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));
3469 // Ensure non-NaN values, minimum size as well as being within valid screen area.
3470 FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
3472 page->chrome().setWindowRect(newWindowRect);
3473 page->chrome().show();
3479 } // namespace WebCore