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 "MemoryCache.h"
43 #include "CachedPage.h"
44 #include "CachedResourceLoader.h"
46 #include "ChromeClient.h"
48 #include "ContentSecurityPolicy.h"
49 #include "DOMImplementation.h"
50 #include "DOMWindow.h"
51 #include "DatabaseManager.h"
53 #include "DocumentLoadTiming.h"
54 #include "DocumentLoader.h"
56 #include "EditorClient.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"
85 #include "PageCache.h"
86 #include "PageTransitionEvent.h"
87 #include "PlatformStrategies.h"
88 #include "PluginData.h"
89 #include "PluginDatabase.h"
90 #include "PluginDocument.h"
91 #include "PolicyChecker.h"
92 #include "ProgressTracker.h"
93 #include "ResourceHandle.h"
94 #include "ResourceRequest.h"
95 #include "SchemeRegistry.h"
96 #include "ScriptCallStack.h"
97 #include "ScriptController.h"
98 #include "ScriptSourceCode.h"
99 #include "ScrollAnimator.h"
100 #include "SecurityOrigin.h"
101 #include "SecurityPolicy.h"
102 #include "SegmentedString.h"
103 #include "SerializedScriptValue.h"
104 #include "Settings.h"
105 #include "TextResourceDecoder.h"
106 #include "WebCoreMemoryInstrumentation.h"
107 #include "WindowFeatures.h"
108 #include "XMLDocumentParser.h"
109 #include <wtf/CurrentTime.h>
110 #include <wtf/MemoryInstrumentationHashSet.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_forcedSandboxFlags(SandboxNone)
244 FrameLoader::~FrameLoader()
248 HashSet<Frame*>::iterator end = m_openedFrames.end();
249 for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
250 (*it)->loader()->m_opener = 0;
252 m_client->frameLoaderDestroyed();
254 if (m_networkingContext)
255 m_networkingContext->invalidate();
258 void FrameLoader::init()
260 // This somewhat odd set of steps gives the frame an initial empty document.
261 setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData()).get());
262 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
263 m_provisionalDocumentLoader->startLoadingMainResource();
264 m_frame->document()->cancelParsing();
265 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
267 m_networkingContext = m_client->createNetworkingContext();
268 m_progressTracker = FrameProgressTracker::create(m_frame);
271 void FrameLoader::setDefersLoading(bool defers)
273 if (m_documentLoader)
274 m_documentLoader->setDefersLoading(defers);
275 if (m_provisionalDocumentLoader)
276 m_provisionalDocumentLoader->setDefersLoading(defers);
277 if (m_policyDocumentLoader)
278 m_policyDocumentLoader->setDefersLoading(defers);
279 history()->setDefersLoading(defers);
282 m_frame->navigationScheduler()->startTimer();
283 startCheckCompleteTimer();
287 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
289 urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
290 0, lockHistory, lockBackForwardList, MaybeSendReferrer, ReplaceDocumentIfJavaScriptURL);
293 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer)
295 urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
296 triggeringEvent, lockHistory, lockBackForwardList, shouldSendReferrer, DoNotReplaceDocumentIfJavaScriptURL);
299 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
300 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
301 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
303 ASSERT(!m_suppressOpenerInNewFrame);
305 RefPtr<Frame> protect(m_frame);
306 FrameLoadRequest frameRequest(passedRequest);
308 if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
311 if (frameRequest.frameName().isEmpty())
312 frameRequest.setFrameName(m_frame->document()->baseTarget());
314 if (shouldSendReferrer == NeverSendReferrer)
315 m_suppressOpenerInNewFrame = true;
316 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
318 loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, shouldSendReferrer);
320 m_suppressOpenerInNewFrame = false;
323 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
325 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
327 // FIXME: Find a good spot for these.
328 ASSERT(submission->data());
329 ASSERT(submission->state());
330 ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == m_frame);
332 if (!m_frame->page())
335 if (submission->action().isEmpty())
338 if (isDocumentSandboxed(m_frame, SandboxForms)) {
339 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
340 m_frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
344 if (protocolIsJavaScript(submission->action())) {
345 if (!m_frame->document()->contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
347 m_isExecutingJavaScriptFormAction = true;
348 m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
349 m_isExecutingJavaScriptFormAction = false;
353 Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
355 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
358 targetFrame = m_frame;
360 submission->clearTarget();
362 if (!targetFrame->page())
365 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
367 // We do not want to submit more than one form from the same page, nor do we want to submit a single
368 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
369 // The flag is reset in each time we start handle a new mouse or key down event, and
370 // also in setView since this part may get reused for a page from the back/forward cache.
371 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
373 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
374 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
375 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
377 if (m_frame->tree()->isDescendantOf(targetFrame)) {
378 if (m_submittedFormURL == submission->requestURL())
380 m_submittedFormURL = submission->requestURL();
383 submission->data()->generateFiles(m_frame->document());
384 submission->setReferrer(outgoingReferrer());
385 submission->setOrigin(outgoingOrigin());
387 targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
390 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
392 if (m_frame->document() && m_frame->document()->parser())
393 m_frame->document()->parser()->stopParsing();
395 if (unloadEventPolicy != UnloadEventPolicyNone) {
396 if (m_frame->document()) {
397 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
398 Node* currentFocusedNode = m_frame->document()->focusedNode();
399 if (currentFocusedNode && currentFocusedNode->toInputElement())
400 currentFocusedNode->toInputElement()->endEditing();
401 if (m_pageDismissalEventBeingDispatched == NoDismissal) {
402 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
403 m_pageDismissalEventBeingDispatched = PageHideDismissal;
404 m_frame->document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
406 if (!m_frame->document()->inPageCache()) {
407 RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
408 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
409 // while dispatching the event, so protect it to prevent writing the end
410 // time into freed memory.
411 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
412 m_pageDismissalEventBeingDispatched = UnloadDismissal;
413 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
414 DocumentLoadTiming* timing = documentLoader->timing();
415 ASSERT(timing->navigationStart());
416 timing->markUnloadEventStart();
417 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
418 timing->markUnloadEventEnd();
420 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
423 m_pageDismissalEventBeingDispatched = NoDismissal;
424 if (m_frame->document())
425 m_frame->document()->updateStyleIfNeeded();
426 m_wasUnloadEventEmitted = true;
430 // Dispatching the unload event could have made m_frame->document() null.
431 if (m_frame->document() && !m_frame->document()->inPageCache()) {
432 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
433 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
434 && m_frame->document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
436 if (!keepEventListeners)
437 m_frame->document()->removeAllEventListeners();
441 m_isComplete = true; // to avoid calling completed() in finishedParsing()
442 m_didCallImplicitClose = true; // don't want that one either
444 if (m_frame->document() && m_frame->document()->parsing()) {
446 m_frame->document()->setParsing(false);
449 if (Document* doc = m_frame->document()) {
450 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
451 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
452 doc->setReadyState(Document::Complete);
454 #if ENABLE(SQL_DATABASE)
455 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
456 DatabaseManager::manager().stopDatabases(doc, 0);
460 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
461 m_frame->navigationScheduler()->cancel();
464 void FrameLoader::stop()
466 // http://bugs.webkit.org/show_bug.cgi?id=10854
467 // The frame's last ref may be removed and it will be deleted by checkCompleted().
468 RefPtr<Frame> protector(m_frame);
470 if (DocumentParser* parser = m_frame->document()->parser()) {
471 parser->stopParsing();
475 icon()->stopLoader();
478 bool FrameLoader::closeURL()
480 history()->saveDocumentState();
482 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
483 Document* currentDocument = m_frame->document();
484 stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
486 m_frame->editor()->clearUndoRedoOperations();
490 bool FrameLoader::didOpenURL()
492 if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
493 // A redirect was scheduled before the document was created.
494 // This can happen when one frame changes another frame's location.
498 m_frame->navigationScheduler()->cancel();
499 m_frame->editor()->clearLastEditCommand();
501 m_isComplete = false;
502 m_didCallImplicitClose = false;
504 // If we are still in the process of initializing an empty document then
505 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
506 // since it may cause clients to attempt to render the frame.
507 if (!m_stateMachine.creatingInitialEmptyDocument()) {
508 DOMWindow* window = m_frame->document()->domWindow();
509 window->setStatus(String());
510 window->setDefaultStatus(String());
518 void FrameLoader::didExplicitOpen()
520 m_isComplete = false;
521 m_didCallImplicitClose = false;
523 // Calling document.open counts as committing the first real document load.
524 if (!m_stateMachine.committedFirstRealDocumentLoad())
525 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
527 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
528 // from a subsequent window.document.open / window.document.write call.
529 // Canceling redirection here works for all cases because document.open
530 // implicitly precedes document.write.
531 m_frame->navigationScheduler()->cancel();
535 void FrameLoader::cancelAndClear()
537 m_frame->navigationScheduler()->cancel();
542 clear(m_frame->document(), false);
543 m_frame->script()->updatePlatformScriptObjects();
546 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
548 m_frame->editor()->clear();
552 m_needsClear = false;
554 if (!m_frame->document()->inPageCache()) {
555 m_frame->document()->cancelParsing();
556 m_frame->document()->stopActiveDOMObjects();
557 if (m_frame->document()->attached()) {
558 m_frame->document()->prepareForDestruction();
559 m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
563 // Do this after detaching the document so that the unload event works.
564 if (clearWindowProperties) {
565 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->document()->domWindow());
566 m_frame->document()->domWindow()->resetUnlessSuspendedForPageCache();
567 m_frame->script()->clearWindowShell(newDocument->domWindow(), m_frame->document()->inPageCache());
570 m_frame->selection()->prepareForDestruction();
571 m_frame->eventHandler()->clear();
572 if (clearFrameView && m_frame->view())
573 m_frame->view()->clear();
575 // Do not drop the document before the ScriptController and view are cleared
576 // as some destructors might still try to access the document.
577 m_frame->setDocument(0);
579 m_subframeLoader.clear();
581 if (clearScriptObjects)
582 m_frame->script()->clearScriptObjects();
584 m_frame->script()->enableEval();
586 m_frame->navigationScheduler()->clear();
589 m_shouldCallCheckCompleted = false;
590 m_shouldCallCheckLoadComplete = false;
592 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
593 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
596 void FrameLoader::receivedFirstData()
598 dispatchDidCommitLoad();
599 dispatchDidClearWindowObjectsInAllWorlds();
600 dispatchGlobalObjectAvailableInAllWorlds();
602 if (m_documentLoader) {
603 StringWithDirection ptitle = m_documentLoader->title();
604 // If we have a title let the WebView know about it.
605 if (!ptitle.isNull())
606 m_client->dispatchDidReceiveTitle(ptitle);
609 if (!m_documentLoader)
611 if (m_frame->document()->isViewSource())
616 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
619 url = m_frame->document()->url().string();
621 url = m_frame->document()->completeURL(url).string();
623 m_frame->navigationScheduler()->scheduleRedirect(delay, url);
626 void FrameLoader::setOutgoingReferrer(const KURL& url)
628 m_outgoingReferrer = url.strippedForUseAsReferrer();
631 void FrameLoader::didBeginDocument(bool dispatch)
634 m_isComplete = false;
635 m_didCallImplicitClose = false;
636 m_frame->document()->setReadyState(Document::Loading);
638 if (m_pendingStateObject) {
639 m_frame->document()->statePopped(m_pendingStateObject.get());
640 m_pendingStateObject.clear();
644 dispatchDidClearWindowObjectsInAllWorlds();
646 updateFirstPartyForCookies();
647 m_frame->document()->initContentSecurityPolicy();
649 Settings* settings = m_frame->document()->settings();
651 m_frame->document()->cachedResourceLoader()->setImagesEnabled(settings->areImagesEnabled());
652 m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings->loadsImagesAutomatically());
655 if (m_documentLoader) {
656 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
657 if (!dnsPrefetchControl.isEmpty())
658 m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
660 String policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy");
661 if (!policyValue.isEmpty())
662 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Enforce);
664 policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy-Report-Only");
665 if (!policyValue.isEmpty())
666 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Report);
668 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
669 if (!policyValue.isEmpty())
670 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedEnforce);
672 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
673 if (!policyValue.isEmpty())
674 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedReport);
676 String headerContentLanguage = m_documentLoader->response().httpHeaderField("Content-Language");
677 if (!headerContentLanguage.isEmpty()) {
678 size_t commaIndex = headerContentLanguage.find(',');
679 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
680 headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
681 if (!headerContentLanguage.isEmpty())
682 m_frame->document()->setContentLanguage(headerContentLanguage);
686 history()->restoreDocumentState();
689 void FrameLoader::finishedParsing()
691 m_frame->injectUserScripts(InjectAtDocumentEnd);
693 if (m_stateMachine.creatingInitialEmptyDocument())
696 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
697 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
698 // Null-checking the FrameView indicates whether or not we're in the destructor.
699 RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
701 m_client->dispatchDidFinishDocumentLoad();
705 if (!m_frame->view())
706 return; // We are being destroyed by something checkCompleted called.
708 // Check if the scrollbars are really needed for the content.
709 // If not, remove them, relayout, and repaint.
710 m_frame->view()->restoreScrollbar();
711 scrollToFragmentWithParentBoundary(m_frame->document()->url());
714 void FrameLoader::loadDone()
719 bool FrameLoader::allChildrenAreComplete() const
721 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
722 if (!child->loader()->m_isComplete)
728 bool FrameLoader::allAncestorsAreComplete() const
730 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
731 if (!ancestor->loader()->m_isComplete)
737 void FrameLoader::checkCompleted()
739 RefPtr<Frame> protect(m_frame);
740 m_shouldCallCheckCompleted = false;
743 m_frame->view()->handleLoadCompleted();
745 // Have we completed before?
749 // Are we still parsing?
750 if (m_frame->document()->parsing())
753 // Still waiting for images/scripts?
754 if (m_frame->document()->cachedResourceLoader()->requestCount())
757 // Still waiting for elements that don't go through a FrameLoader?
758 if (m_frame->document()->isDelayingLoadEvent())
761 // Any frame that hasn't completed yet?
762 if (!allChildrenAreComplete())
767 m_requestedHistoryItem = 0;
768 m_frame->document()->setReadyState(Document::Complete);
770 checkCallImplicitClose(); // if we didn't do it before
772 m_frame->navigationScheduler()->startTimer();
779 m_frame->view()->handleLoadCompleted();
782 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
784 RefPtr<Frame> protect(m_frame);
786 if (Page* page = m_frame->page()) {
787 if (page->defersLoading())
790 if (m_shouldCallCheckCompleted)
792 if (m_shouldCallCheckLoadComplete)
796 void FrameLoader::startCheckCompleteTimer()
798 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
800 if (m_checkTimer.isActive())
802 m_checkTimer.startOneShot(0);
805 void FrameLoader::scheduleCheckCompleted()
807 m_shouldCallCheckCompleted = true;
808 startCheckCompleteTimer();
811 void FrameLoader::scheduleCheckLoadComplete()
813 m_shouldCallCheckLoadComplete = true;
814 startCheckCompleteTimer();
817 void FrameLoader::checkCallImplicitClose()
819 if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
822 if (!allChildrenAreComplete())
823 return; // still got a frame running -> too early
825 m_didCallImplicitClose = true;
826 m_wasUnloadEventEmitted = false;
827 m_frame->document()->implicitClose();
830 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
834 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
835 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);
836 if (subframeArchive) {
837 childFrame->loader()->loadArchive(subframeArchive.release());
840 #endif // ENABLE(WEB_ARCHIVE)
842 HistoryItem* parentItem = history()->currentItem();
843 // If we're moving in the back/forward list, we might want to replace the content
844 // of this child frame with whatever was there at that point.
845 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
846 && !m_frame->document()->loadEventFinished()) {
847 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
849 childFrame->loader()->loadDifferentDocumentItem(childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
854 childFrame->loader()->loadURL(url, referer, "_self", false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
857 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
858 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
860 ArchiveResource* mainResource = archive->mainResource();
861 ASSERT(mainResource);
865 SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
867 ResourceRequest request(mainResource->url());
869 request.applyWebArchiveHackForMail();
872 RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
873 documentLoader->setArchive(archive.get());
874 load(documentLoader.get());
876 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
878 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
880 String mimeType = mimeTypeIn;
882 if (mimeType.isEmpty())
883 mimeType = mimeTypeFromURL(url);
885 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
886 if (mimeType.isEmpty()) {
887 String decodedPath = decodeURLEscapeSequences(url.path());
888 mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(decodedPath.substring(decodedPath.reverseFind('.') + 1));
892 if (mimeType.isEmpty())
893 return ObjectContentFrame; // Go ahead and hope that we can display the content.
895 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
896 bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
898 bool plugInSupportsMIMEType = false;
901 if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
902 return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
904 if (plugInSupportsMIMEType)
905 return WebCore::ObjectContentNetscapePlugin;
907 if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
908 return WebCore::ObjectContentFrame;
910 return WebCore::ObjectContentNone;
913 String FrameLoader::outgoingReferrer() const
915 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
916 // for why we walk the parent chain for srcdoc documents.
917 Frame* frame = m_frame;
918 while (frame->document()->isSrcdocDocument()) {
919 frame = frame->tree()->parent();
920 // Srcdoc documents cannot be top-level documents, by definition,
921 // because they need to be contained in iframes with the srcdoc.
924 return frame->loader()->m_outgoingReferrer;
927 String FrameLoader::outgoingOrigin() const
929 return m_frame->document()->securityOrigin()->toString();
932 bool FrameLoader::checkIfFormActionAllowedByCSP(const KURL& url) const
934 if (m_submittedFormURL.isEmpty())
937 return m_frame->document()->contentSecurityPolicy()->allowFormAction(url);
940 Frame* FrameLoader::opener()
945 void FrameLoader::setOpener(Frame* opener)
947 if (m_opener && !opener)
948 m_client->didDisownOpener();
951 m_opener->loader()->m_openedFrames.remove(m_frame);
953 opener->loader()->m_openedFrames.add(m_frame);
956 if (m_frame->document())
957 m_frame->document()->initSecurityContext();
960 // FIXME: This does not belong in FrameLoader!
961 void FrameLoader::handleFallbackContent()
963 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
964 if (!owner || !owner->hasTagName(objectTag))
966 static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
969 void FrameLoader::provisionalLoadStarted()
971 if (m_stateMachine.firstLayoutDone())
972 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
973 m_frame->navigationScheduler()->cancel(true);
974 m_client->provisionalLoadStarted();
977 void FrameLoader::resetMultipleFormSubmissionProtection()
979 m_submittedFormURL = KURL();
982 void FrameLoader::updateFirstPartyForCookies()
984 if (m_frame->tree()->parent())
985 setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
987 setFirstPartyForCookies(m_frame->document()->url());
990 void FrameLoader::setFirstPartyForCookies(const KURL& url)
992 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
993 frame->document()->setFirstPartyForCookies(url);
996 // This does the same kind of work that didOpenURL does, except it relies on the fact
997 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
998 void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
1000 // If we have a state object, we cannot also be a new navigation.
1001 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1003 // Update the data source's request with the new URL to fake the URL change
1004 KURL oldURL = m_frame->document()->url();
1005 m_frame->document()->setURL(url);
1006 setOutgoingReferrer(url);
1007 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1008 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1009 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1010 // based on the current request. Must also happen before we openURL and displace the
1011 // scroll position, since adding the BF item will save away scroll state.
1013 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1014 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1015 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1016 // though its load is not yet done. I think this all works out OK, for one because
1017 // we have already saved away the scroll and doc state for the long slow load,
1018 // but it's not an obvious case.
1020 history()->updateBackForwardListForFragmentScroll();
1023 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1025 history()->updateForSameDocumentNavigation();
1027 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1029 m_frame->eventHandler()->stopAutoscrollTimer();
1031 // It's important to model this as a load that starts and immediately finishes.
1032 // Otherwise, the parent frame may think we never finished loading.
1035 // We need to scroll to the fragment whether or not a hash change occurred, since
1036 // the user might have scrolled since the previous navigation.
1037 scrollToFragmentWithParentBoundary(url);
1039 m_isComplete = false;
1042 if (isNewNavigation) {
1043 // This will clear previousItem from the rest of the frame tree that didn't
1044 // doing any loading. We need to make a pass on this now, since for fragment
1045 // navigation we'll not go through a real load and reach Completed state.
1046 checkLoadComplete();
1049 m_client->dispatchDidNavigateWithinPage();
1051 m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1052 m_client->dispatchDidPopStateWithinPage();
1055 m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1056 m_client->dispatchDidChangeLocationWithinPage();
1059 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1060 m_client->didFinishLoad();
1063 bool FrameLoader::isComplete() const
1065 return m_isComplete;
1068 void FrameLoader::completed()
1070 RefPtr<Frame> protect(m_frame);
1072 for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1073 descendant->navigationScheduler()->startTimer();
1075 if (Frame* parent = m_frame->tree()->parent())
1076 parent->loader()->checkCompleted();
1078 if (m_frame->view())
1079 m_frame->view()->maintainScrollPositionAtAnchor(0);
1082 void FrameLoader::started()
1084 for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1085 frame->loader()->m_isComplete = false;
1088 void FrameLoader::prepareForHistoryNavigation()
1090 // If there is no currentItem, but we still want to engage in
1091 // history navigation we need to manufacture one, and update
1092 // the state machine of this frame to impersonate having
1094 RefPtr<HistoryItem> currentItem = history()->currentItem();
1096 currentItem = HistoryItem::create();
1097 currentItem->setLastVisitWasFailure(true);
1098 history()->setCurrentItem(currentItem.get());
1099 frame()->page()->backForward()->setCurrentItem(currentItem.get());
1101 ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1102 stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1103 stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1107 void FrameLoader::prepareForLoadStart()
1109 m_progressTracker->progressStarted();
1110 m_client->dispatchDidStartProvisionalLoad();
1112 // Notify accessibility.
1113 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
1114 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadTypeReload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1115 cache->frameLoadingEventNotification(m_frame, loadingEvent);
1119 void FrameLoader::setupForReplace()
1121 m_client->revertToProvisionalState(m_documentLoader.get());
1122 setState(FrameStateProvisional);
1123 m_provisionalDocumentLoader = m_documentLoader;
1124 m_documentLoader = 0;
1128 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1129 PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
1131 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1132 RefPtr<Frame> protect(m_frame);
1134 KURL url = request.resourceRequest().url();
1136 ASSERT(m_frame->document());
1137 if (!request.requester()->canDisplay(url)) {
1138 reportLocalLoadFailed(m_frame, url.elidedString());
1142 String argsReferrer = request.resourceRequest().httpReferrer();
1143 if (argsReferrer.isEmpty())
1144 argsReferrer = outgoingReferrer();
1146 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), url, argsReferrer);
1147 if (shouldSendReferrer == NeverSendReferrer)
1148 referrer = String();
1150 FrameLoadType loadType;
1151 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1152 loadType = FrameLoadTypeReload;
1153 else if (lockBackForwardList)
1154 loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1156 loadType = FrameLoadTypeStandard;
1158 if (request.resourceRequest().httpMethod() == "POST")
1159 loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1161 loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1163 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1164 // load if frame names have changed.
1165 Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : m_frame;
1167 sourceFrame = m_frame;
1168 Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName());
1169 if (targetFrame && targetFrame != sourceFrame) {
1170 if (Page* page = targetFrame->page())
1171 page->chrome()->focus();
1175 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1176 PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1178 if (m_inStopAllLoaders)
1181 RefPtr<FormState> formState = prpFormState;
1182 bool isFormSubmission = formState;
1184 ResourceRequest request(newURL);
1185 if (!referrer.isEmpty()) {
1186 request.setHTTPReferrer(referrer);
1187 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1188 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1190 #if ENABLE(CACHE_PARTITIONING)
1191 if (m_frame->tree()->top() != m_frame)
1192 request.setCachePartition(m_frame->tree()->top()->document()->securityOrigin()->cachePartition());
1194 addExtraFieldsToRequest(request, newLoadType, true);
1195 if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1196 request.setCachePolicy(ReloadIgnoringCacheData);
1198 ASSERT(newLoadType != FrameLoadTypeSame);
1200 // The search for a target frame is done earlier in the case of form submission.
1201 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1202 if (targetFrame && targetFrame != m_frame) {
1203 targetFrame->loader()->loadURL(newURL, referrer, "_self", lockHistory, newLoadType, event, formState.release());
1207 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1210 NavigationAction action(request, newLoadType, isFormSubmission, event);
1212 if (!targetFrame && !frameName.isEmpty()) {
1213 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1214 request, formState.release(), frameName, this);
1218 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1220 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1221 const String& httpMethod = request.httpMethod();
1223 // Make sure to do scroll to fragment processing even if the URL is
1224 // exactly the same so pages with '#' links and DHTML side effects
1226 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1227 oldDocumentLoader->setTriggeringAction(action);
1228 policyChecker()->stopCheck();
1229 policyChecker()->setLoadType(newLoadType);
1230 policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1231 callContinueFragmentScrollAfterNavigationPolicy, this);
1233 // must grab this now, since this load may stop the previous load and clear this flag
1234 bool isRedirect = m_quickRedirectComing;
1235 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1237 m_quickRedirectComing = false;
1238 if (m_provisionalDocumentLoader)
1239 m_provisionalDocumentLoader->setIsClientRedirect(true);
1240 } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1241 // Example of this case are sites that reload the same URL with a different cookie
1242 // driving the generated content, or a master frame with links that drive a target
1243 // frame, where the user has clicked on the same link repeatedly.
1244 m_loadType = FrameLoadTypeSame;
1248 SubstituteData FrameLoader::defaultSubstituteDataForURL(const KURL& url)
1250 if (!shouldTreatURLAsSrcdocDocument(url))
1251 return SubstituteData();
1252 String srcdoc = m_frame->ownerElement()->fastGetAttribute(srcdocAttr);
1253 ASSERT(!srcdoc.isNull());
1254 CString encodedSrcdoc = srcdoc.utf8();
1255 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL());
1258 void FrameLoader::load(const FrameLoadRequest& passedRequest)
1260 FrameLoadRequest request(passedRequest);
1262 if (m_inStopAllLoaders)
1265 if (!request.frameName().isEmpty()) {
1266 Frame* frame = findFrameForNavigation(request.frameName());
1268 request.setShouldCheckNewWindowPolicy(false);
1269 if (frame->loader() != this) {
1270 frame->loader()->load(request);
1276 if (request.shouldCheckNewWindowPolicy()) {
1277 policyChecker()->checkNewWindowPolicy(NavigationAction(request.resourceRequest(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request.resourceRequest(), 0, request.frameName(), this);
1281 if (!request.hasSubstituteData())
1282 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1284 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request.resourceRequest(), request.substituteData());
1285 if (request.lockHistory() && m_documentLoader)
1286 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1290 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1292 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1293 if (lockHistory && m_documentLoader)
1294 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1296 loader->setTriggeringAction(action);
1297 if (m_documentLoader)
1298 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1300 loadWithDocumentLoader(loader.get(), type, formState);
1303 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1305 ResourceRequest& r = newDocumentLoader->request();
1306 addExtraFieldsToMainResourceRequest(r);
1309 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1310 r.setCachePolicy(ReloadIgnoringCacheData);
1311 type = FrameLoadTypeSame;
1312 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadTypeReload)
1313 type = FrameLoadTypeReload;
1315 type = FrameLoadTypeStandard;
1317 if (m_documentLoader)
1318 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1320 // When we loading alternate content for an unreachable URL that we're
1321 // visiting in the history list, we treat it as a reload so the history list
1322 // is appropriately maintained.
1324 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1325 // shouldn't a more explicit type of reload be defined, that means roughly
1326 // "load without affecting history" ?
1327 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1328 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1329 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1330 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1331 history()->saveDocumentAndScrollState();
1333 ASSERT(type == FrameLoadTypeStandard);
1334 type = FrameLoadTypeReload;
1337 loadWithDocumentLoader(newDocumentLoader, type, 0);
1340 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1342 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1343 RefPtr<Frame> protect(m_frame);
1345 ASSERT(m_client->hasWebView());
1347 // Unfortunately the view must be non-nil, this is ultimately due
1348 // to parser requiring a FrameView. We should fix this dependency.
1350 ASSERT(m_frame->view());
1352 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1355 if (m_frame->document())
1356 m_previousURL = m_frame->document()->url();
1358 policyChecker()->setLoadType(type);
1359 RefPtr<FormState> formState = prpFormState;
1360 bool isFormSubmission = formState;
1362 const KURL& newURL = loader->request().url();
1363 const String& httpMethod = loader->request().httpMethod();
1365 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker()->loadType(), newURL)) {
1366 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1367 NavigationAction action(loader->request(), policyChecker()->loadType(), isFormSubmission);
1369 oldDocumentLoader->setTriggeringAction(action);
1370 policyChecker()->stopCheck();
1371 policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1372 callContinueFragmentScrollAfterNavigationPolicy, this);
1374 if (Frame* parent = m_frame->tree()->parent())
1375 loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
1377 policyChecker()->stopCheck();
1378 setPolicyDocumentLoader(loader);
1379 if (loader->triggeringAction().isEmpty())
1380 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker()->loadType(), isFormSubmission));
1382 if (Element* ownerElement = m_frame->ownerElement()) {
1383 // We skip dispatching the beforeload event if we've already
1384 // committed a real document load because the event would leak
1385 // subsequent activity by the frame which the parent frame isn't
1386 // supposed to learn. For example, if the child frame navigated to
1387 // a new URL, the parent frame shouldn't learn the URL.
1388 if (!m_stateMachine.committedFirstRealDocumentLoad()
1389 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1390 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1395 policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1396 callContinueLoadAfterNavigationPolicy, this);
1400 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1402 ASSERT(!url.isEmpty());
1406 frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
1409 const ResourceRequest& FrameLoader::initialRequest() const
1411 return activeDocumentLoader()->originalRequest();
1414 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1416 ResourceRequest request(url);
1418 unsigned long identifier;
1419 ResourceError error;
1420 requestFromDelegate(request, identifier, error);
1421 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1423 url = request.url();
1425 return error.isNull();
1428 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1430 KURL unreachableURL = docLoader->unreachableURL();
1432 if (unreachableURL.isEmpty())
1435 if (!isBackForwardLoadType(policyChecker()->loadType()))
1438 // We only treat unreachableURLs specially during the delegate callbacks
1439 // for provisional load errors and navigation policy decisions. The former
1440 // case handles well-formed URLs that can't be loaded, and the latter
1441 // case handles malformed URLs and unknown schemes. Loading alternate content
1442 // at other times behaves like a standard load.
1443 DocumentLoader* compareDocumentLoader = 0;
1444 if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1445 compareDocumentLoader = m_policyDocumentLoader.get();
1446 else if (m_delegateIsHandlingProvisionalLoadError)
1447 compareDocumentLoader = m_provisionalDocumentLoader.get();
1449 return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1452 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1454 if (!m_documentLoader)
1457 ResourceRequest request = m_documentLoader->request();
1458 KURL unreachableURL = m_documentLoader->unreachableURL();
1459 if (!unreachableURL.isEmpty())
1460 request.setURL(unreachableURL);
1462 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1463 // We should ask the user for confirmation in this case.
1464 request.setCachePolicy(ReturnCacheDataElseLoad);
1466 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1467 setPolicyDocumentLoader(loader.get());
1469 loader->setOverrideEncoding(encoding);
1471 loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1474 void FrameLoader::reloadWithOverrideURL(const KURL& overrideUrl, bool endToEndReload)
1476 if (!m_documentLoader)
1479 if (overrideUrl.isEmpty())
1482 ResourceRequest request = m_documentLoader->request();
1483 request.setURL(overrideUrl);
1484 reloadWithRequest(request, endToEndReload);
1487 void FrameLoader::reload(bool endToEndReload)
1489 if (!m_documentLoader)
1492 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1493 // Reloading in this case will lose the current contents (see 4151001).
1494 if (m_documentLoader->request().url().isEmpty())
1497 // Replace error-page URL with the URL we were trying to reach.
1498 ResourceRequest initialRequest = m_documentLoader->request();
1499 KURL unreachableURL = m_documentLoader->unreachableURL();
1500 if (!unreachableURL.isEmpty())
1501 initialRequest.setURL(unreachableURL);
1503 reloadWithRequest(initialRequest, endToEndReload);
1506 void FrameLoader::reloadWithRequest(const ResourceRequest& initialRequest, bool endToEndReload)
1508 ASSERT(m_documentLoader);
1510 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1511 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1512 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1514 ResourceRequest& request = loader->request();
1516 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1517 request.setCachePolicy(ReloadIgnoringCacheData);
1519 // If we're about to re-post, set up action so the application can warn the user.
1520 if (request.httpMethod() == "POST")
1521 loader->setTriggeringAction(NavigationAction(request, NavigationTypeFormResubmitted));
1523 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1525 loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1528 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1530 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1531 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1534 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1535 if (m_inStopAllLoaders)
1538 // Calling stopLoading() on the provisional document loader can blow away
1539 // the frame from underneath.
1540 RefPtr<Frame> protect(m_frame);
1542 m_inStopAllLoaders = true;
1544 policyChecker()->stopCheck();
1546 // If no new load is in progress, we should clear the provisional item from history
1547 // before we call stopLoading.
1548 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1549 history()->setProvisionalItem(0);
1551 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1552 child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
1553 if (m_provisionalDocumentLoader)
1554 m_provisionalDocumentLoader->stopLoading();
1555 if (m_documentLoader)
1556 m_documentLoader->stopLoading();
1558 setProvisionalDocumentLoader(0);
1560 m_checkTimer.stop();
1562 m_inStopAllLoaders = false;
1565 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1569 if (deferCheckLoadComplete)
1570 scheduleCheckLoadComplete();
1571 else if (m_frame->page())
1572 checkLoadComplete();
1575 DocumentLoader* FrameLoader::activeDocumentLoader() const
1577 if (m_state == FrameStateProvisional)
1578 return m_provisionalDocumentLoader.get();
1579 return m_documentLoader.get();
1582 bool FrameLoader::isLoading() const
1584 DocumentLoader* docLoader = activeDocumentLoader();
1587 return docLoader->isLoading();
1590 bool FrameLoader::frameHasLoaded() const
1592 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1595 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1597 if (!loader && !m_documentLoader)
1600 ASSERT(loader != m_documentLoader);
1601 ASSERT(!loader || loader->frameLoader() == this);
1603 m_client->prepareForDataSourceReplacement();
1606 // detachChildren() can trigger this frame's unload event, and therefore
1607 // script can run and do just about anything. For example, an unload event that calls
1608 // document.write("") on its parent frame can lead to a recursive detachChildren()
1609 // invocation for this frame. In that case, we can end up at this point with a
1610 // loader that hasn't been deleted but has been detached from its frame. Such a
1611 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1612 // state if we try to use it.
1613 if (loader && !loader->frame())
1616 if (m_documentLoader)
1617 m_documentLoader->detachFromFrame();
1619 m_documentLoader = loader;
1622 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1624 if (m_policyDocumentLoader == loader)
1629 loader->setFrame(m_frame);
1630 if (m_policyDocumentLoader
1631 && m_policyDocumentLoader != m_provisionalDocumentLoader
1632 && m_policyDocumentLoader != m_documentLoader)
1633 m_policyDocumentLoader->detachFromFrame();
1635 m_policyDocumentLoader = loader;
1638 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1640 ASSERT(!loader || !m_provisionalDocumentLoader);
1641 ASSERT(!loader || loader->frameLoader() == this);
1643 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1644 m_provisionalDocumentLoader->detachFromFrame();
1646 m_provisionalDocumentLoader = loader;
1649 double FrameLoader::timeOfLastCompletedLoad()
1651 return storedTimeOfLastCompletedLoad;
1654 void FrameLoader::setState(FrameState newState)
1658 if (newState == FrameStateProvisional)
1659 provisionalLoadStarted();
1660 else if (newState == FrameStateComplete) {
1661 frameLoadCompleted();
1662 storedTimeOfLastCompletedLoad = currentTime();
1663 if (m_documentLoader)
1664 m_documentLoader->stopRecordingResponses();
1668 void FrameLoader::clearProvisionalLoad()
1670 setProvisionalDocumentLoader(0);
1671 m_progressTracker->progressCompleted();
1672 setState(FrameStateComplete);
1675 void FrameLoader::commitProvisionalLoad()
1677 RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1678 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1679 RefPtr<Frame> protect(m_frame);
1681 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1682 m_frame->document() ? m_frame->document()->url().elidedString().utf8().data() : "",
1683 pdl ? pdl->url().elidedString().utf8().data() : "<no provisional DocumentLoader>");
1685 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1686 // We are doing this here because we know for sure that a new page is about to be loaded.
1687 HistoryItem* item = history()->currentItem();
1688 if (!m_frame->tree()->parent() && pageCache()->canCache(m_frame->page()) && !item->isInPageCache())
1689 pageCache()->add(item, m_frame->page());
1691 if (m_loadType != FrameLoadTypeReplace)
1692 closeOldDataSources();
1694 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1695 m_client->makeRepresentation(pdl.get());
1697 transitionToCommitted(cachedPage);
1699 if (pdl && m_documentLoader) {
1700 // Check if the destination page is allowed to access the previous page's timing information.
1701 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1702 m_documentLoader->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_previousURL));
1705 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1706 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1707 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1708 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1709 if (m_sentRedirectNotification)
1710 clientRedirectCancelledOrFinished(false);
1712 if (cachedPage && cachedPage->document()) {
1713 prepareForCachedPageRestore();
1714 cachedPage->restore(m_frame->page());
1716 // The page should be removed from the cache immediately after a restoration in order for the PageCache to be consistent.
1717 pageCache()->remove(history()->currentItem());
1719 dispatchDidCommitLoad();
1721 // If we have a title let the WebView know about it.
1722 StringWithDirection title = m_documentLoader->title();
1723 if (!title.isNull())
1724 m_client->dispatchDidReceiveTitle(title);
1729 pageCache()->remove(history()->currentItem());
1733 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1734 m_frame->document() ? m_frame->document()->url().elidedString().utf8().data() : "");
1736 if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1737 history()->updateForClientRedirect();
1739 if (m_loadingFromCachedPage) {
1740 m_frame->document()->documentDidResumeFromPageCache();
1742 // Force a layout to update view size and thereby update scrollbars.
1743 m_frame->view()->forceLayout();
1745 const ResponseVector& responses = m_documentLoader->responses();
1746 size_t count = responses.size();
1747 for (size_t i = 0; i < count; i++) {
1748 const ResourceResponse& response = responses[i];
1749 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1750 ResourceError error;
1751 unsigned long identifier;
1752 ResourceRequest request(response.url());
1753 requestFromDelegate(request, identifier, error);
1754 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1755 // However, with today's computers and networking speeds, this won't happen in practice.
1756 // Could be an issue with a giant local file.
1757 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1760 // FIXME: Why only this frame and not parent frames?
1761 checkLoadCompleteForThisFrame();
1765 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1767 ASSERT(m_client->hasWebView());
1768 ASSERT(m_state == FrameStateProvisional);
1770 if (m_state != FrameStateProvisional)
1773 if (FrameView* view = m_frame->view()) {
1774 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
1775 scrollAnimator->cancelAnimations();
1778 m_client->setCopiesOnScroll();
1779 history()->updateForCommit();
1781 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1782 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1783 // or the two will stomp each other.
1784 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1785 if (m_documentLoader)
1787 if (pdl != m_provisionalDocumentLoader)
1790 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1791 if (m_documentLoader)
1792 m_documentLoader->stopLoadingSubresources();
1793 if (m_documentLoader)
1794 m_documentLoader->stopLoadingPlugIns();
1796 setDocumentLoader(m_provisionalDocumentLoader.get());
1797 setProvisionalDocumentLoader(0);
1799 if (pdl != m_documentLoader) {
1800 ASSERT(m_state == FrameStateComplete);
1804 setState(FrameStateCommittedPage);
1806 #if ENABLE(TOUCH_EVENTS)
1807 if (isLoadingMainFrame())
1808 m_frame->page()->chrome()->client()->needTouchEvents(false);
1811 // Handle adding the URL to the back/forward list.
1812 DocumentLoader* dl = m_documentLoader.get();
1814 switch (m_loadType) {
1815 case FrameLoadTypeForward:
1816 case FrameLoadTypeBack:
1817 case FrameLoadTypeIndexedBackForward:
1818 if (m_frame->page()) {
1819 // If the first load within a frame is a navigation within a back/forward list that was attached
1820 // without any of the items being loaded then we need to update the history in a similar manner as
1821 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1822 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1823 history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1825 history()->updateForBackForwardNavigation();
1827 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1828 if (history()->currentItem() && !cachedPage)
1829 m_pendingStateObject = history()->currentItem()->stateObject();
1831 // Create a document view for this document, or used the cached view.
1833 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1834 ASSERT(cachedDocumentLoader);
1835 cachedDocumentLoader->setFrame(m_frame);
1836 m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1839 m_client->transitionToCommittedForNewPage();
1843 case FrameLoadTypeReload:
1844 case FrameLoadTypeReloadFromOrigin:
1845 case FrameLoadTypeSame:
1846 case FrameLoadTypeReplace:
1847 history()->updateForReload();
1848 m_client->transitionToCommittedForNewPage();
1851 case FrameLoadTypeStandard:
1852 history()->updateForStandardLoad();
1853 if (m_frame->view())
1854 m_frame->view()->setScrollbarsSuppressed(true);
1855 m_client->transitionToCommittedForNewPage();
1858 case FrameLoadTypeRedirectWithLockedBackForwardList:
1859 history()->updateForRedirectWithLockedBackForwardList();
1860 m_client->transitionToCommittedForNewPage();
1863 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1864 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1866 ASSERT_NOT_REACHED();
1869 m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
1871 // Tell the client we've committed this URL.
1872 ASSERT(m_frame->view());
1874 if (m_stateMachine.creatingInitialEmptyDocument())
1877 if (!m_stateMachine.committedFirstRealDocumentLoad())
1878 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1881 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1883 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1884 // the redirect succeeded. We should either rename this API, or add a new method, like
1885 // -webView:didFinishClientRedirectForFrame:
1886 m_client->dispatchDidCancelClientRedirect();
1888 if (!cancelWithLoadInProgress)
1889 m_quickRedirectComing = false;
1891 m_sentRedirectNotification = false;
1894 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
1896 m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
1898 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
1899 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
1900 m_sentRedirectNotification = true;
1902 // If a "quick" redirect comes in, we set a special mode so we treat the next
1903 // load as part of the original navigation. If we don't have a document loader, we have
1904 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
1905 // Loads triggered by JavaScript form submissions never count as quick redirects.
1906 m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
1909 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
1911 // This function implements the rule: "Don't reload if navigating by fragment within
1912 // the same URL, but do reload if going to a new URL or to the same URL with no
1913 // fragment identifier at all."
1914 if (!destinationURL.hasFragmentIdentifier())
1916 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
1919 void FrameLoader::closeOldDataSources()
1921 // FIXME: Is it important for this traversal to be postorder instead of preorder?
1922 // If so, add helpers for postorder traversal, and use them. If not, then lets not
1923 // use a recursive algorithm here.
1924 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1925 child->loader()->closeOldDataSources();
1927 if (m_documentLoader)
1928 m_client->dispatchWillClose();
1930 m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
1933 void FrameLoader::prepareForCachedPageRestore()
1935 ASSERT(!m_frame->tree()->parent());
1936 ASSERT(m_frame->page());
1937 ASSERT(m_frame->page()->mainFrame() == m_frame);
1939 m_frame->navigationScheduler()->cancel();
1941 // We still have to close the previous part page.
1944 // Delete old status bar messages (if it _was_ activated on last URL).
1945 if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
1946 DOMWindow* window = m_frame->document()->domWindow();
1947 window->setStatus(String());
1948 window->setDefaultStatus(String());
1952 void FrameLoader::open(CachedFrameBase& cachedFrame)
1954 m_isComplete = false;
1956 // Don't re-emit the load event.
1957 m_didCallImplicitClose = true;
1959 KURL url = cachedFrame.url();
1961 // FIXME: I suspect this block of code doesn't do anything.
1962 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
1966 Document* document = cachedFrame.document();
1968 ASSERT(document->domWindow());
1970 clear(document, true, true, cachedFrame.isMainFrame());
1972 document->setInPageCache(false);
1974 m_needsClear = true;
1975 m_isComplete = false;
1976 m_didCallImplicitClose = false;
1977 m_outgoingReferrer = url.string();
1979 FrameView* view = cachedFrame.view();
1981 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
1983 view->setWasScrolledByUser(false);
1985 // Use the current ScrollView's frame rect.
1986 if (m_frame->view())
1987 view->setFrameRect(m_frame->view()->frameRect());
1988 m_frame->setView(view);
1990 m_frame->setDocument(document);
1991 document->domWindow()->resumeFromPageCache();
1993 updateFirstPartyForCookies();
1995 cachedFrame.restore();
1998 bool FrameLoader::isHostedByObjectElement() const
2000 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2001 return owner && owner->hasTagName(objectTag);
2004 bool FrameLoader::isLoadingMainFrame() const
2006 Page* page = m_frame->page();
2007 return page && m_frame == page->mainFrame();
2010 bool FrameLoader::isReplacing() const
2012 return m_loadType == FrameLoadTypeReplace;
2015 void FrameLoader::setReplacing()
2017 m_loadType = FrameLoadTypeReplace;
2020 bool FrameLoader::subframeIsLoading() const
2022 // It's most likely that the last added frame is the last to load so we walk backwards.
2023 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2024 FrameLoader* childLoader = child->loader();
2025 DocumentLoader* documentLoader = childLoader->documentLoader();
2026 if (documentLoader && documentLoader->isLoadingInAPISense())
2028 documentLoader = childLoader->provisionalDocumentLoader();
2029 if (documentLoader && documentLoader->isLoadingInAPISense())
2031 documentLoader = childLoader->policyDocumentLoader();
2038 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2040 m_client->willChangeTitle(loader);
2043 FrameLoadType FrameLoader::loadType() const
2048 CachePolicy FrameLoader::subresourceCachePolicy() const
2051 return CachePolicyVerify;
2053 if (m_loadType == FrameLoadTypeReloadFromOrigin)
2054 return CachePolicyReload;
2056 if (Frame* parentFrame = m_frame->tree()->parent()) {
2057 CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
2058 if (parentCachePolicy != CachePolicyVerify)
2059 return parentCachePolicy;
2062 if (m_loadType == FrameLoadTypeReload)
2063 return CachePolicyRevalidate;
2065 const ResourceRequest& request(documentLoader()->request());
2067 if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2068 return CachePolicyRevalidate;
2071 if (request.cachePolicy() == ReturnCacheDataElseLoad)
2072 return CachePolicyHistoryBuffer;
2074 return CachePolicyVerify;
2077 void FrameLoader::checkLoadCompleteForThisFrame()
2079 ASSERT(m_client->hasWebView());
2081 Settings* settings = m_frame->settings();
2084 case FrameStateProvisional: {
2085 if (m_delegateIsHandlingProvisionalLoadError)
2088 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2092 // If we've received any errors we may be stuck in the provisional state and actually complete.
2093 const ResourceError& error = pdl->mainDocumentError();
2097 // Check all children first.
2098 RefPtr<HistoryItem> item;
2099 if (Page* page = m_frame->page())
2100 if (isBackForwardLoadType(loadType()))
2101 // Reset the back forward list to the last committed history item at the top level.
2102 item = page->mainFrame()->loader()->history()->currentItem();
2104 // Only reset if we aren't already going to a new provisional item.
2105 bool shouldReset = !history()->provisionalItem();
2106 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2107 m_delegateIsHandlingProvisionalLoadError = true;
2108 m_client->dispatchDidFailProvisionalLoad(error);
2109 m_delegateIsHandlingProvisionalLoadError = false;
2111 ASSERT(!pdl->isLoading());
2113 // If we're in the middle of loading multipart data, we need to restore the document loader.
2114 if (isReplacing() && !m_documentLoader.get())
2115 setDocumentLoader(m_provisionalDocumentLoader.get());
2117 // Finish resetting the load state, but only if another load hasn't been started by the
2118 // delegate callback.
2119 if (pdl == m_provisionalDocumentLoader)
2120 clearProvisionalLoad();
2121 else if (activeDocumentLoader()) {
2122 KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2123 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2124 shouldReset = false;
2127 if (shouldReset && item)
2128 if (Page* page = m_frame->page()) {
2129 page->backForward()->setCurrentItem(item.get());
2130 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2135 case FrameStateCommittedPage: {
2136 DocumentLoader* dl = m_documentLoader.get();
2137 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2140 setState(FrameStateComplete);
2142 // FIXME: Is this subsequent work important if we already navigated away?
2143 // Maybe there are bugs because of that, or extra work we can skip because
2144 // the new page is ready.
2146 m_client->forceLayoutForNonHTML();
2148 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2149 if (m_frame->page()) {
2150 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2151 history()->restoreScrollPositionAndViewState();
2154 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2157 if (!settings->needsDidFinishLoadOrderQuirk()) {
2158 m_progressTracker->progressCompleted();
2159 if (Page* page = m_frame->page()) {
2160 if (m_frame == page->mainFrame())
2161 page->resetRelevantPaintedObjectCounter();
2165 const ResourceError& error = dl->mainDocumentError();
2167 AXObjectCache::AXLoadingEvent loadingEvent;
2168 if (!error.isNull()) {
2169 m_client->dispatchDidFailLoad(error);
2170 loadingEvent = AXObjectCache::AXLoadingFailed;
2172 m_client->dispatchDidFinishLoad();
2173 loadingEvent = AXObjectCache::AXLoadingFinished;
2176 if (settings->needsDidFinishLoadOrderQuirk()) {
2177 m_progressTracker->progressCompleted();
2178 if (Page* page = m_frame->page()) {
2179 if (m_frame == page->mainFrame())
2180 page->resetRelevantPaintedObjectCounter();
2184 // Notify accessibility.
2185 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
2186 cache->frameLoadingEventNotification(m_frame, loadingEvent);
2191 case FrameStateComplete:
2192 m_loadType = FrameLoadTypeStandard;
2193 frameLoadCompleted();
2197 ASSERT_NOT_REACHED();
2200 void FrameLoader::continueLoadAfterWillSubmitForm()
2202 if (!m_provisionalDocumentLoader)
2205 prepareForLoadStart();
2207 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2208 // so we need to null check it again.
2209 if (!m_provisionalDocumentLoader)
2212 DocumentLoader* activeDocLoader = activeDocumentLoader();
2213 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2216 m_loadingFromCachedPage = false;
2217 m_provisionalDocumentLoader->startLoadingMainResource();
2220 static KURL originatingURLFromBackForwardList(Page* page)
2222 // FIXME: Can this logic be replaced with m_frame->document()->firstPartyForCookies()?
2223 // It has the same meaning of "page a user thinks is the current one".
2226 int backCount = page->backForward()->backCount();
2227 for (int backIndex = 0; backIndex <= backCount; backIndex++) {
2228 // FIXME: At one point we had code here to check a "was user gesture" flag.
2229 // Do we need to restore that logic?
2230 HistoryItem* historyItem = page->backForward()->itemAtIndex(-backIndex);
2234 originalURL = historyItem->originalURL();
2235 if (!originalURL.isNull())
2242 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2246 // If there is no referrer, assume that the download was initiated directly, so current document is
2247 // completely unrelated to it. See <rdar://problem/5294691>.
2248 // FIXME: Referrer is not sent in many other cases, so we will often miss this important information.
2249 // Find a better way to decide whether the download was unrelated to current document.
2250 if (!request.httpReferrer().isNull()) {
2251 // find the first item in the history that was originated by the user
2252 originalURL = originatingURLFromBackForwardList(m_frame->page());
2255 if (originalURL.isNull())
2256 originalURL = request.url();
2258 if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
2259 unsigned port = originalURL.port();
2261 // 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.
2262 // 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.
2263 String hostOnlyURLString;
2265 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ":", String::number(port));
2267 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
2269 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2270 request.setFirstPartyForCookies(KURL(KURL(), hostOnlyURLString));
2274 void FrameLoader::didLayout(LayoutMilestones milestones)
2276 m_client->dispatchDidLayout(milestones);
2279 void FrameLoader::didFirstLayout()
2281 if (m_frame->page() && isBackForwardLoadType(m_loadType))
2282 history()->restoreScrollPositionAndViewState();
2284 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2285 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2288 void FrameLoader::frameLoadCompleted()
2290 // Note: Can be called multiple times.
2292 m_client->frameLoadCompleted();
2294 history()->updateForFrameLoadCompleted();
2296 // After a canceled provisional load, firstLayoutDone is false.
2297 // Reset it to true if we're displaying a page.
2298 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2299 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2302 void FrameLoader::detachChildren()
2304 typedef Vector<RefPtr<Frame> > FrameVector;
2305 FrameVector childrenToDetach;
2306 childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2307 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2308 childrenToDetach.append(child);
2309 FrameVector::iterator end = childrenToDetach.end();
2310 for (FrameVector::iterator it = childrenToDetach.begin(); it != end; ++it)
2311 (*it)->loader()->detachFromParent();
2314 void FrameLoader::closeAndRemoveChild(Frame* child)
2316 child->tree()->detachFromParent();
2319 if (child->ownerElement() && child->page())
2320 child->page()->decrementSubframeCount();
2321 child->willDetachPage();
2322 child->detachFromPage();
2324 m_frame->tree()->removeChild(child);
2327 // Called every time a resource is completely loaded or an error is received.
2328 void FrameLoader::checkLoadComplete()
2330 ASSERT(m_client->hasWebView());
2332 m_shouldCallCheckLoadComplete = false;
2334 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2335 // is currently needed in order to null out the previous history item for all frames.
2336 if (Page* page = m_frame->page()) {
2337 Vector<RefPtr<Frame>, 10> frames;
2338 for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2339 frames.append(frame);
2340 // To process children before their parents, iterate the vector backwards.
2341 for (size_t i = frames.size(); i; --i)
2342 frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
2346 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2349 return m_frame->document()->cachedResourceLoader()->requestCount();
2352 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2353 count += frame->document()->cachedResourceLoader()->requestCount();
2357 String FrameLoader::userAgent(const KURL& url) const
2359 String userAgent = m_client->userAgent(url);
2360 InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2364 void FrameLoader::handledOnloadEvents()
2366 m_client->dispatchDidHandleOnloadEvents();
2368 if (documentLoader())
2369 documentLoader()->handledOnloadEvents();
2372 void FrameLoader::frameDetached()
2375 m_frame->document()->stopActiveDOMObjects();
2379 void FrameLoader::detachFromParent()
2381 RefPtr<Frame> protect(m_frame);
2384 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2386 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2387 // will trigger the unload event handlers of any child frames, and those event
2388 // handlers might start a new subresource load in this frame.
2391 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2393 detachViewsAndDocumentLoader();
2395 m_progressTracker.clear();
2397 if (Frame* parent = m_frame->tree()->parent()) {
2398 parent->loader()->closeAndRemoveChild(m_frame);
2399 parent->loader()->scheduleCheckCompleted();
2401 m_frame->setView(0);
2402 m_frame->willDetachPage();
2403 m_frame->detachFromPage();
2407 void FrameLoader::detachViewsAndDocumentLoader()
2409 m_client->detachedFromParent2();
2410 setDocumentLoader(0);
2411 m_client->detachedFromParent3();
2414 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2416 addExtraFieldsToRequest(request, m_loadType, false);
2419 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2421 // FIXME: Using m_loadType seems wrong for some callers.
2422 // If we are only preparing to load the main resource, that is previous load's load type!
2423 addExtraFieldsToRequest(request, m_loadType, true);
2426 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2428 // Don't set the cookie policy URL if it's already been set.
2429 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2430 if (request.firstPartyForCookies().isEmpty()) {
2431 if (mainResource && isLoadingMainFrame())
2432 request.setFirstPartyForCookies(request.url());
2433 else if (Document* document = m_frame->document())
2434 request.setFirstPartyForCookies(document->firstPartyForCookies());
2437 // The remaining modifications are only necessary for HTTP and HTTPS.
2438 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2441 applyUserAgent(request);
2443 if (!mainResource) {
2444 if (request.isConditional())
2445 request.setCachePolicy(ReloadIgnoringCacheData);
2446 else if (documentLoader()->isLoadingInAPISense()) {
2447 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2448 // original request cache policy for two reasons:
2449 // 1. For POST requests, we mutate the cache policy for the main resource,
2450 // but we do not want this to apply to subresources
2451 // 2. Delegates that modify the cache policy using willSendRequest: should
2452 // not affect any other resources. Such changes need to be done
2454 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2455 // 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.
2456 // This policy is set on initial request too, but should not be inherited.
2457 ResourceRequestCachePolicy subresourceCachePolicy = (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2458 request.setCachePolicy(subresourceCachePolicy);
2460 request.setCachePolicy(UseProtocolCachePolicy);
2462 // FIXME: Other FrameLoader functions have duplicated code for setting cache policy of main request when reloading.
2463 // It seems better to manage it explicitly than to hide the logic inside addExtraFieldsToRequest().
2464 } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2465 request.setCachePolicy(ReloadIgnoringCacheData);
2467 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2468 if (loadType == FrameLoadTypeReload)
2469 request.setHTTPHeaderField("Cache-Control", "max-age=0");
2470 else if (loadType == FrameLoadTypeReloadFromOrigin) {
2471 request.setHTTPHeaderField("Cache-Control", "no-cache");
2472 request.setHTTPHeaderField("Pragma", "no-cache");
2477 request.setHTTPAccept(defaultAcceptHeader);
2479 // Make sure we send the Origin header.
2480 addHTTPOriginIfNeeded(request, String());
2482 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2483 Settings* settings = m_frame->settings();
2484 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame->document()->encoding(), settings ? settings->defaultTextEncodingName() : String());
2487 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2489 if (!request.httpOrigin().isEmpty())
2490 return; // Request already has an Origin header.
2492 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2493 // For example, if an intranet page has a hyperlink to an external web
2494 // site, we don't want to include the Origin of the request because it
2495 // will leak the internal host name. Similar privacy concerns have lead
2496 // to the widespread suppression of the Referer header at the network
2498 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2501 // For non-GET and non-HEAD methods, always send an Origin header so the
2502 // server knows we support this feature.
2504 if (origin.isEmpty()) {
2505 // If we don't know what origin header to attach, we attach the value
2506 // for an empty origin.
2507 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2511 request.setHTTPOrigin(origin);
2514 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2516 RefPtr<FormState> formState = prpFormState;
2518 // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a
2519 // bunch of parameters that would come in here and then be built back up to a ResourceRequest. In case
2520 // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2521 // from scratch as it did all along.
2522 const KURL& url = inRequest.url();
2523 RefPtr<FormData> formData = inRequest.httpBody();
2524 const String& contentType = inRequest.httpContentType();
2525 String origin = inRequest.httpOrigin();
2527 ResourceRequest workingResourceRequest(url);
2529 if (!referrer.isEmpty())
2530 workingResourceRequest.setHTTPReferrer(referrer);
2531 workingResourceRequest.setHTTPOrigin(origin);
2532 workingResourceRequest.setHTTPMethod("POST");
2533 workingResourceRequest.setHTTPBody(formData);
2534 workingResourceRequest.setHTTPContentType(contentType);
2535 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2537 NavigationAction action(workingResourceRequest, loadType, true, event);
2539 if (!frameName.isEmpty()) {
2540 // The search for a target frame is done earlier in the case of form submission.
2541 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2542 targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2544 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2546 // must grab this now, since this load may stop the previous load and clear this flag
2547 bool isRedirect = m_quickRedirectComing;
2548 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2550 m_quickRedirectComing = false;
2551 if (m_provisionalDocumentLoader)
2552 m_provisionalDocumentLoader->setIsClientRedirect(true);
2557 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2559 ASSERT(m_frame->document());
2560 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), outgoingReferrer());
2562 ResourceRequest initialRequest = request;
2563 initialRequest.setTimeoutInterval(10);
2565 if (!referrer.isEmpty())
2566 initialRequest.setHTTPReferrer(referrer);
2567 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2569 if (Page* page = m_frame->page())
2570 initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url());
2572 addExtraFieldsToSubresourceRequest(initialRequest);
2574 unsigned long identifier = 0;
2575 ResourceRequest newRequest(initialRequest);
2576 requestFromDelegate(newRequest, identifier, error);
2578 if (error.isNull()) {
2579 ASSERT(!newRequest.isNull());
2581 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2582 #if USE(PLATFORM_STRATEGIES)
2583 platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, error, response, data);
2585 ResourceHandle::loadResourceSynchronously(networkingContext(), newRequest, storedCredentials, error, response, data);
2587 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2590 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data.data(), data.size(), -1, error);
2594 const ResourceRequest& FrameLoader::originalRequest() const
2596 return activeDocumentLoader()->originalRequestCopy();
2599 void FrameLoader::receivedMainResourceError(const ResourceError& error)
2601 // Retain because the stop may release the last reference to it.
2602 RefPtr<Frame> protect(m_frame);
2604 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2605 // FIXME: Don't want to do this if an entirely new load is going, so should check
2606 // that both data sources on the frame are either this or nil.
2608 if (m_client->shouldFallBack(error))
2609 handleFallbackContent();
2611 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2612 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2613 m_submittedFormURL = KURL();
2615 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2616 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2617 // so that the existing view (that wenever got far enough to replace) can continue being used.
2618 history()->invalidateCurrentItemCachedPage();
2620 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2621 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2622 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2623 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2625 if (m_sentRedirectNotification)
2626 clientRedirectCancelledOrFinished(false);
2630 if (m_frame->page())
2631 checkLoadComplete();
2634 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2635 const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2637 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2638 loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2641 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2643 m_quickRedirectComing = false;
2645 if (!shouldContinue)
2648 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2649 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2650 m_provisionalDocumentLoader->stopLoading();
2651 setProvisionalDocumentLoader(0);
2654 bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;
2655 loadInSameDocument(request.url(), 0, !isRedirect);
2658 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2660 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2661 // currently displaying a frameset, or if the URL does not have a fragment.
2662 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2664 // FIXME: What about load types other than Standard and Reload?
2666 return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2667 && loadType != FrameLoadTypeReload
2668 && loadType != FrameLoadTypeReloadFromOrigin
2669 && loadType != FrameLoadTypeSame
2670 && !shouldReload(m_frame->document()->url(), url)
2671 // We don't want to just scroll if a link from within a
2672 // frameset is trying to reload the frameset into _top.
2673 && !m_frame->document()->isFrameSet();
2676 void FrameLoader::scrollToFragmentWithParentBoundary(const KURL& url)
2678 FrameView* view = m_frame->view();
2682 // Leaking scroll position to a cross-origin ancestor would permit the so-called "framesniffing" attack.
2683 RefPtr<Frame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame->document()->findUnsafeParentScrollPropagationBoundary() : 0);
2686 boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
2688 view->scrollToFragment(url);
2691 boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
2694 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2695 const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2697 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2698 loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2701 bool FrameLoader::shouldClose()
2703 Page* page = m_frame->page();
2704 Chrome* chrome = page ? page->chrome() : 0;
2705 if (!chrome || !chrome->canRunBeforeUnloadConfirmPanel())
2708 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2709 Vector<RefPtr<Frame> > targetFrames;
2710 targetFrames.append(m_frame);
2711 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2712 targetFrames.append(child);
2714 bool shouldClose = false;
2716 NavigationDisablerForBeforeUnload navigationDisabler;
2719 for (i = 0; i < targetFrames.size(); i++) {
2720 if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2722 if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(chrome))
2726 if (i == targetFrames.size())
2731 m_submittedFormURL = KURL();
2736 bool FrameLoader::fireBeforeUnloadEvent(Chrome* chrome)
2738 DOMWindow* domWindow = m_frame->document()->domWindow();
2742 RefPtr<Document> document = m_frame->document();
2743 if (!document->body())
2746 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2747 m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2748 domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2749 m_pageDismissalEventBeingDispatched = NoDismissal;
2751 if (!beforeUnloadEvent->defaultPrevented())
2752 document->defaultEventHandler(beforeUnloadEvent.get());
2753 if (beforeUnloadEvent->result().isNull())
2756 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2757 return chrome->runBeforeUnloadConfirmPanel(text, m_frame);
2760 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2762 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2763 // nil policyDataSource because loading the alternate page will have passed
2764 // through this method already, nested; otherwise, policyDataSource should still be set.
2765 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2767 bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2769 // Two reasons we can't continue:
2770 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
2771 // is the user responding Cancel to the form repost nag sheet.
2772 // 2) User responded Cancel to an alert popped up by the before unload event handler.
2773 bool canContinue = shouldContinue && shouldClose();
2776 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
2777 // need to report that the client redirect was cancelled.
2778 if (m_quickRedirectComing)
2779 clientRedirectCancelledOrFinished(false);
2781 setPolicyDocumentLoader(0);
2783 // If the navigation request came from the back/forward menu, and we punt on it, we have the
2784 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
2785 // we only do this when punting a navigation for the target frame or top-level frame.
2786 if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2787 if (Page* page = m_frame->page()) {
2788 Frame* mainFrame = page->mainFrame();
2789 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem()) {
2790 page->backForward()->setCurrentItem(resetItem);
2791 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2798 FrameLoadType type = policyChecker()->loadType();
2799 // A new navigation is in progress, so don't clear the history's provisional item.
2800 stopAllLoaders(ShouldNotClearProvisionalItem);
2802 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2803 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
2804 if (!m_frame->page())
2807 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2808 if (Page* page = m_frame->page()) {
2809 if (page->mainFrame() == m_frame)
2810 m_frame->page()->inspectorController()->resume();
2814 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2816 setState(FrameStateProvisional);
2818 setPolicyDocumentLoader(0);
2820 if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
2821 loadProvisionalItemFromCachedPage();
2826 m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
2828 continueLoadAfterWillSubmitForm();
2831 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
2832 const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2834 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2835 loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
2838 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
2839 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2841 if (!shouldContinue)
2844 RefPtr<Frame> frame = m_frame;
2845 RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
2849 if (frameName != "_blank")
2850 mainFrame->tree()->setName(frameName);
2852 mainFrame->page()->setOpenedByDOM();
2853 mainFrame->loader()->m_client->dispatchShow();
2854 if (!m_suppressOpenerInNewFrame) {
2855 mainFrame->loader()->setOpener(frame.get());
2856 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
2858 mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(request), false, FrameLoadTypeStandard, formState);
2861 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
2863 ASSERT(!request.isNull());
2866 if (Page* page = m_frame->page()) {
2867 identifier = page->progress()->createUniqueIdentifier();
2868 notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
2871 ResourceRequest newRequest(request);
2872 notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
2874 if (newRequest.isNull())
2875 error = cancelledError(request);
2877 error = ResourceError();
2879 request = newRequest;
2882 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
2884 newRequest = ResourceRequest(resource->url());
2886 Page* page = m_frame->page();
2890 if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
2893 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
2894 if (resource->type() == CachedResource::MainResource)
2897 if (!page->areMemoryCacheClientCallsEnabled()) {
2898 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2899 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
2900 m_documentLoader->didTellClientAboutLoad(resource->url());
2904 if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
2905 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2906 m_documentLoader->didTellClientAboutLoad(resource->url());
2910 unsigned long identifier;
2911 ResourceError error;
2912 requestFromDelegate(newRequest, identifier, error);
2913 InspectorInstrumentation::markResourceAsCached(page, identifier);
2914 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
2917 void FrameLoader::applyUserAgent(ResourceRequest& request)
2919 String userAgent = this->userAgent(request.url());
2920 ASSERT(!userAgent.isNull());
2921 request.setHTTPUserAgent(userAgent);
2924 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
2926 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptions);
2928 Frame* topFrame = m_frame->tree()->top();
2929 if (m_frame == topFrame)
2932 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
2934 switch (disposition) {
2935 case XFrameOptionsSameOrigin: {
2936 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOrigin);
2937 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
2938 if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
2940 for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
2941 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
2942 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOriginWithBadAncestorChain);
2948 case XFrameOptionsDeny:
2950 case XFrameOptionsAllowAll:
2952 case XFrameOptionsConflict:
2953 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.elidedString() + "'. Falling back to 'DENY'.", requestIdentifier);
2955 case XFrameOptionsInvalid:
2956 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.elidedString() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
2959 ASSERT_NOT_REACHED();
2964 void FrameLoader::loadProvisionalItemFromCachedPage()
2966 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
2967 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().elidedString().utf8().data());
2969 prepareForLoadStart();
2971 m_loadingFromCachedPage = true;
2973 // Should have timing data from previous time(s) the page was shown.
2974 ASSERT(provisionalLoader->timing()->navigationStart());
2975 provisionalLoader->resetTiming();
2976 provisionalLoader->timing()->markNavigationStart();
2978 provisionalLoader->setCommitted(true);
2979 commitProvisionalLoad();
2982 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
2984 if (!history()->currentItem())
2986 return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
2989 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
2991 if (!equalIgnoringCase(url.string(), "about:srcdoc"))
2993 HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
2996 if (!ownerElement->hasTagName(iframeTag))
2998 return ownerElement->fastHasAttribute(srcdocAttr);
3001 void FrameLoader::checkDidPerformFirstNavigation()
3003 Page* page = m_frame->page();
3007 if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3008 m_didPerformFirstNavigation = true;
3009 m_client->didPerformFirstNavigation();
3013 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
3015 Frame* frame = m_frame->tree()->find(name);
3017 // From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
3019 // If the source browsing context is the same as the browsing context
3020 // being navigated, and this browsing context has its seamless browsing
3021 // context flag set, and the browsing context being navigated was not
3022 // chosen using an explicit self-navigation override, then find the
3023 // nearest ancestor browsing context that does not have its seamless
3024 // browsing context flag set, and continue these steps as if that
3025 // browsing context was the one that was going to be navigated instead.
3026 if (frame == m_frame && name != "_self" && m_frame->document()->shouldDisplaySeamlesslyWithParent()) {
3027 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
3028 if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
3033 ASSERT(frame != m_frame);
3036 if (activeDocument) {
3037 if (!activeDocument->canNavigate(frame))
3040 // FIXME: Eventually all callers should supply the actual activeDocument
3041 // so we can call canNavigate with the right document.
3042 if (!m_frame->document()->canNavigate(frame))
3049 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3051 ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3053 // Save user view state to the current history item here since we don't do a normal load.
3054 // FIXME: Does form state need to be saved here too?
3055 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3056 if (FrameView* view = m_frame->view())
3057 view->setWasScrolledByUser(false);
3059 history()->setCurrentItem(item);
3061 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3062 loadInSameDocument(item->url(), item->stateObject(), false);
3064 // Restore user view state from the current history item here since we don't do a normal load.
3065 history()->restoreScrollPositionAndViewState();
3068 // FIXME: This function should really be split into a couple pieces, some of
3069 // which should be methods of HistoryController and some of which should be
3070 // methods of FrameLoader.
3071 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
3073 // Remember this item so we can traverse any child items as child frames load
3074 history()->setProvisionalItem(item);
3076 if (CachedPage* cachedPage = pageCache()->get(item)) {
3077 loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
3081 KURL itemURL = item->url();
3082 KURL itemOriginalURL = item->originalURL();
3084 if (documentLoader())
3085 currentURL = documentLoader()->url();
3086 RefPtr<FormData> formData = item->formData();
3088 ResourceRequest request(itemURL);
3090 if (!item->referrer().isNull())
3091 request.setHTTPReferrer(item->referrer());
3093 // If this was a repost that failed the page cache, we might try to repost the form.
3094 NavigationAction action;
3096 formData->generateFiles(m_frame->document());
3098 request.setHTTPMethod("POST");
3099 request.setHTTPBody(formData);
3100 request.setHTTPContentType(item->formContentType());
3101 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3102 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3104 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3105 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3106 addExtraFieldsToRequest(request, loadType, true);
3108 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3109 // We want to know this before talking to the policy delegate, since it affects whether
3110 // we show the DoYouReallyWantToRepost nag.
3112 // This trick has a small bug (3123893) where we might find a cache hit, but then
3113 // have the item vanish when we try to use it in the ensuing nav. This should be
3114 // extremely rare, but in that case the user will get an error on the navigation.
3116 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3117 request.setCachePolicy(ReturnCacheDataDontLoad);
3118 action = NavigationAction(request, loadType, false);
3120 request.setCachePolicy(ReturnCacheDataElseLoad);
3121 action = NavigationAction(request, NavigationTypeFormResubmitted);
3125 case FrameLoadTypeReload:
3126 case FrameLoadTypeReloadFromOrigin:
3127 request.setCachePolicy(ReloadIgnoringCacheData);
3129 case FrameLoadTypeBack:
3130 case FrameLoadTypeForward:
3131 case FrameLoadTypeIndexedBackForward:
3132 // If the first load within a frame is a navigation within a back/forward list that was attached
3133 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3134 if (m_stateMachine.committedFirstRealDocumentLoad())
3135 request.setCachePolicy(ReturnCacheDataElseLoad);
3137 case FrameLoadTypeStandard:
3138 case FrameLoadTypeRedirectWithLockedBackForwardList:
3140 case FrameLoadTypeSame:
3142 ASSERT_NOT_REACHED();
3145 addExtraFieldsToRequest(request, loadType, true);
3147 ResourceRequest requestForOriginalURL(request);
3148 requestForOriginalURL.setURL(itemOriginalURL);
3149 action = NavigationAction(requestForOriginalURL, loadType, false);
3152 loadWithNavigationAction(request, action, false, loadType, 0);
3155 // Loads content into this frame, as specified by history item
3156 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3158 m_requestedHistoryItem = item;
3159 HistoryItem* currentItem = history()->currentItem();
3160 bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3162 if (sameDocumentNavigation)
3163 loadSameDocumentItem(item);
3165 loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
3168 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3170 ASSERT(m_state == FrameStateProvisional);
3171 ASSERT(!m_loadingFromCachedPage);
3172 // We only use cache-only loads to avoid resubmitting forms.
3173 ASSERT(isBackForwardLoadType(m_loadType));
3174 ASSERT(m_history->provisionalItem()->formData());
3175 ASSERT(m_history->provisionalItem() == m_requestedHistoryItem.get());
3177 FrameLoadType loadType = m_loadType;
3178 HistoryItem* item = m_history->provisionalItem();
3180 stopAllLoaders(ShouldNotClearProvisionalItem);
3181 loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
3184 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3186 ResourceError error = m_client->cancelledError(request);
3187 error.setIsCancellation(true);
3191 void FrameLoader::setTitle(const StringWithDirection& title)
3193 documentLoader()->setTitle(title);
3196 String FrameLoader::referrer() const
3198 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3201 void FrameLoader::dispatchDocumentElementAvailable()
3203 m_frame->injectUserScripts(InjectAtDocumentStart);
3204 m_client->documentElementAvailable();
3207 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3209 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3212 Vector<RefPtr<DOMWrapperWorld> > worlds;
3213 ScriptController::getAllWorlds(worlds);
3214 for (size_t i = 0; i < worlds.size(); ++i)
3215 dispatchDidClearWindowObjectInWorld(worlds[i].get());
3218 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3220 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3223 m_client->dispatchDidClearWindowObjectInWorld(world);
3225 #if ENABLE(INSPECTOR)
3226 if (Page* page = m_frame->page())
3227 page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3230 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3233 void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
3235 Vector<RefPtr<DOMWrapperWorld> > worlds;
3236 ScriptController::getAllWorlds(worlds);
3237 for (size_t i = 0; i < worlds.size(); ++i)
3238 m_client->dispatchGlobalObjectAvailable(worlds[i].get());
3241 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3243 SandboxFlags flags = m_forcedSandboxFlags;
3244 if (Frame* parentFrame = m_frame->tree()->parent())
3245 flags |= parentFrame->document()->sandboxFlags();
3246 if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3247 flags |= ownerElement->sandboxFlags();
3251 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3253 m_client->didChangeTitle(loader);
3255 if (loader == m_documentLoader) {
3256 // Must update the entries in the back-forward list too.
3257 history()->setCurrentItemTitle(loader->title());
3258 // This must go through the WebFrame because it has the right notion of the current b/f item.
3259 m_client->setTitle(loader->title(), loader->urlForHistory());
3260 m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3261 m_client->dispatchDidReceiveTitle(loader->title());
3265 void FrameLoader::didChangeIcons(IconType type)
3267 m_client->dispatchDidChangeIcons(type);
3270 void FrameLoader::dispatchDidCommitLoad()
3272 if (m_stateMachine.creatingInitialEmptyDocument())
3275 m_client->dispatchDidCommitLoad();
3277 if (isLoadingMainFrame()) {
3278 m_frame->page()->resetSeenPlugins();
3279 m_frame->page()->resetSeenMediaEngines();
3282 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3284 if (m_frame->page()->mainFrame() == m_frame)
3285 m_frame->page()->featureObserver()->didCommitLoad();
3289 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3291 ASSERT(m_frame->page());
3292 ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3294 if (!m_documentLoader)
3297 Vector<ResourceRequest> pastLoads;
3298 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3300 size_t size = pastLoads.size();
3301 for (size_t i = 0; i < size; ++i) {
3302 CachedResource* resource = memoryCache()->resourceForRequest(pastLoads[i]);
3304 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3305 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3306 // Consider if there's some efficient way of remembering enough to deliver this client call.
3307 // We have the URL, but not the rest of the response or the length.
3311 ResourceRequest request(resource->url());
3312 m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3316 NetworkingContext* FrameLoader::networkingContext() const
3318 return m_networkingContext.get();
3321 void FrameLoader::loadProgressingStatusChanged()
3323 bool isLoadProgressing = m_frame->page()->progress()->isLoadProgressing();
3324 FrameView* view = m_frame->page()->mainFrame()->view();
3325 view->updateLayerFlushThrottlingInAllFrames(isLoadProgressing);
3326 view->adjustTiledBackingCoverage();
3329 void FrameLoader::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3331 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::Loader);
3332 info.addMember(m_frame, "frame");
3333 info.ignoreMember(m_client);
3334 info.addMember(m_progressTracker, "progressTracker");
3335 info.addMember(m_documentLoader, "documentLoader");
3336 info.addMember(m_provisionalDocumentLoader, "provisionalDocumentLoader");
3337 info.addMember(m_policyDocumentLoader, "policyDocumentLoader");
3338 info.addMember(m_pendingStateObject, "pendingStateObject");
3339 info.addMember(m_submittedFormURL, "submittedFormURL");
3340 info.addMember(m_checkTimer, "checkTimer");
3341 info.addMember(m_opener, "opener");
3342 info.addMember(m_openedFrames, "openedFrames");
3343 info.addMember(m_outgoingReferrer, "outgoingReferrer");
3344 info.addMember(m_networkingContext, "networkingContext");
3345 info.addMember(m_previousURL, "previousURL");
3346 info.addMember(m_requestedHistoryItem, "requestedHistoryItem");
3349 bool FrameLoaderClient::hasHTMLView() const
3354 Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3356 ASSERT(!features.dialog || request.frameName().isEmpty());
3358 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3359 if (Frame* frame = lookupFrame->loader()->findFrameForNavigation(request.frameName(), openerFrame->document())) {
3360 if (Page* page = frame->page())
3361 page->chrome()->focus();
3367 // Sandboxed frames cannot open new auxiliary browsing contexts.
3368 if (isDocumentSandboxed(openerFrame, SandboxPopups)) {
3369 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
3370 openerFrame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().elidedString() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
3374 // FIXME: Setting the referrer should be the caller's responsibility.
3375 FrameLoadRequest requestWithReferrer = request;
3376 String referrer = SecurityPolicy::generateReferrerHeader(openerFrame->document()->referrerPolicy(), request.resourceRequest().url(), openerFrame->loader()->outgoingReferrer());
3377 if (!referrer.isEmpty())
3378 requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
3379 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
3381 if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
3386 Page* oldPage = openerFrame->page();
3390 NavigationAction action(requestWithReferrer.resourceRequest());
3391 Page* page = oldPage->chrome()->createWindow(openerFrame, requestWithReferrer, features, action);
3395 Frame* frame = page->mainFrame();
3397 frame->loader()->forceSandboxFlags(openerFrame->document()->sandboxFlags());
3399 if (request.frameName() != "_blank")
3400 frame->tree()->setName(request.frameName());
3402 page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3403 page->chrome()->setStatusbarVisible(features.statusBarVisible);
3404 page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
3405 page->chrome()->setMenubarVisible(features.menuBarVisible);
3406 page->chrome()->setResizable(features.resizable);
3408 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3409 // specify the size of the viewport. We can only resize the window, so adjust
3410 // for the difference between the window size and the viewport size.
3412 FloatRect windowRect = page->chrome()->windowRect();
3413 FloatSize viewportSize = page->chrome()->pageRect().size();
3416 windowRect.setX(features.x);
3418 windowRect.setY(features.y);
3419 if (features.widthSet)
3420 windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
3421 if (features.heightSet)
3422 windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));
3424 // Ensure non-NaN values, minimum size as well as being within valid screen area.
3425 FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
3427 page->chrome()->setWindowRect(newWindowRect);
3428 page->chrome()->show();
3434 } // namespace WebCore