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 Inc. ("Apple") nor the names of
20 * its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
27 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "FrameLoader.h"
38 #include "AXObjectCache.h"
39 #include "ApplicationCacheHost.h"
40 #include "BackForwardController.h"
41 #include "BeforeUnloadEvent.h"
42 #include "CachedPage.h"
43 #include "CachedResourceLoader.h"
45 #include "ChromeClient.h"
46 #include "ContentSecurityPolicy.h"
47 #include "DOMImplementation.h"
48 #include "DOMWindow.h"
49 #include "DatabaseManager.h"
50 #include "DiagnosticLoggingClient.h"
51 #include "DiagnosticLoggingKeys.h"
53 #include "DocumentLoadTiming.h"
54 #include "DocumentLoader.h"
56 #include "EditorClient.h"
59 #include "EventHandler.h"
60 #include "EventNames.h"
61 #include "FloatRect.h"
62 #include "FormState.h"
63 #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 "GCController.h"
70 #include "HTMLAnchorElement.h"
71 #include "HTMLFormElement.h"
72 #include "HTMLInputElement.h"
73 #include "HTMLNames.h"
74 #include "HTMLObjectElement.h"
75 #include "HTMLParserIdioms.h"
76 #include "HTTPHeaderNames.h"
77 #include "HTTPParsers.h"
78 #include "HistoryController.h"
79 #include "HistoryItem.h"
80 #include "IconController.h"
81 #include "IgnoreOpensDuringUnloadCountIncrementer.h"
82 #include "InspectorController.h"
83 #include "InspectorInstrumentation.h"
84 #include "LoaderStrategy.h"
86 #include "MIMETypeRegistry.h"
87 #include "MainFrame.h"
88 #include "MemoryCache.h"
89 #include "PageCache.h"
90 #include "PageThrottler.h"
91 #include "PageTransitionEvent.h"
92 #include "PlatformStrategies.h"
93 #include "PluginData.h"
94 #include "PluginDocument.h"
95 #include "PolicyChecker.h"
96 #include "ProgressTracker.h"
97 #include "ResourceHandle.h"
98 #include "ResourceLoadInfo.h"
99 #include "ResourceRequest.h"
100 #include "SVGDocument.h"
101 #include "SVGLocatable.h"
102 #include "SVGNames.h"
103 #include "SVGPreserveAspectRatio.h"
104 #include "SVGViewElement.h"
105 #include "SVGViewSpec.h"
106 #include "SchemeRegistry.h"
107 #include "ScriptController.h"
108 #include "ScriptSourceCode.h"
109 #include "ScrollAnimator.h"
110 #include "SecurityOrigin.h"
111 #include "SecurityPolicy.h"
112 #include "SegmentedString.h"
113 #include "SerializedScriptValue.h"
114 #include "Settings.h"
115 #include "SubframeLoader.h"
116 #include "TextResourceDecoder.h"
117 #include "UserContentController.h"
118 #include "WindowFeatures.h"
119 #include "XMLDocumentParser.h"
120 #include <wtf/CurrentTime.h>
122 #include <wtf/StdLibExtras.h>
123 #include <wtf/text/CString.h>
124 #include <wtf/text/WTFString.h>
126 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
130 #if ENABLE(DATA_DETECTION)
131 #include "DataDetection.h"
135 #include "DocumentType.h"
136 #include "MemoryPressureHandler.h"
137 #include "ResourceLoader.h"
138 #include "RuntimeApplicationChecksIOS.h"
139 #include "SystemMemory.h"
140 #include "WKContentObservation.h"
145 using namespace HTMLNames;
146 using namespace SVGNames;
148 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
151 const int memoryLevelThresholdToPrunePageCache = 20;
154 bool isBackForwardLoadType(FrameLoadType type)
157 case FrameLoadType::Standard:
158 case FrameLoadType::Reload:
159 case FrameLoadType::ReloadFromOrigin:
160 case FrameLoadType::Same:
161 case FrameLoadType::RedirectWithLockedBackForwardList:
162 case FrameLoadType::Replace:
164 case FrameLoadType::Back:
165 case FrameLoadType::Forward:
166 case FrameLoadType::IndexedBackForward:
169 ASSERT_NOT_REACHED();
173 // This is not in the FrameLoader class to emphasize that it does not depend on
174 // private FrameLoader data, and to avoid increasing the number of public functions
175 // with access to private data. Since only this .cpp file needs it, making it
176 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
179 static bool isDocumentSandboxed(Frame& frame, SandboxFlags mask)
181 return frame.document() && frame.document()->isSandboxed(mask);
184 struct ForbidPromptsScope {
185 ForbidPromptsScope(Page* page) : m_page(page)
189 m_page->forbidPrompts();
192 ~ForbidPromptsScope()
196 m_page->allowPrompts();
202 class FrameLoader::FrameProgressTracker {
204 explicit FrameProgressTracker(Frame& frame)
206 , m_inProgress(false)
210 ~FrameProgressTracker()
212 if (m_inProgress && m_frame.page())
213 m_frame.page()->progress().progressCompleted(m_frame);
216 void progressStarted()
218 ASSERT(m_frame.page());
220 m_frame.page()->progress().progressStarted(m_frame);
224 void progressCompleted()
226 ASSERT(m_inProgress);
227 ASSERT(m_frame.page());
228 m_inProgress = false;
229 m_frame.page()->progress().progressCompleted(m_frame);
237 FrameLoader::FrameLoader(Frame& frame, FrameLoaderClient& client)
240 , m_policyChecker(std::make_unique<PolicyChecker>(frame))
241 , m_history(std::make_unique<HistoryController>(frame))
243 , m_subframeLoader(std::make_unique<SubframeLoader>(frame))
244 , m_icon(std::make_unique<IconController>(frame))
245 , m_mixedContentChecker(frame)
246 , m_state(FrameStateProvisional)
247 , m_loadType(FrameLoadType::Standard)
248 , m_quickRedirectComing(false)
249 , m_sentRedirectNotification(false)
250 , m_inStopAllLoaders(false)
251 , m_isExecutingJavaScriptFormAction(false)
252 , m_didCallImplicitClose(true)
253 , m_wasUnloadEventEmitted(false)
254 , m_isComplete(false)
255 , m_needsClear(false)
256 , m_checkTimer(*this, &FrameLoader::checkTimerFired)
257 , m_shouldCallCheckCompleted(false)
258 , m_shouldCallCheckLoadComplete(false)
260 , m_loadingFromCachedPage(false)
261 , m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
262 , m_loadsSynchronously(false)
263 , m_forcedSandboxFlags(SandboxNone)
267 FrameLoader::~FrameLoader()
271 for (auto& frame : m_openedFrames)
272 frame->loader().m_opener = nullptr;
274 m_client.frameLoaderDestroyed();
276 if (m_networkingContext)
277 m_networkingContext->invalidate();
280 void FrameLoader::init()
282 // This somewhat odd set of steps gives the frame an initial empty document.
283 setPolicyDocumentLoader(m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData()).ptr());
284 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
285 m_provisionalDocumentLoader->startLoadingMainResource();
287 Ref<Frame> protect(m_frame);
288 m_frame.document()->cancelParsing();
289 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
291 m_networkingContext = m_client.createNetworkingContext();
292 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
296 void FrameLoader::initForSynthesizedDocument(const URL&)
298 // FIXME: We need to initialize the document URL to the specified URL. Currently the URL is empty and hence
299 // FrameLoader::checkCompleted() will overwrite the URL of the document to be activeDocumentLoader()->documentURL().
301 RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData());
302 loader->attachToFrame(m_frame);
303 loader->setResponse(ResourceResponse(URL(), ASCIILiteral("text/html"), 0, String()));
304 loader->setCommitted(true);
305 setDocumentLoader(loader.get());
307 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
308 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
309 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
310 m_client.transitionToCommittedForNewPage();
312 m_didCallImplicitClose = true;
314 m_state = FrameStateComplete;
317 m_networkingContext = m_client.createNetworkingContext();
318 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
322 void FrameLoader::setDefersLoading(bool defers)
324 if (m_documentLoader)
325 m_documentLoader->setDefersLoading(defers);
326 if (m_provisionalDocumentLoader)
327 m_provisionalDocumentLoader->setDefersLoading(defers);
328 if (m_policyDocumentLoader)
329 m_policyDocumentLoader->setDefersLoading(defers);
330 history().setDefersLoading(defers);
333 m_frame.navigationScheduler().startTimer();
334 startCheckCompleteTimer();
338 void FrameLoader::changeLocation(const FrameLoadRequest& request)
340 urlSelected(request, nullptr);
343 void FrameLoader::urlSelected(const URL& url, const String& passedTarget, Event* triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy)
345 NewFrameOpenerPolicy newFrameOpenerPolicy = shouldSendReferrer == NeverSendReferrer ? NewFrameOpenerPolicy::Suppress : NewFrameOpenerPolicy::Allow;
347 urlSelected(FrameLoadRequest(m_frame.document()->securityOrigin(), ResourceRequest(url), passedTarget, lockHistory, lockBackForwardList, shouldSendReferrer, AllowNavigationToInvalidURL::Yes, newFrameOpenerPolicy, DoNotReplaceDocumentIfJavaScriptURL, shouldOpenExternalURLsPolicy), triggeringEvent);
350 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, Event* triggeringEvent)
352 Ref<Frame> protect(m_frame);
353 FrameLoadRequest frameRequest(passedRequest);
355 if (m_frame.script().executeIfJavaScriptURL(frameRequest.resourceRequest().url(), frameRequest.shouldReplaceDocumentIfJavaScriptURL()))
358 if (frameRequest.frameName().isEmpty())
359 frameRequest.setFrameName(m_frame.document()->baseTarget());
361 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
363 loadFrameRequest(frameRequest, triggeringEvent, nullptr);
366 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
368 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
370 // FIXME: Find a good spot for these.
371 ASSERT(submission->data());
372 ASSERT(submission->state());
373 ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == &m_frame);
378 if (submission->action().isEmpty())
381 if (isDocumentSandboxed(m_frame, SandboxForms)) {
382 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
383 m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked form submission to '" + submission->action().stringCenterEllipsizedToLength() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
387 if (protocolIsJavaScript(submission->action())) {
388 if (!m_frame.document()->contentSecurityPolicy()->allowFormAction(URL(submission->action())))
390 m_isExecutingJavaScriptFormAction = true;
391 Ref<Frame> protect(m_frame);
392 m_frame.script().executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
393 m_isExecutingJavaScriptFormAction = false;
397 Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
399 if (!DOMWindow::allowPopUp(&m_frame) && !ScriptController::processingUserGesture())
402 // FIXME: targetFrame can be 0 for two distinct reasons:
403 // 1. The frame was not found by name, so we should try opening a new window.
404 // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
405 // Continuing form submission makes no sense in the latter case.
406 // There is a repeat check after timer fires, so this is not a correctness issue.
408 targetFrame = &m_frame;
410 submission->clearTarget();
412 if (!targetFrame->page())
415 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
417 // We do not want to submit more than one form from the same page, nor do we want to submit a single
418 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
419 // The flag is reset in each time we start dispatching a new mouse or key down event, and
420 // also in setView since this part may get reused for a page from the back/forward cache.
421 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
423 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
424 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
425 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
427 if (m_frame.tree().isDescendantOf(targetFrame)) {
428 if (m_submittedFormURL == submission->requestURL())
430 m_submittedFormURL = submission->requestURL();
433 submission->data()->generateFiles(m_frame.document());
434 submission->setReferrer(outgoingReferrer());
435 submission->setOrigin(outgoingOrigin());
437 targetFrame->navigationScheduler().scheduleFormSubmission(submission);
440 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
442 if (m_frame.document() && m_frame.document()->parser())
443 m_frame.document()->parser()->stopParsing();
445 if (unloadEventPolicy != UnloadEventPolicyNone)
446 dispatchUnloadEvents(unloadEventPolicy);
448 m_isComplete = true; // to avoid calling completed() in finishedParsing()
449 m_didCallImplicitClose = true; // don't want that one either
451 if (m_frame.document() && m_frame.document()->parsing()) {
453 m_frame.document()->setParsing(false);
456 if (Document* doc = m_frame.document()) {
457 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
458 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
459 doc->setReadyState(Document::Complete);
461 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
462 DatabaseManager::singleton().stopDatabases(doc, 0);
465 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
466 m_frame.navigationScheduler().cancel();
469 void FrameLoader::stop()
471 // http://bugs.webkit.org/show_bug.cgi?id=10854
472 // The frame's last ref may be removed and it will be deleted by checkCompleted().
473 Ref<Frame> protect(m_frame);
475 if (DocumentParser* parser = m_frame.document()->parser()) {
476 parser->stopParsing();
483 void FrameLoader::willTransitionToCommitted()
485 // This function is called when a frame is still fully in place (not cached, not detached), but will be replaced.
487 if (m_frame.editor().hasComposition()) {
488 // The text was already present in DOM, so it's better to confirm than to cancel the composition.
489 m_frame.editor().confirmComposition();
490 if (EditorClient* editorClient = m_frame.editor().client()) {
491 editorClient->respondToChangedSelection(&m_frame);
492 editorClient->discardedComposition(&m_frame);
497 bool FrameLoader::closeURL()
499 history().saveDocumentState();
501 Document* currentDocument = m_frame.document();
502 UnloadEventPolicy unloadEventPolicy;
503 if (m_frame.page() && m_frame.page()->chrome().client().isSVGImageChromeClient()) {
504 // If this is the SVGDocument of an SVGImage, no need to dispatch events or recalcStyle.
505 unloadEventPolicy = UnloadEventPolicyNone;
507 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
508 unloadEventPolicy = currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly;
511 stopLoading(unloadEventPolicy);
513 m_frame.editor().clearUndoRedoOperations();
517 bool FrameLoader::didOpenURL()
519 if (m_frame.navigationScheduler().redirectScheduledDuringLoad()) {
520 // A redirect was scheduled before the document was created.
521 // This can happen when one frame changes another frame's location.
525 m_frame.navigationScheduler().cancel();
526 m_frame.editor().clearLastEditCommand();
528 m_isComplete = false;
529 m_didCallImplicitClose = false;
531 // If we are still in the process of initializing an empty document then
532 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
533 // since it may cause clients to attempt to render the frame.
534 if (!m_stateMachine.creatingInitialEmptyDocument()) {
535 DOMWindow* window = m_frame.document()->domWindow();
536 window->setStatus(String());
537 window->setDefaultStatus(String());
545 void FrameLoader::didExplicitOpen()
547 m_isComplete = false;
548 m_didCallImplicitClose = false;
550 // Calling document.open counts as committing the first real document load.
551 if (!m_stateMachine.committedFirstRealDocumentLoad())
552 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
554 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
555 // from a subsequent window.document.open / window.document.write call.
556 // Canceling redirection here works for all cases because document.open
557 // implicitly precedes document.write.
558 m_frame.navigationScheduler().cancel();
562 void FrameLoader::cancelAndClear()
564 m_frame.navigationScheduler().cancel();
569 clear(m_frame.document(), false);
570 m_frame.script().updatePlatformScriptObjects();
573 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
575 m_frame.editor().clear();
579 m_needsClear = false;
581 if (!m_frame.document()->inPageCache()) {
582 m_frame.document()->cancelParsing();
583 m_frame.document()->stopActiveDOMObjects();
584 bool hadLivingRenderTree = m_frame.document()->hasLivingRenderTree();
585 m_frame.document()->prepareForDestruction();
586 if (hadLivingRenderTree)
587 m_frame.document()->removeFocusedNodeOfSubtree(m_frame.document());
590 // Do this after detaching the document so that the unload event works.
591 if (clearWindowProperties) {
592 InspectorInstrumentation::frameWindowDiscarded(&m_frame, m_frame.document()->domWindow());
593 m_frame.document()->domWindow()->resetUnlessSuspendedForDocumentSuspension();
594 m_frame.script().clearWindowShell(newDocument->domWindow(), m_frame.document()->inPageCache());
597 m_frame.selection().prepareForDestruction();
598 m_frame.eventHandler().clear();
599 if (clearFrameView && m_frame.view())
600 m_frame.view()->clear();
602 // Do not drop the document before the ScriptController and view are cleared
603 // as some destructors might still try to access the document.
604 m_frame.setDocument(nullptr);
606 subframeLoader().clear();
608 if (clearScriptObjects)
609 m_frame.script().clearScriptObjects();
611 m_frame.script().enableEval();
613 m_frame.navigationScheduler().clear();
616 m_shouldCallCheckCompleted = false;
617 m_shouldCallCheckLoadComplete = false;
619 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
620 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
623 void FrameLoader::receivedFirstData()
625 dispatchDidCommitLoad();
626 dispatchDidClearWindowObjectsInAllWorlds();
627 dispatchGlobalObjectAvailableInAllWorlds();
629 if (m_documentLoader) {
630 StringWithDirection ptitle = m_documentLoader->title();
631 // If we have a title let the WebView know about it.
632 if (!ptitle.isNull())
633 m_client.dispatchDidReceiveTitle(ptitle);
636 if (!m_documentLoader)
641 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField(HTTPHeaderName::Refresh), false, delay, urlString))
644 if (urlString.isEmpty())
645 completedURL = m_frame.document()->url();
647 completedURL = m_frame.document()->completeURL(urlString);
649 if (!protocolIsJavaScript(completedURL))
650 m_frame.navigationScheduler().scheduleRedirect(m_frame.document(), delay, completedURL);
652 String message = "Refused to refresh " + m_frame.document()->url().stringCenterEllipsizedToLength() + " to a javascript: URL";
653 m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
657 void FrameLoader::setOutgoingReferrer(const URL& url)
659 m_outgoingReferrer = url.strippedForUseAsReferrer();
662 void FrameLoader::didBeginDocument(bool dispatch)
665 m_isComplete = false;
666 m_didCallImplicitClose = false;
667 m_frame.document()->setReadyState(Document::Loading);
669 if (m_pendingStateObject) {
670 m_frame.document()->statePopped(m_pendingStateObject.get());
671 m_pendingStateObject = nullptr;
675 dispatchDidClearWindowObjectsInAllWorlds();
677 updateFirstPartyForCookies();
678 m_frame.document()->initContentSecurityPolicy();
680 const Settings& settings = m_frame.settings();
681 m_frame.document()->cachedResourceLoader().setImagesEnabled(settings.areImagesEnabled());
682 m_frame.document()->cachedResourceLoader().setAutoLoadImages(settings.loadsImagesAutomatically());
684 if (m_documentLoader) {
685 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XDNSPrefetchControl);
686 if (!dnsPrefetchControl.isEmpty())
687 m_frame.document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
689 m_frame.document()->contentSecurityPolicy()->didReceiveHeaders(ContentSecurityPolicyResponseHeaders(m_documentLoader->response()));
691 String headerContentLanguage = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentLanguage);
692 if (!headerContentLanguage.isEmpty()) {
693 size_t commaIndex = headerContentLanguage.find(',');
694 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
695 headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
696 if (!headerContentLanguage.isEmpty())
697 m_frame.document()->setContentLanguage(headerContentLanguage);
701 history().restoreDocumentState();
704 void FrameLoader::finishedParsing()
706 m_frame.injectUserScripts(InjectAtDocumentEnd);
708 if (m_stateMachine.creatingInitialEmptyDocument())
711 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
712 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
713 // Null-checking the FrameView indicates whether or not we're in the destructor.
714 RefPtr<Frame> protector = m_frame.view() ? &m_frame : 0;
716 m_client.dispatchDidFinishDocumentLoad();
718 scrollToFragmentWithParentBoundary(m_frame.document()->url());
723 return; // We are being destroyed by something checkCompleted called.
725 // Check if the scrollbars are really needed for the content.
726 // If not, remove them, relayout, and repaint.
727 m_frame.view()->restoreScrollbar();
730 void FrameLoader::loadDone()
735 bool FrameLoader::allChildrenAreComplete() const
737 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
738 if (!child->loader().m_isComplete)
744 bool FrameLoader::allAncestorsAreComplete() const
746 for (Frame* ancestor = &m_frame; ancestor; ancestor = ancestor->tree().parent()) {
747 if (!ancestor->loader().m_isComplete)
753 void FrameLoader::checkCompleted()
755 m_shouldCallCheckCompleted = false;
757 // Have we completed before?
761 // Are we still parsing?
762 if (m_frame.document()->parsing())
765 // Still waiting for images/scripts?
766 if (m_frame.document()->cachedResourceLoader().requestCount())
769 // Still waiting for elements that don't go through a FrameLoader?
770 if (m_frame.document()->isDelayingLoadEvent())
773 // Any frame that hasn't completed yet?
774 if (!allChildrenAreComplete())
777 // Important not to protect earlier in this function, because earlier parts
778 // of this function can be called in the frame's destructor, and it's not legal
779 // to ref an object while it's being destroyed.
780 Ref<Frame> protect(m_frame);
784 m_requestedHistoryItem = nullptr;
785 m_frame.document()->setReadyState(Document::Complete);
788 if (m_frame.document()->url().isEmpty()) {
789 // We need to update the document URL of a PDF document to be non-empty so that both back/forward history navigation
790 // between PDF pages and fragment navigation works. See <rdar://problem/9544769> for more details.
791 // FIXME: Is there a better place for this code, say DocumentLoader? Also, we should explicitly only update the URL
792 // of the document when it's a PDFDocument object instead of assuming that a Document object with an empty URL is a PDFDocument.
793 // FIXME: This code is incorrect for a synthesized document (which also has an empty URL). The URL for a synthesized
794 // document should be the URL specified to FrameLoader::initForSynthesizedDocument().
795 m_frame.document()->setURL(activeDocumentLoader()->documentURL());
799 checkCallImplicitClose(); // if we didn't do it before
801 m_frame.navigationScheduler().startTimer();
808 void FrameLoader::checkTimerFired()
810 Ref<Frame> protect(m_frame);
812 if (Page* page = m_frame.page()) {
813 if (page->defersLoading())
816 if (m_shouldCallCheckCompleted)
818 if (m_shouldCallCheckLoadComplete)
822 void FrameLoader::startCheckCompleteTimer()
824 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
826 if (m_checkTimer.isActive())
828 m_checkTimer.startOneShot(0);
831 void FrameLoader::scheduleCheckCompleted()
833 m_shouldCallCheckCompleted = true;
834 startCheckCompleteTimer();
837 void FrameLoader::scheduleCheckLoadComplete()
839 m_shouldCallCheckLoadComplete = true;
840 startCheckCompleteTimer();
843 void FrameLoader::checkCallImplicitClose()
845 if (m_didCallImplicitClose || m_frame.document()->parsing() || m_frame.document()->isDelayingLoadEvent())
848 if (!allChildrenAreComplete())
849 return; // still got a frame running -> too early
851 m_didCallImplicitClose = true;
852 m_wasUnloadEventEmitted = false;
853 m_frame.document()->implicitClose();
856 void FrameLoader::loadURLIntoChildFrame(const URL& url, const String& referer, Frame* childFrame)
860 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
861 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree().uniqueName(), url);
862 if (subframeArchive) {
863 childFrame->loader().loadArchive(subframeArchive.release());
866 #endif // ENABLE(WEB_ARCHIVE)
868 HistoryItem* parentItem = history().currentItem();
869 // If we're moving in the back/forward list, we might want to replace the content
870 // of this child frame with whatever was there at that point.
871 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
872 && !m_frame.document()->loadEventFinished()) {
873 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree().uniqueName());
875 childFrame->loader().m_requestedHistoryItem = childItem;
876 childFrame->loader().loadDifferentDocumentItem(*childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
881 FrameLoadRequest frameLoadRequest(m_frame.document()->securityOrigin(), ResourceRequest(url), "_self", LockHistory::No, LockBackForwardList::Yes, ShouldSendReferrer::MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress, ReplaceDocumentIfJavaScriptURL, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
882 childFrame->loader().loadURL(frameLoadRequest, referer, FrameLoadType::RedirectWithLockedBackForwardList, 0, 0);
885 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
886 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
888 ArchiveResource* mainResource = archive->mainResource();
889 ASSERT(mainResource);
893 ResourceResponse response(URL(), mainResource->mimeType(), mainResource->data()->size(), mainResource->textEncoding());
894 SubstituteData substituteData(mainResource->data(), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
896 ResourceRequest request(mainResource->url());
898 request.applyWebArchiveHackForMail();
901 RefPtr<DocumentLoader> documentLoader = m_client.createDocumentLoader(request, substituteData);
902 documentLoader->setArchive(archive.get());
903 load(documentLoader.get());
905 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
907 String FrameLoader::outgoingReferrer() const
909 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
910 // for why we walk the parent chain for srcdoc documents.
911 Frame* frame = &m_frame;
912 while (frame->document()->isSrcdocDocument()) {
913 frame = frame->tree().parent();
914 // Srcdoc documents cannot be top-level documents, by definition,
915 // because they need to be contained in iframes with the srcdoc.
918 return frame->loader().m_outgoingReferrer;
921 String FrameLoader::outgoingOrigin() const
923 return m_frame.document()->securityOrigin()->toString();
926 bool FrameLoader::checkIfFormActionAllowedByCSP(const URL& url) const
928 if (m_submittedFormURL.isEmpty())
931 return m_frame.document()->contentSecurityPolicy()->allowFormAction(url);
934 Frame* FrameLoader::opener()
939 void FrameLoader::setOpener(Frame* opener)
941 if (m_opener && !opener)
942 m_client.didDisownOpener();
945 m_opener->loader().m_openedFrames.remove(&m_frame);
947 opener->loader().m_openedFrames.add(&m_frame);
950 if (m_frame.document())
951 m_frame.document()->initSecurityContext();
954 // FIXME: This does not belong in FrameLoader!
955 void FrameLoader::handleFallbackContent()
957 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
958 if (!is<HTMLObjectElement>(owner))
960 downcast<HTMLObjectElement>(*owner).renderFallbackContent();
963 void FrameLoader::provisionalLoadStarted()
965 if (m_stateMachine.firstLayoutDone())
966 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
967 m_frame.navigationScheduler().cancel(true);
968 m_client.provisionalLoadStarted();
971 void FrameLoader::resetMultipleFormSubmissionProtection()
973 m_submittedFormURL = URL();
976 void FrameLoader::updateFirstPartyForCookies()
978 if (m_frame.tree().parent())
979 setFirstPartyForCookies(m_frame.tree().parent()->document()->firstPartyForCookies());
981 setFirstPartyForCookies(m_frame.document()->url());
984 void FrameLoader::setFirstPartyForCookies(const URL& url)
986 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
987 frame->document()->setFirstPartyForCookies(url);
990 // This does the same kind of work that didOpenURL does, except it relies on the fact
991 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
992 void FrameLoader::loadInSameDocument(const URL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
994 // If we have a state object, we cannot also be a new navigation.
995 ASSERT(!stateObject || (stateObject && !isNewNavigation));
997 // Update the data source's request with the new URL to fake the URL change
998 URL oldURL = m_frame.document()->url();
999 m_frame.document()->setURL(url);
1000 setOutgoingReferrer(url);
1001 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1002 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1003 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1004 // based on the current request. Must also happen before we openURL and displace the
1005 // scroll position, since adding the BF item will save away scroll state.
1007 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1008 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1009 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1010 // though its load is not yet done. I think this all works out OK, for one because
1011 // we have already saved away the scroll and doc state for the long slow load,
1012 // but it's not an obvious case.
1014 history().updateBackForwardListForFragmentScroll();
1017 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1019 history().updateForSameDocumentNavigation();
1021 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1023 m_frame.eventHandler().stopAutoscrollTimer();
1025 // It's important to model this as a load that starts and immediately finishes.
1026 // Otherwise, the parent frame may think we never finished loading.
1029 // We need to scroll to the fragment whether or not a hash change occurred, since
1030 // the user might have scrolled since the previous navigation.
1031 scrollToFragmentWithParentBoundary(url);
1033 m_isComplete = false;
1036 if (isNewNavigation) {
1037 // This will clear previousItem from the rest of the frame tree that didn't
1038 // doing any loading. We need to make a pass on this now, since for fragment
1039 // navigation we'll not go through a real load and reach Completed state.
1040 checkLoadComplete();
1043 m_client.dispatchDidNavigateWithinPage();
1045 m_frame.document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1046 m_client.dispatchDidPopStateWithinPage();
1049 m_frame.document()->enqueueHashchangeEvent(oldURL, url);
1050 m_client.dispatchDidChangeLocationWithinPage();
1053 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1054 m_client.didFinishLoad();
1057 bool FrameLoader::isComplete() const
1059 return m_isComplete;
1062 void FrameLoader::completed()
1064 Ref<Frame> protect(m_frame);
1066 for (Frame* descendant = m_frame.tree().traverseNext(&m_frame); descendant; descendant = descendant->tree().traverseNext(&m_frame))
1067 descendant->navigationScheduler().startTimer();
1069 if (Frame* parent = m_frame.tree().parent())
1070 parent->loader().checkCompleted();
1073 m_frame.view()->maintainScrollPositionAtAnchor(nullptr);
1074 m_activityAssertion = nullptr;
1077 void FrameLoader::started()
1080 m_activityAssertion = m_frame.page()->pageThrottler().pageLoadActivityToken();
1081 for (Frame* frame = &m_frame; frame; frame = frame->tree().parent())
1082 frame->loader().m_isComplete = false;
1085 void FrameLoader::prepareForLoadStart()
1087 m_progressTracker->progressStarted();
1088 m_client.dispatchDidStartProvisionalLoad();
1090 if (AXObjectCache::accessibilityEnabled()) {
1091 if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache()) {
1092 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadType::Reload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1093 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
1098 void FrameLoader::setupForReplace()
1100 m_client.revertToProvisionalState(m_documentLoader.get());
1101 setState(FrameStateProvisional);
1102 m_provisionalDocumentLoader = m_documentLoader;
1103 m_documentLoader = nullptr;
1107 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, Event* event, PassRefPtr<FormState> formState)
1109 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1110 Ref<Frame> protect(m_frame);
1112 URL url = request.resourceRequest().url();
1114 ASSERT(m_frame.document());
1115 if (!request.requester()->canDisplay(url)) {
1116 reportLocalLoadFailed(&m_frame, url.stringCenterEllipsizedToLength());
1120 String argsReferrer = request.resourceRequest().httpReferrer();
1121 if (argsReferrer.isEmpty())
1122 argsReferrer = outgoingReferrer();
1124 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), url, argsReferrer);
1125 if (request.shouldSendReferrer() == NeverSendReferrer)
1126 referrer = String();
1128 FrameLoadType loadType;
1129 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1130 loadType = FrameLoadType::Reload;
1131 else if (request.lockBackForwardList() == LockBackForwardList::Yes)
1132 loadType = FrameLoadType::RedirectWithLockedBackForwardList;
1134 loadType = FrameLoadType::Standard;
1136 if (request.resourceRequest().httpMethod() == "POST")
1137 loadPostRequest(request, referrer, loadType, event, formState.get());
1139 loadURL(request, referrer, loadType, event, formState.get());
1141 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1142 // load if frame names have changed.
1143 Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : &m_frame;
1145 sourceFrame = &m_frame;
1146 Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(request.frameName());
1147 if (targetFrame && targetFrame != sourceFrame) {
1148 if (Page* page = targetFrame->page())
1149 page->chrome().focus();
1153 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& sourceFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1155 if (!sourceFrame.isMainFrame())
1156 return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
1157 if (ScriptController::processingUserGesture())
1158 return ShouldOpenExternalURLsPolicy::ShouldAllow;
1159 return propagatedPolicy;
1162 void FrameLoader::loadURL(const FrameLoadRequest& frameLoadRequest, const String& referrer, FrameLoadType newLoadType, Event* event, PassRefPtr<FormState> prpFormState)
1164 if (m_inStopAllLoaders)
1167 Ref<Frame> protect(m_frame);
1169 String frameName = frameLoadRequest.frameName();
1170 AllowNavigationToInvalidURL allowNavigationToInvalidURL = frameLoadRequest.allowNavigationToInvalidURL();
1171 NewFrameOpenerPolicy openerPolicy = frameLoadRequest.newFrameOpenerPolicy();
1172 LockHistory lockHistory = frameLoadRequest.lockHistory();
1173 RefPtr<FormState> formState = prpFormState;
1174 bool isFormSubmission = formState;
1176 const URL& newURL = frameLoadRequest.resourceRequest().url();
1177 ResourceRequest request(newURL);
1178 if (!referrer.isEmpty()) {
1179 request.setHTTPReferrer(referrer);
1180 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1181 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1183 #if ENABLE(CACHE_PARTITIONING)
1184 if (&m_frame.tree().top() != &m_frame)
1185 request.setDomainForCachePartition(m_frame.tree().top().document()->securityOrigin()->domainForCachePartition());
1187 addExtraFieldsToRequest(request, newLoadType, true);
1188 if (newLoadType == FrameLoadType::Reload || newLoadType == FrameLoadType::ReloadFromOrigin)
1189 request.setCachePolicy(ReloadIgnoringCacheData);
1191 ASSERT(newLoadType != FrameLoadType::Same);
1193 // The search for a target frame is done earlier in the case of form submission.
1194 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1195 if (targetFrame && targetFrame != &m_frame) {
1196 FrameLoadRequest newFrameLoadRequest(frameLoadRequest);
1197 newFrameLoadRequest.setFrameName("_self");
1198 targetFrame->loader().loadURL(newFrameLoadRequest, referrer, newLoadType, event, formState.release());
1202 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1205 NavigationAction action(request, newLoadType, isFormSubmission, event, frameLoadRequest.shouldOpenExternalURLsPolicy());
1207 if (!targetFrame && !frameName.isEmpty()) {
1208 action = action.copyWithShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(m_frame, frameLoadRequest.shouldOpenExternalURLsPolicy()));
1209 policyChecker().checkNewWindowPolicy(action, request, formState.release(), frameName, [this, allowNavigationToInvalidURL, openerPolicy](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
1210 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
1215 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1217 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1218 const String& httpMethod = request.httpMethod();
1220 // Make sure to do scroll to fragment processing even if the URL is
1221 // exactly the same so pages with '#' links and DHTML side effects
1223 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1224 oldDocumentLoader->setTriggeringAction(action);
1225 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1226 policyChecker().stopCheck();
1227 policyChecker().setLoadType(newLoadType);
1228 policyChecker().checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(), [this](const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue) {
1229 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
1234 // must grab this now, since this load may stop the previous load and clear this flag
1235 bool isRedirect = m_quickRedirectComing;
1236 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release(), allowNavigationToInvalidURL);
1238 m_quickRedirectComing = false;
1239 if (m_provisionalDocumentLoader)
1240 m_provisionalDocumentLoader->setIsClientRedirect(true);
1241 } else if (sameURL && newLoadType != FrameLoadType::Reload && newLoadType != FrameLoadType::ReloadFromOrigin) {
1242 // Example of this case are sites that reload the same URL with a different cookie
1243 // driving the generated content, or a master frame with links that drive a target
1244 // frame, where the user has clicked on the same link repeatedly.
1245 m_loadType = FrameLoadType::Same;
1249 SubstituteData FrameLoader::defaultSubstituteDataForURL(const URL& url)
1251 if (!shouldTreatURLAsSrcdocDocument(url))
1252 return SubstituteData();
1253 String srcdoc = m_frame.ownerElement()->fastGetAttribute(srcdocAttr);
1254 ASSERT(!srcdoc.isNull());
1255 CString encodedSrcdoc = srcdoc.utf8();
1257 ResourceResponse response(URL(), ASCIILiteral("text/html"), encodedSrcdoc.length(), ASCIILiteral("UTF-8"));
1258 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1261 void FrameLoader::load(const FrameLoadRequest& passedRequest)
1263 FrameLoadRequest request(passedRequest);
1265 if (m_inStopAllLoaders)
1268 if (!request.frameName().isEmpty()) {
1269 Frame* frame = findFrameForNavigation(request.frameName());
1271 request.setShouldCheckNewWindowPolicy(false);
1272 if (&frame->loader() != this) {
1273 frame->loader().load(request);
1279 if (request.shouldCheckNewWindowPolicy()) {
1280 NavigationAction action(request.resourceRequest(), NavigationType::Other, passedRequest.shouldOpenExternalURLsPolicy());
1281 policyChecker().checkNewWindowPolicy(action, request.resourceRequest(), nullptr, request.frameName(), [this](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
1282 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress);
1288 if (!request.hasSubstituteData())
1289 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1291 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request.resourceRequest(), request.substituteData());
1292 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, request.shouldOpenExternalURLsPolicy());
1297 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, LockHistory lockHistory, FrameLoadType type, PassRefPtr<FormState> formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
1299 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1300 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, action.shouldOpenExternalURLsPolicy());
1302 if (lockHistory == LockHistory::Yes && m_documentLoader)
1303 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1305 loader->setTriggeringAction(action);
1306 if (m_documentLoader)
1307 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1309 loadWithDocumentLoader(loader.ptr(), type, formState, allowNavigationToInvalidURL);
1312 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1314 ResourceRequest& r = newDocumentLoader->request();
1315 addExtraFieldsToMainResourceRequest(r);
1318 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1319 r.setCachePolicy(ReloadIgnoringCacheData);
1320 type = FrameLoadType::Same;
1321 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadType::Reload)
1322 type = FrameLoadType::Reload;
1324 type = FrameLoadType::Standard;
1326 if (m_documentLoader)
1327 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1329 // When we loading alternate content for an unreachable URL that we're
1330 // visiting in the history list, we treat it as a reload so the history list
1331 // is appropriately maintained.
1333 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadType::Reload" ...
1334 // shouldn't a more explicit type of reload be defined, that means roughly
1335 // "load without affecting history" ?
1336 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1337 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1338 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1339 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1340 history().saveDocumentAndScrollState();
1342 ASSERT(type == FrameLoadType::Standard);
1343 type = FrameLoadType::Reload;
1346 loadWithDocumentLoader(newDocumentLoader, type, 0, AllowNavigationToInvalidURL::Yes);
1349 static void logNavigation(MainFrame& frame, FrameLoadType type)
1351 String navigationDescription;
1353 case FrameLoadType::Standard:
1354 navigationDescription = ASCIILiteral("standard");
1356 case FrameLoadType::Back:
1357 navigationDescription = ASCIILiteral("back");
1359 case FrameLoadType::Forward:
1360 navigationDescription = ASCIILiteral("forward");
1362 case FrameLoadType::IndexedBackForward:
1363 navigationDescription = ASCIILiteral("indexedBackForward");
1365 case FrameLoadType::Reload:
1366 navigationDescription = ASCIILiteral("reload");
1368 case FrameLoadType::Same:
1369 navigationDescription = ASCIILiteral("same");
1371 case FrameLoadType::ReloadFromOrigin:
1372 navigationDescription = ASCIILiteral("reloadFromOrigin");
1374 case FrameLoadType::Replace:
1375 case FrameLoadType::RedirectWithLockedBackForwardList:
1376 // Not logging those for now.
1379 frame.diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::navigationKey(), navigationDescription, ShouldSample::No);
1382 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
1384 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1385 Ref<Frame> protect(m_frame);
1387 ASSERT(m_client.hasWebView());
1389 // Unfortunately the view must be non-nil, this is ultimately due
1390 // to parser requiring a FrameView. We should fix this dependency.
1392 ASSERT(m_frame.view());
1394 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1397 if (m_frame.document())
1398 m_previousURL = m_frame.document()->url();
1400 // Log main frame navigation types.
1401 if (m_frame.isMainFrame())
1402 logNavigation(static_cast<MainFrame&>(m_frame), type);
1404 policyChecker().setLoadType(type);
1405 RefPtr<FormState> formState = prpFormState;
1406 bool isFormSubmission = formState;
1408 const URL& newURL = loader->request().url();
1409 const String& httpMethod = loader->request().httpMethod();
1411 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker().loadType(), newURL)) {
1412 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1413 NavigationAction action(loader->request(), policyChecker().loadType(), isFormSubmission);
1415 oldDocumentLoader->setTriggeringAction(action);
1416 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1417 policyChecker().stopCheck();
1418 policyChecker().checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState, [this](const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue) {
1419 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
1424 if (Frame* parent = m_frame.tree().parent())
1425 loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
1427 policyChecker().stopCheck();
1428 setPolicyDocumentLoader(loader);
1429 if (loader->triggeringAction().isEmpty())
1430 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker().loadType(), isFormSubmission));
1432 if (Element* ownerElement = m_frame.ownerElement()) {
1433 // We skip dispatching the beforeload event if we've already
1434 // committed a real document load because the event would leak
1435 // subsequent activity by the frame which the parent frame isn't
1436 // supposed to learn. For example, if the child frame navigated to
1437 // a new URL, the parent frame shouldn't learn the URL.
1438 if (!m_stateMachine.committedFirstRealDocumentLoad()
1439 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1440 continueLoadAfterNavigationPolicy(loader->request(), formState, false, allowNavigationToInvalidURL);
1445 policyChecker().checkNavigationPolicy(loader->request(), loader, formState, [this, allowNavigationToInvalidURL](const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue) {
1446 continueLoadAfterNavigationPolicy(request, formState, shouldContinue, allowNavigationToInvalidURL);
1450 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1452 ASSERT(!url.isEmpty());
1456 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to load local resource: " + url);
1459 void FrameLoader::reportBlockedPortFailed(Frame* frame, const String& url)
1461 ASSERT(!url.isEmpty());
1465 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to use restricted network port: " + url);
1468 const ResourceRequest& FrameLoader::initialRequest() const
1470 return activeDocumentLoader()->originalRequest();
1473 bool FrameLoader::willLoadMediaElementURL(URL& url)
1476 // MobileStore depends on the iOS 4.0 era client delegate method because webView:resource:willSendRequest:redirectResponse:fromDataSource
1477 // doesn't let them tell when a load request is coming from a media element. See <rdar://problem/8266916> for more details.
1478 if (applicationIsMobileStore())
1479 return m_client.shouldLoadMediaElementURL(url);
1482 ResourceRequest request(url);
1484 unsigned long identifier;
1485 ResourceError error;
1486 requestFromDelegate(request, identifier, error);
1487 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String()), 0, -1, -1, error);
1489 url = request.url();
1491 return error.isNull();
1494 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1496 URL unreachableURL = docLoader->unreachableURL();
1498 if (unreachableURL.isEmpty())
1501 if (!isBackForwardLoadType(policyChecker().loadType()))
1504 // We only treat unreachableURLs specially during the delegate callbacks
1505 // for provisional load errors and navigation policy decisions. The former
1506 // case handles well-formed URLs that can't be loaded, and the latter
1507 // case handles malformed URLs and unknown schemes. Loading alternate content
1508 // at other times behaves like a standard load.
1509 if (policyChecker().delegateIsDecidingNavigationPolicy() || policyChecker().delegateIsHandlingUnimplementablePolicy())
1510 return m_policyDocumentLoader && unreachableURL == m_policyDocumentLoader->request().url();
1512 return unreachableURL == m_provisionalLoadErrorBeingHandledURL;
1515 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1517 if (!m_documentLoader)
1520 ResourceRequest request = m_documentLoader->request();
1521 URL unreachableURL = m_documentLoader->unreachableURL();
1522 if (!unreachableURL.isEmpty())
1523 request.setURL(unreachableURL);
1525 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1526 // We should ask the user for confirmation in this case.
1527 request.setCachePolicy(ReturnCacheDataElseLoad);
1529 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1530 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1532 setPolicyDocumentLoader(loader.ptr());
1534 loader->setOverrideEncoding(encoding);
1536 loadWithDocumentLoader(loader.ptr(), FrameLoadType::Reload, 0, AllowNavigationToInvalidURL::Yes);
1539 void FrameLoader::reload(bool endToEndReload, bool contentBlockersEnabled)
1541 if (!m_documentLoader)
1544 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1545 // Reloading in this case will lose the current contents (see 4151001).
1546 if (m_documentLoader->request().url().isEmpty())
1549 // Replace error-page URL with the URL we were trying to reach.
1550 ResourceRequest initialRequest = m_documentLoader->request();
1551 URL unreachableURL = m_documentLoader->unreachableURL();
1552 if (!unreachableURL.isEmpty())
1553 initialRequest.setURL(unreachableURL);
1555 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1556 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1557 Ref<DocumentLoader> loader = m_client.createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1558 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1560 loader->setUserContentExtensionsEnabled(contentBlockersEnabled);
1562 ResourceRequest& request = loader->request();
1564 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1565 request.setCachePolicy(ReloadIgnoringCacheData);
1567 // If we're about to re-post, set up action so the application can warn the user.
1568 if (request.httpMethod() == "POST")
1569 loader->setTriggeringAction(NavigationAction(request, NavigationType::FormResubmitted));
1571 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1573 loadWithDocumentLoader(loader.ptr(), endToEndReload ? FrameLoadType::ReloadFromOrigin : FrameLoadType::Reload, 0, AllowNavigationToInvalidURL::Yes);
1576 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1578 ASSERT(!m_frame.document() || !m_frame.document()->inPageCache());
1579 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1582 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1583 if (m_inStopAllLoaders)
1586 // Calling stopLoading() on the provisional document loader can blow away
1587 // the frame from underneath.
1588 Ref<Frame> protect(m_frame);
1590 m_inStopAllLoaders = true;
1592 policyChecker().stopCheck();
1594 // If no new load is in progress, we should clear the provisional item from history
1595 // before we call stopLoading.
1596 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1597 history().setProvisionalItem(nullptr);
1599 for (RefPtr<Frame> child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
1600 child->loader().stopAllLoaders(clearProvisionalItemPolicy);
1601 if (m_provisionalDocumentLoader)
1602 m_provisionalDocumentLoader->stopLoading();
1603 if (m_documentLoader)
1604 m_documentLoader->stopLoading();
1606 setProvisionalDocumentLoader(nullptr);
1608 m_checkTimer.stop();
1610 m_inStopAllLoaders = false;
1613 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1618 // Lay out immediately when stopping to immediately clear the old page if we just committed this one
1619 // but haven't laid out/painted yet.
1620 // FIXME: Is this behavior specific to iOS? Or should we expose a setting to toggle this behavior?
1621 if (m_frame.view() && !m_frame.view()->didFirstLayout())
1622 m_frame.view()->layout();
1625 if (deferCheckLoadComplete)
1626 scheduleCheckLoadComplete();
1627 else if (m_frame.page())
1628 checkLoadComplete();
1631 DocumentLoader* FrameLoader::activeDocumentLoader() const
1633 if (m_state == FrameStateProvisional)
1634 return m_provisionalDocumentLoader.get();
1635 return m_documentLoader.get();
1638 bool FrameLoader::isLoading() const
1640 DocumentLoader* docLoader = activeDocumentLoader();
1643 return docLoader->isLoading();
1646 bool FrameLoader::frameHasLoaded() const
1648 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1651 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1653 if (!loader && !m_documentLoader)
1656 ASSERT(loader != m_documentLoader);
1657 ASSERT(!loader || loader->frameLoader() == this);
1659 m_client.prepareForDataSourceReplacement();
1662 // detachChildren() can trigger this frame's unload event, and therefore
1663 // script can run and do just about anything. For example, an unload event that calls
1664 // document.write("") on its parent frame can lead to a recursive detachChildren()
1665 // invocation for this frame. In that case, we can end up at this point with a
1666 // loader that hasn't been deleted but has been detached from its frame. Such a
1667 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1668 // state if we try to use it.
1669 if (loader && !loader->frame())
1672 if (m_documentLoader)
1673 m_documentLoader->detachFromFrame();
1675 m_documentLoader = loader;
1678 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1680 if (m_policyDocumentLoader == loader)
1684 loader->attachToFrame(m_frame);
1685 if (m_policyDocumentLoader
1686 && m_policyDocumentLoader != m_provisionalDocumentLoader
1687 && m_policyDocumentLoader != m_documentLoader)
1688 m_policyDocumentLoader->detachFromFrame();
1690 m_policyDocumentLoader = loader;
1693 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1695 ASSERT(!loader || !m_provisionalDocumentLoader);
1696 ASSERT(!loader || loader->frameLoader() == this);
1698 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1699 m_provisionalDocumentLoader->detachFromFrame();
1701 m_provisionalDocumentLoader = loader;
1704 void FrameLoader::setState(FrameState newState)
1708 if (newState == FrameStateProvisional)
1709 provisionalLoadStarted();
1710 else if (newState == FrameStateComplete) {
1711 frameLoadCompleted();
1712 if (m_documentLoader)
1713 m_documentLoader->stopRecordingResponses();
1717 void FrameLoader::clearProvisionalLoad()
1719 setProvisionalDocumentLoader(nullptr);
1720 m_progressTracker->progressCompleted();
1721 setState(FrameStateComplete);
1724 void FrameLoader::commitProvisionalLoad()
1726 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1727 Ref<Frame> protect(m_frame);
1729 std::unique_ptr<CachedPage> cachedPage;
1730 if (m_loadingFromCachedPage && history().provisionalItem())
1731 cachedPage = PageCache::singleton().take(*history().provisionalItem(), m_frame.page());
1733 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame.tree().uniqueName().string().utf8().data(),
1734 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
1735 pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>");
1738 // In the case where we are not navigating to a cached page, and the system is under (speculative) memory pressure,
1739 // we can try to preemptively release some of the pages in the cache.
1740 // FIXME: Right now the capacity is 1 on iOS devices with 256 MB of RAM, so this will always blow away the whole
1741 // page cache. We could still preemptively prune the page cache while navigating to a cached page if capacity > 1.
1742 // See <rdar://problem/11779846> for more details.
1744 if (MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
1745 LOG(MemoryPressure, "Pruning page cache because under memory pressure at: %s", __PRETTY_FUNCTION__);
1746 LOG(PageCache, "Pruning page cache to 0 due to memory pressure");
1747 // Don't cache any page if we are under memory pressure.
1748 PageCache::singleton().pruneToSizeNow(0, PruningReason::MemoryPressure);
1749 } else if (systemMemoryLevel() <= memoryLevelThresholdToPrunePageCache) {
1750 LOG(MemoryPressure, "Pruning page cache because system memory level is %d at: %s", systemMemoryLevel(), __PRETTY_FUNCTION__);
1751 auto& pageCache = PageCache::singleton();
1752 LOG(PageCache, "Pruning page cache to %d due to low memory (level %d less or equal to %d threshold)", pageCache.maxSize() / 2, systemMemoryLevel(), memoryLevelThresholdToPrunePageCache);
1753 pageCache.pruneToSizeNow(pageCache.maxSize() / 2, PruningReason::MemoryPressure);
1758 willTransitionToCommitted();
1760 if (!m_frame.tree().parent() && history().currentItem()) {
1761 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1762 // We are doing this here because we know for sure that a new page is about to be loaded.
1763 PageCache::singleton().addIfCacheable(*history().currentItem(), m_frame.page());
1766 // For top-level navigations, have JSC throw away linked code. The immediate memory savings far
1767 // outweigh the cost of recompiling in the case of a future backwards navigation.
1768 GCController::singleton().deleteAllLinkedCode();
1772 if (m_loadType != FrameLoadType::Replace)
1773 closeOldDataSources();
1775 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1776 m_client.makeRepresentation(pdl.get());
1778 transitionToCommitted(cachedPage.get());
1780 if (pdl && m_documentLoader) {
1781 // Check if the destination page is allowed to access the previous page's timing information.
1782 Ref<SecurityOrigin> securityOrigin(SecurityOrigin::create(pdl->request().url()));
1783 m_documentLoader->timing().setHasSameOriginAsPreviousDocument(securityOrigin.get().canRequest(m_previousURL));
1786 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1787 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1788 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1789 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1790 if (m_sentRedirectNotification)
1791 clientRedirectCancelledOrFinished(false);
1793 if (cachedPage && cachedPage->document()) {
1795 // FIXME: CachedPage::restore() would dispatch viewport change notification. However UIKit expects load
1796 // commit to happen before any changes to viewport arguments and dealing with this there is difficult.
1797 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(true);
1799 prepareForCachedPageRestore();
1801 // Start request for the main resource and dispatch didReceiveResponse before the load is committed for
1802 // consistency with all other loads. See https://bugs.webkit.org/show_bug.cgi?id=150927.
1803 ResourceError mainResouceError;
1804 unsigned long mainResourceIdentifier;
1805 ResourceRequest mainResourceRequest(cachedPage->documentLoader()->request());
1806 requestFromDelegate(mainResourceRequest, mainResourceIdentifier, mainResouceError);
1807 notifier().dispatchDidReceiveResponse(cachedPage->documentLoader(), mainResourceIdentifier, cachedPage->documentLoader()->response());
1809 // FIXME: This API should be turned around so that we ground CachedPage into the Page.
1810 cachedPage->restore(*m_frame.page());
1812 dispatchDidCommitLoad();
1814 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(false);
1815 m_frame.page()->chrome().dispatchViewportPropertiesDidChange(m_frame.page()->viewportArguments());
1817 // If we have a title let the WebView know about it.
1818 StringWithDirection title = m_documentLoader->title();
1819 if (!title.isNull())
1820 m_client.dispatchDidReceiveTitle(title);
1822 // Send remaining notifications for the main resource.
1823 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), mainResourceIdentifier, mainResourceRequest, ResourceResponse(),
1824 nullptr, static_cast<int>(m_documentLoader->response().expectedContentLength()), 0, mainResouceError);
1830 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame.tree().uniqueName().string().utf8().data(),
1831 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
1833 if (m_loadType == FrameLoadType::Standard && m_documentLoader->isClientRedirect())
1834 history().updateForClientRedirect();
1836 if (m_loadingFromCachedPage) {
1838 // Note, didReceiveDocType is expected to be called for cached pages. See <rdar://problem/5906758> for more details.
1839 if (m_frame.document()->doctype() && m_frame.page())
1840 m_frame.page()->chrome().didReceiveDocType(&m_frame);
1842 m_frame.document()->resume(ActiveDOMObject::PageCache);
1844 // Force a layout to update view size and thereby update scrollbars.
1846 if (!m_client.forceLayoutOnRestoreFromPageCache())
1847 m_frame.view()->forceLayout();
1849 m_frame.view()->forceLayout();
1852 // Main resource delegates were already sent, so we skip the first response here.
1853 for (unsigned i = 1; i < m_documentLoader->responses().size(); ++i) {
1854 const auto& response = m_documentLoader->responses()[i];
1855 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1856 ResourceError error;
1857 unsigned long identifier;
1858 ResourceRequest request(response.url());
1859 requestFromDelegate(request, identifier, error);
1860 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1861 // However, with today's computers and networking speeds, this won't happen in practice.
1862 // Could be an issue with a giant local file.
1863 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1866 // FIXME: Why only this frame and not parent frames?
1867 checkLoadCompleteForThisFrame();
1871 void FrameLoader::transitionToCommitted(CachedPage* cachedPage)
1873 ASSERT(m_client.hasWebView());
1874 ASSERT(m_state == FrameStateProvisional);
1876 if (m_state != FrameStateProvisional)
1879 if (FrameView* view = m_frame.view()) {
1880 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
1881 scrollAnimator->cancelAnimations();
1884 m_client.setCopiesOnScroll();
1885 history().updateForCommit();
1887 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1888 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1889 // or the two will stomp each other.
1890 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1891 if (m_documentLoader)
1893 if (pdl != m_provisionalDocumentLoader)
1896 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1897 if (m_documentLoader)
1898 m_documentLoader->stopLoadingSubresources();
1899 if (m_documentLoader)
1900 m_documentLoader->stopLoadingPlugIns();
1902 setDocumentLoader(m_provisionalDocumentLoader.get());
1903 setProvisionalDocumentLoader(nullptr);
1905 if (pdl != m_documentLoader) {
1906 ASSERT(m_state == FrameStateComplete);
1910 setState(FrameStateCommittedPage);
1912 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
1913 if (m_frame.isMainFrame())
1914 m_frame.page()->chrome().client().needTouchEvents(false);
1917 // Handle adding the URL to the back/forward list.
1918 DocumentLoader* dl = m_documentLoader.get();
1920 switch (m_loadType) {
1921 case FrameLoadType::Forward:
1922 case FrameLoadType::Back:
1923 case FrameLoadType::IndexedBackForward:
1924 if (m_frame.page()) {
1925 // If the first load within a frame is a navigation within a back/forward list that was attached
1926 // without any of the items being loaded then we need to update the history in a similar manner as
1927 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1928 if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame.isMainFrame())
1929 history().updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1931 history().updateForBackForwardNavigation();
1933 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1934 if (history().currentItem() && !cachedPage)
1935 m_pendingStateObject = history().currentItem()->stateObject();
1937 // Create a document view for this document, or used the cached view.
1939 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1940 ASSERT(cachedDocumentLoader);
1941 cachedDocumentLoader->attachToFrame(m_frame);
1942 m_client.transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1944 m_client.transitionToCommittedForNewPage();
1948 case FrameLoadType::Reload:
1949 case FrameLoadType::ReloadFromOrigin:
1950 case FrameLoadType::Same:
1951 case FrameLoadType::Replace:
1952 history().updateForReload();
1953 m_client.transitionToCommittedForNewPage();
1956 case FrameLoadType::Standard:
1957 history().updateForStandardLoad();
1959 m_frame.view()->setScrollbarsSuppressed(true);
1960 m_client.transitionToCommittedForNewPage();
1963 case FrameLoadType::RedirectWithLockedBackForwardList:
1964 history().updateForRedirectWithLockedBackForwardList();
1965 m_client.transitionToCommittedForNewPage();
1968 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1969 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1971 ASSERT_NOT_REACHED();
1974 m_documentLoader->writer().setMIMEType(dl->responseMIMEType());
1976 // Tell the client we've committed this URL.
1977 ASSERT(m_frame.view());
1979 if (m_stateMachine.creatingInitialEmptyDocument())
1982 if (!m_stateMachine.committedFirstRealDocumentLoad())
1983 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1986 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1988 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1989 // the redirect succeeded. We should either rename this API, or add a new method, like
1990 // -webView:didFinishClientRedirectForFrame:
1991 m_client.dispatchDidCancelClientRedirect();
1993 if (!cancelWithLoadInProgress)
1994 m_quickRedirectComing = false;
1996 m_sentRedirectNotification = false;
1999 void FrameLoader::clientRedirected(const URL& url, double seconds, double fireDate, LockBackForwardList lockBackForwardList)
2001 m_client.dispatchWillPerformClientRedirect(url, seconds, fireDate);
2003 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
2004 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
2005 m_sentRedirectNotification = true;
2007 // If a "quick" redirect comes in, we set a special mode so we treat the next
2008 // load as part of the original navigation. If we don't have a document loader, we have
2009 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
2010 // Loads triggered by JavaScript form submissions never count as quick redirects.
2011 m_quickRedirectComing = (lockBackForwardList == LockBackForwardList::Yes || history().currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
2014 bool FrameLoader::shouldReload(const URL& currentURL, const URL& destinationURL)
2016 // This function implements the rule: "Don't reload if navigating by fragment within
2017 // the same URL, but do reload if going to a new URL or to the same URL with no
2018 // fragment identifier at all."
2019 if (!destinationURL.hasFragmentIdentifier())
2021 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
2024 void FrameLoader::closeOldDataSources()
2026 // FIXME: Is it important for this traversal to be postorder instead of preorder?
2027 // If so, add helpers for postorder traversal, and use them. If not, then lets not
2028 // use a recursive algorithm here.
2029 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
2030 child->loader().closeOldDataSources();
2032 if (m_documentLoader)
2033 m_client.dispatchWillClose();
2035 m_client.setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2038 void FrameLoader::prepareForCachedPageRestore()
2040 ASSERT(!m_frame.tree().parent());
2041 ASSERT(m_frame.page());
2042 ASSERT(m_frame.isMainFrame());
2044 m_frame.navigationScheduler().cancel();
2046 // We still have to close the previous part page.
2049 // Delete old status bar messages (if it _was_ activated on last URL).
2050 if (m_frame.script().canExecuteScripts(NotAboutToExecuteScript)) {
2051 DOMWindow* window = m_frame.document()->domWindow();
2052 window->setStatus(String());
2053 window->setDefaultStatus(String());
2057 void FrameLoader::open(CachedFrameBase& cachedFrame)
2059 m_isComplete = false;
2061 // Don't re-emit the load event.
2062 m_didCallImplicitClose = true;
2064 URL url = cachedFrame.url();
2066 // FIXME: I suspect this block of code doesn't do anything.
2067 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2071 Document* document = cachedFrame.document();
2073 ASSERT(document->domWindow());
2075 clear(document, true, true, cachedFrame.isMainFrame());
2077 document->setInPageCache(false);
2079 m_needsClear = true;
2080 m_isComplete = false;
2081 m_didCallImplicitClose = false;
2082 m_outgoingReferrer = url.string();
2084 FrameView* view = cachedFrame.view();
2086 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2088 view->setWasScrolledByUser(false);
2090 Optional<IntRect> previousViewFrameRect = m_frame.view() ? m_frame.view()->frameRect() : Optional<IntRect>(Nullopt);
2091 m_frame.setView(view);
2093 // Use the previous ScrollView's frame rect.
2094 if (previousViewFrameRect)
2095 view->setFrameRect(previousViewFrameRect.value());
2097 m_frame.setDocument(document);
2098 document->domWindow()->resumeFromDocumentSuspension();
2100 updateFirstPartyForCookies();
2102 cachedFrame.restore();
2105 bool FrameLoader::isHostedByObjectElement() const
2107 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
2108 return owner && owner->hasTagName(objectTag);
2111 bool FrameLoader::isReplacing() const
2113 return m_loadType == FrameLoadType::Replace;
2116 void FrameLoader::setReplacing()
2118 m_loadType = FrameLoadType::Replace;
2121 bool FrameLoader::subframeIsLoading() const
2123 // It's most likely that the last added frame is the last to load so we walk backwards.
2124 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling()) {
2125 FrameLoader& childLoader = child->loader();
2126 DocumentLoader* documentLoader = childLoader.documentLoader();
2127 if (documentLoader && documentLoader->isLoadingInAPISense())
2129 documentLoader = childLoader.provisionalDocumentLoader();
2130 if (documentLoader && documentLoader->isLoadingInAPISense())
2132 documentLoader = childLoader.policyDocumentLoader();
2139 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2141 m_client.willChangeTitle(loader);
2144 FrameLoadType FrameLoader::loadType() const
2149 CachePolicy FrameLoader::subresourceCachePolicy() const
2152 return CachePolicyVerify;
2154 if (m_loadType == FrameLoadType::ReloadFromOrigin)
2155 return CachePolicyReload;
2157 if (Frame* parentFrame = m_frame.tree().parent()) {
2158 CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
2159 if (parentCachePolicy != CachePolicyVerify)
2160 return parentCachePolicy;
2163 switch (m_loadType) {
2164 case FrameLoadType::Reload:
2165 return CachePolicyRevalidate;
2166 case FrameLoadType::Back:
2167 case FrameLoadType::Forward:
2168 case FrameLoadType::IndexedBackForward:
2169 return CachePolicyHistoryBuffer;
2170 case FrameLoadType::ReloadFromOrigin:
2171 ASSERT_NOT_REACHED(); // Already handled above.
2172 return CachePolicyReload;
2173 case FrameLoadType::RedirectWithLockedBackForwardList:
2174 case FrameLoadType::Replace:
2175 case FrameLoadType::Same:
2176 case FrameLoadType::Standard:
2177 return CachePolicyVerify;
2180 RELEASE_ASSERT_NOT_REACHED();
2181 return CachePolicyVerify;
2184 void FrameLoader::checkLoadCompleteForThisFrame()
2186 ASSERT(m_client.hasWebView());
2189 case FrameStateProvisional: {
2190 if (!m_provisionalLoadErrorBeingHandledURL.isEmpty())
2193 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2197 // If we've received any errors we may be stuck in the provisional state and actually complete.
2198 const ResourceError& error = pdl->mainDocumentError();
2202 // Check all children first.
2203 RefPtr<HistoryItem> item;
2204 if (Page* page = m_frame.page())
2205 if (isBackForwardLoadType(loadType()))
2206 // Reset the back forward list to the last committed history item at the top level.
2207 item = page->mainFrame().loader().history().currentItem();
2209 // Only reset if we aren't already going to a new provisional item.
2210 bool shouldReset = !history().provisionalItem();
2211 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2212 m_provisionalLoadErrorBeingHandledURL = m_provisionalDocumentLoader->url();
2213 m_client.dispatchDidFailProvisionalLoad(error);
2214 m_provisionalLoadErrorBeingHandledURL = { };
2216 ASSERT(!pdl->isLoading());
2218 // If we're in the middle of loading multipart data, we need to restore the document loader.
2219 if (isReplacing() && !m_documentLoader.get())
2220 setDocumentLoader(m_provisionalDocumentLoader.get());
2222 // Finish resetting the load state, but only if another load hasn't been started by the
2223 // delegate callback.
2224 if (pdl == m_provisionalDocumentLoader)
2225 clearProvisionalLoad();
2226 else if (activeDocumentLoader()) {
2227 URL unreachableURL = activeDocumentLoader()->unreachableURL();
2228 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2229 shouldReset = false;
2232 if (shouldReset && item)
2233 if (Page* page = m_frame.page()) {
2234 page->backForward().setCurrentItem(item.get());
2235 m_frame.loader().client().updateGlobalHistoryItemForPage();
2240 case FrameStateCommittedPage: {
2241 DocumentLoader* dl = m_documentLoader.get();
2242 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2245 setState(FrameStateComplete);
2247 // FIXME: Is this subsequent work important if we already navigated away?
2248 // Maybe there are bugs because of that, or extra work we can skip because
2249 // the new page is ready.
2251 m_client.forceLayoutForNonHTML();
2253 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2254 if (m_frame.page()) {
2255 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadType::Reload || m_loadType == FrameLoadType::ReloadFromOrigin)
2256 history().restoreScrollPositionAndViewState();
2259 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2262 m_progressTracker->progressCompleted();
2263 Page* page = m_frame.page();
2265 if (m_frame.isMainFrame())
2266 page->resetRelevantPaintedObjectCounter();
2269 const ResourceError& error = dl->mainDocumentError();
2271 AXObjectCache::AXLoadingEvent loadingEvent;
2272 if (!error.isNull()) {
2273 m_client.dispatchDidFailLoad(error);
2274 loadingEvent = AXObjectCache::AXLoadingFailed;
2276 #if ENABLE(DATA_DETECTION)
2277 if (m_frame.settings().dataDetectorTypes() != DataDetectorTypeNone) {
2278 RefPtr<Range> documentRange = makeRange(firstPositionInNode(m_frame.document()->documentElement()), lastPositionInNode(m_frame.document()->documentElement()));
2279 m_frame.setDataDetectionResults(DataDetection::detectContentInRange(documentRange, m_frame.settings().dataDetectorTypes()));
2280 if (m_frame.isMainFrame())
2281 m_client.dispatchDidFinishDataDetection(m_frame.dataDetectionResults());
2284 m_client.dispatchDidFinishLoad();
2285 loadingEvent = AXObjectCache::AXLoadingFinished;
2288 // Notify accessibility.
2289 if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache())
2290 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
2292 // The above calls to dispatchDidFinishLoad() might have detached the Frame
2293 // from its Page and also might have caused Page to be deleted.
2294 // Don't assume 'page' is still available to use.
2295 if (m_frame.isMainFrame() && m_frame.page()) {
2296 ASSERT(&m_frame.page()->mainFrame() == &m_frame);
2297 m_frame.page()->mainFrame().diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageLoadedKey(), emptyString(), error.isNull() ? DiagnosticLoggingResultPass : DiagnosticLoggingResultFail, ShouldSample::Yes);
2303 case FrameStateComplete:
2304 m_loadType = FrameLoadType::Standard;
2305 frameLoadCompleted();
2309 ASSERT_NOT_REACHED();
2312 void FrameLoader::continueLoadAfterWillSubmitForm()
2314 if (!m_provisionalDocumentLoader)
2317 prepareForLoadStart();
2319 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2320 // so we need to null check it again.
2321 if (!m_provisionalDocumentLoader)
2324 DocumentLoader* activeDocLoader = activeDocumentLoader();
2325 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2328 m_loadingFromCachedPage = false;
2329 m_provisionalDocumentLoader->startLoadingMainResource();
2332 static URL originatingURLFromBackForwardList(Page* page)
2334 // FIXME: Can this logic be replaced with m_frame.document()->firstPartyForCookies()?
2335 // It has the same meaning of "page a user thinks is the current one".
2338 int backCount = page->backForward().backCount();
2339 for (int backIndex = 0; backIndex <= backCount; backIndex++) {
2340 // FIXME: At one point we had code here to check a "was user gesture" flag.
2341 // Do we need to restore that logic?
2342 HistoryItem* historyItem = page->backForward().itemAtIndex(-backIndex);
2346 originalURL = historyItem->originalURL();
2347 if (!originalURL.isNull())
2354 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2358 // If there is no referrer, assume that the download was initiated directly, so current document is
2359 // completely unrelated to it. See <rdar://problem/5294691>.
2360 // FIXME: Referrer is not sent in many other cases, so we will often miss this important information.
2361 // Find a better way to decide whether the download was unrelated to current document.
2362 if (!request.httpReferrer().isNull()) {
2363 // find the first item in the history that was originated by the user
2364 originalURL = originatingURLFromBackForwardList(m_frame.page());
2367 if (originalURL.isNull())
2368 originalURL = request.url();
2370 if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
2371 unsigned port = originalURL.port();
2373 // 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.
2374 // 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.
2375 String hostOnlyURLString;
2377 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ':', String::number(port));
2379 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
2381 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2382 request.setFirstPartyForCookies(URL(URL(), hostOnlyURLString));
2386 void FrameLoader::didLayout(LayoutMilestones milestones)
2388 ASSERT(m_frame.isMainFrame());
2390 m_client.dispatchDidLayout(milestones);
2393 void FrameLoader::didFirstLayout()
2396 // Only send layout-related delegate callbacks synchronously for the main frame to
2397 // avoid reentering layout for the main frame while delivering a layout-related delegate
2398 // callback for a subframe.
2399 if (&m_frame != &m_frame.page()->mainFrame())
2402 if (m_frame.page() && isBackForwardLoadType(m_loadType))
2403 history().restoreScrollPositionAndViewState();
2405 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2406 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2409 void FrameLoader::frameLoadCompleted()
2411 // Note: Can be called multiple times.
2413 m_client.frameLoadCompleted();
2415 history().updateForFrameLoadCompleted();
2417 // After a canceled provisional load, firstLayoutDone is false.
2418 // Reset it to true if we're displaying a page.
2419 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2420 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2423 void FrameLoader::detachChildren()
2425 // detachChildren() will fire the unload event in each subframe and the
2426 // HTML specification states that the parent document's ignore-opens-during-unload counter while
2427 // this event is being fired in its subframes:
2428 // https://html.spec.whatwg.org/multipage/browsers.html#unload-a-document
2429 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2431 Vector<Ref<Frame>, 16> childrenToDetach;
2432 childrenToDetach.reserveInitialCapacity(m_frame.tree().childCount());
2433 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling())
2434 childrenToDetach.uncheckedAppend(*child);
2435 for (auto& child : childrenToDetach)
2436 child->loader().detachFromParent();
2439 void FrameLoader::closeAndRemoveChild(Frame* child)
2441 child->tree().detachFromParent();
2443 child->setView(nullptr);
2444 if (child->ownerElement() && child->page())
2445 child->page()->decrementSubframeCount();
2446 child->willDetachPage();
2447 child->detachFromPage();
2449 m_frame.tree().removeChild(child);
2452 // Called every time a resource is completely loaded or an error is received.
2453 void FrameLoader::checkLoadComplete()
2455 ASSERT(m_client.hasWebView());
2457 m_shouldCallCheckLoadComplete = false;
2459 if (!m_frame.page())
2462 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2463 // is currently needed in order to null out the previous history item for all frames.
2464 Vector<Ref<Frame>, 16> frames;
2465 for (Frame* frame = &m_frame.mainFrame(); frame; frame = frame->tree().traverseNext())
2466 frames.append(*frame);
2468 // To process children before their parents, iterate the vector backwards.
2469 for (auto frame = frames.rbegin(); frame != frames.rend(); ++frame) {
2470 if ((*frame)->page())
2471 (*frame)->loader().checkLoadCompleteForThisFrame();
2475 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2478 return m_frame.document()->cachedResourceLoader().requestCount();
2481 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
2482 count += frame->document()->cachedResourceLoader().requestCount();
2486 String FrameLoader::userAgent(const URL& url) const
2488 return m_client.userAgent(url);
2491 void FrameLoader::dispatchOnloadEvents()
2493 m_client.dispatchDidDispatchOnloadEvents();
2495 if (documentLoader())
2496 documentLoader()->dispatchOnloadEvents();
2499 void FrameLoader::frameDetached()
2502 m_frame.document()->stopActiveDOMObjects();
2506 void FrameLoader::detachFromParent()
2508 Ref<Frame> protect(m_frame);
2511 history().saveScrollPositionAndViewStateToItem(history().currentItem());
2513 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2514 // will trigger the unload event handlers of any child frames, and those event
2515 // handlers might start a new subresource load in this frame.
2518 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2520 detachViewsAndDocumentLoader();
2522 m_progressTracker = nullptr;
2524 if (Frame* parent = m_frame.tree().parent()) {
2525 parent->loader().closeAndRemoveChild(&m_frame);
2526 parent->loader().scheduleCheckCompleted();
2528 m_frame.setView(nullptr);
2529 m_frame.willDetachPage();
2530 m_frame.detachFromPage();
2534 void FrameLoader::detachViewsAndDocumentLoader()
2536 m_client.detachedFromParent2();
2537 setDocumentLoader(nullptr);
2538 m_client.detachedFromParent3();
2541 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2543 addExtraFieldsToRequest(request, m_loadType, false);
2546 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2548 // FIXME: Using m_loadType seems wrong for some callers.
2549 // If we are only preparing to load the main resource, that is previous load's load type!
2550 addExtraFieldsToRequest(request, m_loadType, true);
2553 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2555 // Don't set the cookie policy URL if it's already been set.
2556 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2557 if (request.firstPartyForCookies().isEmpty()) {
2558 if (mainResource && m_frame.isMainFrame())
2559 request.setFirstPartyForCookies(request.url());
2560 else if (Document* document = m_frame.document())
2561 request.setFirstPartyForCookies(document->firstPartyForCookies());
2564 // The remaining modifications are only necessary for HTTP and HTTPS.
2565 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2568 applyUserAgent(request);
2570 if (!mainResource) {
2571 if (request.isConditional())
2572 request.setCachePolicy(ReloadIgnoringCacheData);
2573 else if (documentLoader()->isLoadingInAPISense()) {
2574 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2575 // original request cache policy for two reasons:
2576 // 1. For POST requests, we mutate the cache policy for the main resource,
2577 // but we do not want this to apply to subresources
2578 // 2. Delegates that modify the cache policy using willSendRequest: should
2579 // not affect any other resources. Such changes need to be done
2581 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2582 // 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.
2583 // This policy is set on initial request too, but should not be inherited.
2584 ResourceRequestCachePolicy subresourceCachePolicy = (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2585 request.setCachePolicy(subresourceCachePolicy);
2587 request.setCachePolicy(UseProtocolCachePolicy);
2589 // FIXME: Other FrameLoader functions have duplicated code for setting cache policy of main request when reloading.
2590 // It seems better to manage it explicitly than to hide the logic inside addExtraFieldsToRequest().
2591 } else if (loadType == FrameLoadType::Reload || loadType == FrameLoadType::ReloadFromOrigin || request.isConditional())
2592 request.setCachePolicy(ReloadIgnoringCacheData);
2594 if (m_overrideCachePolicyForTesting)
2595 request.setCachePolicy(m_overrideCachePolicyForTesting.value());
2596 if (m_overrideResourceLoadPriorityForTesting)
2597 request.setPriority(m_overrideResourceLoadPriorityForTesting.value());
2599 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2600 if (loadType == FrameLoadType::Reload)
2601 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
2602 else if (loadType == FrameLoadType::ReloadFromOrigin) {
2603 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
2604 request.setHTTPHeaderField(HTTPHeaderName::Pragma, "no-cache");
2609 request.setHTTPAccept(defaultAcceptHeader);
2611 // Make sure we send the Origin header.
2612 addHTTPOriginIfNeeded(request, String());
2614 // Only set fallback array if it's still empty (later attempts may be incorrect, see bug 117818).
2615 if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
2616 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2617 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame.document()->encoding(), m_frame.settings().defaultTextEncodingName());
2621 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2623 if (!request.httpOrigin().isEmpty())
2624 return; // Request already has an Origin header.
2626 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2627 // For example, if an intranet page has a hyperlink to an external web
2628 // site, we don't want to include the Origin of the request because it
2629 // will leak the internal host name. Similar privacy concerns have lead
2630 // to the widespread suppression of the Referer header at the network
2632 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2635 // For non-GET and non-HEAD methods, always send an Origin header so the
2636 // server knows we support this feature.
2638 if (origin.isEmpty()) {
2639 // If we don't know what origin header to attach, we attach the value
2640 // for an empty origin.
2641 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2645 request.setHTTPOrigin(origin);
2648 void FrameLoader::loadPostRequest(const FrameLoadRequest& request, const String& referrer, FrameLoadType loadType, Event* event, PassRefPtr<FormState> prpFormState)
2650 RefPtr<FormState> formState = prpFormState;
2652 String frameName = request.frameName();
2653 LockHistory lockHistory = request.lockHistory();
2654 AllowNavigationToInvalidURL allowNavigationToInvalidURL = request.allowNavigationToInvalidURL();
2655 NewFrameOpenerPolicy openerPolicy = request.newFrameOpenerPolicy();
2657 const ResourceRequest& inRequest = request.resourceRequest();
2658 const URL& url = inRequest.url();
2659 const String& contentType = inRequest.httpContentType();
2660 String origin = inRequest.httpOrigin();
2662 ResourceRequest workingResourceRequest(url);
2664 if (!referrer.isEmpty())
2665 workingResourceRequest.setHTTPReferrer(referrer);
2666 workingResourceRequest.setHTTPOrigin(origin);
2667 workingResourceRequest.setHTTPMethod("POST");
2668 workingResourceRequest.setHTTPBody(inRequest.httpBody());
2669 workingResourceRequest.setHTTPContentType(contentType);
2670 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2672 NavigationAction action(workingResourceRequest, loadType, true, event, request.shouldOpenExternalURLsPolicy());
2674 if (!frameName.isEmpty()) {
2675 // The search for a target frame is done earlier in the case of form submission.
2676 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName)) {
2677 targetFrame->loader().loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release(), allowNavigationToInvalidURL);
2681 policyChecker().checkNewWindowPolicy(action, workingResourceRequest, formState.release(), frameName, [this, allowNavigationToInvalidURL, openerPolicy](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
2682 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
2687 // must grab this now, since this load may stop the previous load and clear this flag
2688 bool isRedirect = m_quickRedirectComing;
2689 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release(), allowNavigationToInvalidURL);
2691 m_quickRedirectComing = false;
2692 if (m_provisionalDocumentLoader)
2693 m_provisionalDocumentLoader->setIsClientRedirect(true);
2697 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, RefPtr<SharedBuffer>& data)
2699 ASSERT(m_frame.document());
2700 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), request.url(), outgoingReferrer());
2702 ResourceRequest initialRequest = request;
2703 initialRequest.setTimeoutInterval(10);
2705 if (!referrer.isEmpty())
2706 initialRequest.setHTTPReferrer(referrer);
2707 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2709 initialRequest.setFirstPartyForCookies(m_frame.mainFrame().loader().documentLoader()->request().url());
2711 addExtraFieldsToSubresourceRequest(initialRequest);
2713 unsigned long identifier = 0;
2714 ResourceRequest newRequest(initialRequest);
2715 requestFromDelegate(newRequest, identifier, error);
2717 #if ENABLE(CONTENT_EXTENSIONS)
2718 if (error.isNull()) {
2719 if (auto* page = m_frame.page()) {
2720 if (auto* controller = page->userContentController()) {
2721 if (m_documentLoader && controller->processContentExtensionRulesForLoad(newRequest, ResourceType::Raw, *m_documentLoader) == ContentExtensions::BlockedStatus::Blocked) {
2723 error = ResourceError(errorDomainWebKitInternal, 0, initialRequest.url(), emptyString());
2732 if (error.isNull()) {
2733 ASSERT(!newRequest.isNull());
2735 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2736 Vector<char> buffer;
2737 platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, buffer);
2738 data = SharedBuffer::adoptVector(buffer);
2739 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2742 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data ? data->data() : nullptr, data ? data->size() : 0, -1, error);
2746 const ResourceRequest& FrameLoader::originalRequest() const
2748 return activeDocumentLoader()->originalRequestCopy();
2751 void FrameLoader::receivedMainResourceError(const ResourceError& error)
2753 // Retain because the stop may release the last reference to it.
2754 Ref<Frame> protect(m_frame);
2756 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2757 // FIXME: Don't want to do this if an entirely new load is going, so should check
2758 // that both data sources on the frame are either this or nil.
2760 if (m_client.shouldFallBack(error))
2761 handleFallbackContent();
2763 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2764 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2765 m_submittedFormURL = URL();
2767 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2768 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2769 // so that the existing view (that wenever got far enough to replace) can continue being used.
2770 history().invalidateCurrentItemCachedPage();
2772 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2773 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2774 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2775 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2777 if (m_sentRedirectNotification)
2778 clientRedirectCancelledOrFinished(false);
2783 checkLoadComplete();
2786 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2788 m_quickRedirectComing = false;
2790 if (!shouldContinue)
2793 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2794 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2795 m_provisionalDocumentLoader->stopLoading();
2796 setProvisionalDocumentLoader(nullptr);
2799 bool isRedirect = m_quickRedirectComing || policyChecker().loadType() == FrameLoadType::RedirectWithLockedBackForwardList;
2800 loadInSameDocument(request.url(), 0, !isRedirect);
2803 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const URL& url)
2805 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2806 // currently displaying a frameset, or if the URL does not have a fragment.
2807 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2809 // FIXME: What about load types other than Standard and Reload?
2811 return (!isFormSubmission || equalLettersIgnoringASCIICase(httpMethod, "get"))
2812 && loadType != FrameLoadType::Reload
2813 && loadType != FrameLoadType::ReloadFromOrigin
2814 && loadType != FrameLoadType::Same
2815 && !shouldReload(m_frame.document()->url(), url)
2816 // We don't want to just scroll if a link from within a
2817 // frameset is trying to reload the frameset into _top.
2818 && !m_frame.document()->isFrameSet();
2821 void FrameLoader::scrollToFragmentWithParentBoundary(const URL& url)
2823 FrameView* view = m_frame.view();
2827 // Leaking scroll position to a cross-origin ancestor would permit the so-called "framesniffing" attack.
2828 RefPtr<Frame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame.document()->findUnsafeParentScrollPropagationBoundary() : 0);
2831 boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
2833 view->scrollToFragment(url);
2836 boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
2839 bool FrameLoader::shouldClose()
2841 Page* page = m_frame.page();
2844 if (!page->chrome().canRunBeforeUnloadConfirmPanel())
2847 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2848 Vector<Ref<Frame>, 16> targetFrames;
2849 targetFrames.append(m_frame);
2850 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().traverseNext(&m_frame))
2851 targetFrames.append(*child);
2853 bool shouldClose = false;
2855 NavigationDisablerForBeforeUnload navigationDisabler;
2858 for (i = 0; i < targetFrames.size(); i++) {
2859 if (!targetFrames[i]->tree().isDescendantOf(&m_frame))
2861 if (!targetFrames[i]->loader().dispatchBeforeUnloadEvent(page->chrome(), this))
2865 if (i == targetFrames.size())
2870 m_submittedFormURL = URL();
2872 m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
2876 void FrameLoader::dispatchUnloadEvents(UnloadEventPolicy unloadEventPolicy)
2878 if (!m_frame.document())
2881 // We store the frame's page in a local variable because the frame might get detached inside dispatchEvent.
2882 ForbidPromptsScope forbidPrompts(m_frame.page());
2883 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2885 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
2886 auto* currentFocusedElement = m_frame.document()->focusedElement();
2887 if (is<HTMLInputElement>(currentFocusedElement))
2888 downcast<HTMLInputElement>(*currentFocusedElement).endEditing();
2889 if (m_pageDismissalEventBeingDispatched == PageDismissalType::None) {
2890 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
2891 m_pageDismissalEventBeingDispatched = PageDismissalType::PageHide;
2892 m_frame.document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame.document()->inPageCache()), m_frame.document());
2895 // FIXME: update Page Visibility state here.
2896 // https://bugs.webkit.org/show_bug.cgi?id=116770
2898 if (!m_frame.document()->inPageCache()) {
2899 Ref<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
2900 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2901 // while dispatching the event, so protect it to prevent writing the end
2902 // time into freed memory.
2903 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
2904 m_pageDismissalEventBeingDispatched = PageDismissalType::Unload;
2905 if (documentLoader && documentLoader->timing().navigationStart() && !documentLoader->timing().unloadEventStart() && !documentLoader->timing().unloadEventEnd()) {
2906 auto& timing = documentLoader->timing();
2907 timing.markUnloadEventStart();
2908 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
2909 timing.markUnloadEventEnd();
2911 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
2914 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
2915 if (m_frame.document())
2916 m_frame.document()->updateStyleIfNeeded();
2917 m_wasUnloadEventEmitted = true;
2920 // Dispatching the unload event could have made m_frame.document() null.
2921 if (!m_frame.document())
2924 if (m_frame.document()->inPageCache())
2927 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
2928 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
2929 && m_frame.document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
2931 if (!keepEventListeners)
2932 m_frame.document()->removeAllEventListeners();
2935 bool FrameLoader::dispatchBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
2937 DOMWindow* domWindow = m_frame.document()->domWindow();
2941 RefPtr<Document> document = m_frame.document();
2942 if (!document->bodyOrFrameset())
2945 Ref<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2946 m_pageDismissalEventBeingDispatched = PageDismissalType::BeforeUnload;
2949 ForbidPromptsScope forbidPrompts(m_frame.page());
2950 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2951 domWindow->dispatchEvent(beforeUnloadEvent, domWindow->document());
2954 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
2956 if (!beforeUnloadEvent->defaultPrevented())
2957 document->defaultEventHandler(beforeUnloadEvent.ptr());
2958 if (beforeUnloadEvent->returnValue().isNull())
2961 // If the navigating FrameLoader has already shown a beforeunload confirmation panel for the current navigation attempt,
2962 // this frame is not allowed to cause another one to be shown.
2963 if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
2964 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation."));
2968 // We should only display the beforeunload dialog for an iframe if its SecurityOrigin matches all
2969 // ancestor frame SecurityOrigins up through the navigating FrameLoader.
2970 if (frameLoaderBeingNavigated != this) {
2971 Frame* parentFrame = m_frame.tree().parent();
2972 while (parentFrame) {
2973 Document* parentDocument = parentFrame->document();
2974 if (!parentDocument)
2976 if (!m_frame.document() || !m_frame.document()->securityOrigin()->canAccess(parentDocument->securityOrigin())) {
2977 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show beforeunload confirmation dialog on behalf of a frame with different security origin. Protocols, domains, and ports must match."));
2981 if (&parentFrame->loader() == frameLoaderBeingNavigated)
2984 parentFrame = parentFrame->tree().parent();
2987 // The navigatingFrameLoader should always be in our ancestory.
2988 ASSERT(parentFrame);
2989 ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
2992 frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
2994 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
2995 return chrome.runBeforeUnloadConfirmPanel(text, &m_frame);
2998 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
3000 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
3001 // nil policyDataSource because loading the alternate page will have passed
3002 // through this method already, nested; otherwise, policyDataSource should still be set.
3003 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
3005 bool isTargetItem = history().provisionalItem() ? history().provisionalItem()->isTargetItem() : false;
3007 bool urlIsDisallowed = allowNavigationToInvalidURL == AllowNavigationToInvalidURL::No && !request.url().isValid();
3009 // Three reasons we can't continue:
3010 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
3011 // is the user responding Cancel to the form repost nag sheet.
3012 // 2) User responded Cancel to an alert popped up by the before unload event handler.
3013 // 3) The request's URL is invalid and navigation to invalid URLs is disallowed.
3014 bool canContinue = shouldContinue && shouldClose() && !urlIsDisallowed;
3017 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
3018 // need to report that the client redirect was cancelled.
3019 // FIXME: The client should be told about ignored non-quick redirects, too.
3020 if (m_quickRedirectComing)
3021 clientRedirectCancelledOrFinished(false);
3023 setPolicyDocumentLoader(nullptr);
3025 // If the navigation request came from the back/forward menu, and we punt on it, we have the
3026 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
3027 // we only do this when punting a navigation for the target frame or top-level frame.
3028 if ((isTargetItem || m_frame.isMainFrame()) && isBackForwardLoadType(policyChecker().loadType())) {
3029 if (Page* page = m_frame.page()) {
3030 if (HistoryItem* resetItem = m_frame.mainFrame().loader().history().currentItem()) {
3031 page->backForward().setCurrentItem(resetItem);
3032 m_frame.loader().client().updateGlobalHistoryItemForPage();
3039 FrameLoadType type = policyChecker().loadType();
3040 // A new navigation is in progress, so don't clear the history's provisional item.
3041 stopAllLoaders(ShouldNotClearProvisionalItem);
3043 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
3044 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
3045 if (!m_frame.page())
3048 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
3050 setState(FrameStateProvisional);
3052 setPolicyDocumentLoader(nullptr);
3054 if (isBackForwardLoadType(type)) {
3055 auto& diagnosticLoggingClient = m_frame.mainFrame().diagnosticLoggingClient();
3056 if (history().provisionalItem()->isInPageCache()) {
3057 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultPass, ShouldSample::Yes);
3058 loadProvisionalItemFromCachedPage();
3061 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultFail, ShouldSample::Yes);
3065 continueLoadAfterWillSubmitForm();
3069 m_client.dispatchWillSubmitForm(formState, [this](PolicyAction action) {
3070 policyChecker().continueLoadAfterWillSubmitForm(action);
3074 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
3075 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL, NewFrameOpenerPolicy openerPolicy)
3077 if (!shouldContinue)
3080 Ref<Frame> frame(m_frame);
3081 RefPtr<Frame> mainFrame = m_client.dispatchCreatePage(action);
3085 if (frameName != "_blank")
3086 mainFrame->tree().setName(frameName);
3088 mainFrame->page()->setOpenedByDOM();
3089 mainFrame->loader().m_client.dispatchShow();
3090 if (openerPolicy == NewFrameOpenerPolicy::Allow) {
3091 mainFrame->loader().setOpener(frame.ptr());
3092 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
3095 NavigationAction newAction(request, action.shouldOpenExternalURLsPolicy());
3096 mainFrame->loader().loadWithNavigationAction(request, newAction, LockHistory::No, FrameLoadType::Standard, formState, allowNavigationToInvalidURL);
3099 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
3101 ASSERT(!request.isNull());
3104 if (Page* page = m_frame.page()) {
3105 identifier = page->progress().createUniqueIdentifier();
3106 notifier().assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
3109 ResourceRequest newRequest(request);
3110 notifier().dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
3112 if (newRequest.isNull())
3113 error = cancelledError(request);
3115 error = ResourceError();
3117 request = newRequest;
3120 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
3122 Page* page = m_frame.page();
3126 if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
3129 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
3130 if (resource->type() == CachedResource::MainResource)
3133 if (!page->areMemoryCacheClientCallsEnabled()) {
3134 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), resource);
3135 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
3136 m_documentLoader->didTellClientAboutLoad(resource->url());
3140 if (m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
3141 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), resource);
3142 m_documentLoader->didTellClientAboutLoad(resource->url());
3146 unsigned long identifier;
3147 ResourceError error;
3148 requestFromDelegate(newRequest, identifier, error);
3149 InspectorInstrumentation::markResourceAsCached(*page, identifier);
3150 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
3153 void FrameLoader::applyUserAgent(ResourceRequest& request)
3155 String userAgent = this->userAgent(request.url());
3156 ASSERT(!userAgent.isNull());
3157 request.setHTTPUserAgent(userAgent);
3160 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const URL& url, unsigned long requestIdentifier)
3162 Frame& topFrame = m_frame.tree().top();
3163 if (&m_frame == &topFrame)
3166 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
3168 switch (disposition) {
3169 case XFrameOptionsSameOrigin: {
3170 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
3171 if (!origin->isSameSchemeHostPort(topFrame.document()->securityOrigin()))
3173 for (Frame* frame = m_frame.tree().parent(); frame; frame = frame->tree().parent()) {
3174 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin()))
3179 case XFrameOptionsDeny:
3181 case XFrameOptionsAllowAll:
3183 case XFrameOptionsConflict:
3184 m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.", requestIdentifier);
3186 case XFrameOptionsInvalid:
3187 m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
3189 case XFrameOptionsNone:
3192 ASSERT_NOT_REACHED();
3196 void FrameLoader::loadProvisionalItemFromCachedPage()
3198 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
3199 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().stringCenterEllipsizedToLength().utf8().data());
3201 prepareForLoadStart();
3203 m_loadingFromCachedPage = true;
3205 // Should have timing data from previous time(s) the page was shown.
3206 ASSERT(provisionalLoader->timing().navigationStart());
3207 provisionalLoader->resetTiming();
3208 provisionalLoader->timing().markNavigationStart();
3210 provisionalLoader->setCommitted(true);
3211 commitProvisionalLoad();
3214 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const URL& url) const
3216 if (!history().currentItem())
3218 return url == history().currentItem()->url() || url == history().currentItem()->originalURL();
3221 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const URL& url) const
3223 if (!equalLettersIgnoringASCIICase(url.string(), "about:srcdoc"))
3225 HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement();
3228 if (!ownerElement->hasTagName(iframeTag))
3230 return ownerElement->fastHasAttribute(srcdocAttr);
3233 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
3235 Frame* frame = m_frame.tree().find(name);
3237 // FIXME: Eventually all callers should supply the actual activeDocument so we can call canNavigate with the right document.
3238 if (!activeDocument)
3239 activeDocument = m_frame.document();
3241 if (!activeDocument->canNavigate(frame))
3247 void FrameLoader::loadSameDocumentItem(HistoryItem& item)
3249 ASSERT(item.documentSequenceNumber() == history().currentItem()->documentSequenceNumber());
3251 Ref<Frame> protect(m_frame);
3253 // Save user view state to the current history item here since we don't do a normal load.
3254 // FIXME: Does form state need to be saved here too?
3255 history().saveScrollPositionAndViewStateToItem(history().currentItem());
3256 if (FrameView* view = m_frame.view())
3257 view->setWasScrolledByUser(false);
3259 history().setCurrentItem(&item);
3261 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3262 loadInSameDocument(item.url(), item.stateObject(), false);
3264 // Restore user view state from the current history item here since we don't do a normal load.
3265 history().restoreScrollPositionAndViewState();
3268 // FIXME: This function should really be split into a couple pieces, some of
3269 // which should be methods of HistoryController and some of which should be
3270 // methods of FrameLoader.
3271 void FrameLoader::loadDifferentDocumentItem(HistoryItem& item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
3273 // Remember this item so we can traverse any child items as child frames load
3274 history().setProvisionalItem(&item);
3276 if (CachedPage* cachedPage = PageCache::singleton().get(item, m_frame.page())) {
3277 auto documentLoader = cachedPage->documentLoader();
3278 m_client.updateCachedDocumentLoader(*documentLoader);
3279 documentLoader->setTriggeringAction(NavigationAction(documentLoader->request(), loadType, false));
3280 documentLoader->setLastCheckedRequest(ResourceRequest());
3281 loadWithDocumentLoader(documentLoader, loadType, 0, AllowNavigationToInvalidURL::Yes);
3285 URL itemURL = item.url();
3286 URL itemOriginalURL = item.originalURL();
3288 if (documentLoader())
3289 currentURL = documentLoader()->url();
3290 RefPtr<FormData> formData = item.formData();
3292 ResourceRequest request(itemURL);
3294 if (!item.referrer().isNull())
3295 request.setHTTPReferrer(item.referrer());
3297 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = shouldOpenExternalURLsPolicyToApply(m_frame, item.shouldOpenExternalURLsPolicy());
3298 bool isFormSubmission = false;
3299 Event* event = nullptr;
3301 // If this was a repost that failed the page cache, we might try to repost the form.
3302 NavigationAction action;
3304 formData->generateFiles(m_frame.document());
3306 request.setHTTPMethod("POST");
3307 request.setHTTPBody(WTFMove(formData));
3308 request.setHTTPContentType(item.formContentType());
3309 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item.referrer());
3310 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3312 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3313 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3314 addExtraFieldsToRequest(request, loadType, true);
3316 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3317 // We want to know this before talking to the policy delegate, since it affects whether
3318 // we show the DoYouReallyWantToRepost nag.
3320 // This trick has a small bug (3123893) where we might find a cache hit, but then
3321 // have the item vanish when we try to use it in the ensuing nav. This should be
3322 // extremely rare, but in that case the user will get an error on the navigation.
3324 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3325 request.setCachePolicy(ReturnCacheDataDontLoad);
3326 action = NavigationAction(request, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy);
3328 request.setCachePolicy(ReturnCacheDataElseLoad);
3329 action = NavigationAction(request, NavigationType::FormResubmitted, event, shouldOpenExternalURLsPolicy);
3333 case FrameLoadType::Reload:
3334 case FrameLoadType::ReloadFromOrigin:
3335 request.setCachePolicy(ReloadIgnoringCacheData);
3337 case FrameLoadType::Back:
3338 case FrameLoadType::Forward:
3339 case FrameLoadType::IndexedBackForward:
3340 request.setCachePolicy(ReturnCacheDataElseLoad);
3342 case FrameLoadType::Standard:
3343 case FrameLoadType::RedirectWithLockedBackForwardList:
3345 case FrameLoadType::Same:
3347 ASSERT_NOT_REACHED();
3350 addExtraFieldsToRequest(request, loadType, true);
3352 ResourceRequest requestForOriginalURL(request);
3353 requestForOriginalURL.setURL(itemOriginalURL);
3354 action = NavigationAction(requestForOriginalURL, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy);
3357 loadWithNavigationAction(request, action, LockHistory::No, loadType, 0, AllowNavigationToInvalidURL::Yes);
3360 // Loads content into this frame, as specified by history item
3361 void FrameLoader::loadItem(HistoryItem& item, FrameLoadType loadType)
3363 m_requestedHistoryItem = &item;
3364 HistoryItem* currentItem = history().currentItem();
3365 bool sameDocumentNavigation = currentItem && item.shouldDoSameDocumentNavigationTo(*currentItem);
3367 if (sameDocumentNavigation)
3368 loadSameDocumentItem(item);
3370 loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
3373 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3375 ASSERT(m_state == FrameStateProvisional);
3376 ASSERT(!m_loadingFromCachedPage);
3377 ASSERT(history().provisionalItem());
3378 ASSERT(history().provisionalItem()->formData());
3379 ASSERT(history().provisionalItem() == m_requestedHistoryItem.get());
3381 FrameLoadType loadType = m_loadType;
3382 HistoryItem& item = *history().provisionalItem();
3384 stopAllLoaders(ShouldNotClearProvisionalItem);
3385 loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
3388 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3390 ResourceError error = m_client.cancelledError(request);
3391 error.setIsCancellation(true);
3395 ResourceError FrameLoader::blockedByContentBlockerError(const ResourceRequest& request) const
3397 return m_client.blockedByContentBlockerError(request);
3400 ResourceError FrameLoader::blockedError(const ResourceRequest& request) const
3402 ResourceError error = m_client.blockedError(request);
3403 error.setIsCancellation(true);
3408 RetainPtr<CFDictionaryRef> FrameLoader::connectionProperties(ResourceLoader* loader)
3410 return m_client.connectionProperties(loader->documentLoader(), loader->identifier());
3414 String FrameLoader::referrer() const
3416 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3419 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3421 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript))
3424 Vector<Ref<DOMWrapperWorld>> worlds;
3425 ScriptController::getAllWorlds(worlds);
3426 for (auto& world : worlds)
3427 dispatchDidClearWindowObjectInWorld(world);
3430 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
3432 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame.script().existingWindowShell(world))
3435 m_client.dispatchDidClearWindowObjectInWorld(world);