2 * Copyright (C) 2006-2018 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"
47 #include "ContentFilter.h"
48 #include "ContentSecurityPolicy.h"
49 #include "DOMWindow.h"
50 #include "DatabaseManager.h"
51 #include "DiagnosticLoggingClient.h"
52 #include "DiagnosticLoggingKeys.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"
65 #include "FrameLoadRequest.h"
66 #include "FrameLoaderClient.h"
67 #include "FrameNetworkingContext.h"
68 #include "FrameTree.h"
69 #include "FrameView.h"
70 #include "GCController.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 "IgnoreOpensDuringUnloadCountIncrementer.h"
81 #include "InspectorController.h"
82 #include "InspectorInstrumentation.h"
83 #include "LinkLoader.h"
84 #include "LoadTiming.h"
85 #include "LoaderStrategy.h"
87 #include "MemoryCache.h"
88 #include "MemoryRelease.h"
89 #include "NavigationDisabler.h"
90 #include "NavigationScheduler.h"
92 #include "PageCache.h"
93 #include "PageTransitionEvent.h"
94 #include "PerformanceLogging.h"
95 #include "PlatformStrategies.h"
96 #include "PluginData.h"
97 #include "PluginDocument.h"
98 #include "PolicyChecker.h"
99 #include "ProgressTracker.h"
100 #include "ResourceHandle.h"
101 #include "ResourceLoadInfo.h"
102 #include "ResourceLoadObserver.h"
103 #include "ResourceRequest.h"
104 #include "SVGDocument.h"
105 #include "SVGLocatable.h"
106 #include "SVGNames.h"
107 #include "SVGViewElement.h"
108 #include "SVGViewSpec.h"
109 #include "ScriptController.h"
110 #include "ScriptSourceCode.h"
111 #include "ScrollAnimator.h"
112 #include "SecurityOrigin.h"
113 #include "SecurityPolicy.h"
114 #include "SegmentedString.h"
115 #include "SerializedScriptValue.h"
116 #include "Settings.h"
117 #include "ShouldTreatAsContinuingLoad.h"
118 #include "SubframeLoader.h"
119 #include "SubresourceLoader.h"
120 #include "TextResourceDecoder.h"
121 #include "UserContentController.h"
122 #include "UserGestureIndicator.h"
123 #include "WindowFeatures.h"
124 #include "XMLDocumentParser.h"
125 #include <wtf/CompletionHandler.h>
127 #include <wtf/SetForScope.h>
128 #include <wtf/StdLibExtras.h>
129 #include <wtf/SystemTracing.h>
130 #include <wtf/text/CString.h>
131 #include <wtf/text/WTFString.h>
133 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
137 #if ENABLE(DATA_DETECTION)
138 #include "DataDetection.h"
142 #include "DocumentType.h"
143 #include "ResourceLoader.h"
144 #include "RuntimeApplicationChecks.h"
145 #include "WKContentObservation.h"
148 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - FrameLoader::" fmt, this, ##__VA_ARGS__)
152 using namespace HTMLNames;
153 using namespace SVGNames;
155 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
157 bool isBackForwardLoadType(FrameLoadType type)
160 case FrameLoadType::Standard:
161 case FrameLoadType::Reload:
162 case FrameLoadType::ReloadFromOrigin:
163 case FrameLoadType::ReloadExpiredOnly:
164 case FrameLoadType::Same:
165 case FrameLoadType::RedirectWithLockedBackForwardList:
166 case FrameLoadType::Replace:
168 case FrameLoadType::Back:
169 case FrameLoadType::Forward:
170 case FrameLoadType::IndexedBackForward:
173 ASSERT_NOT_REACHED();
177 bool isReload(FrameLoadType type)
180 case FrameLoadType::Reload:
181 case FrameLoadType::ReloadFromOrigin:
182 case FrameLoadType::ReloadExpiredOnly:
184 case FrameLoadType::Standard:
185 case FrameLoadType::Same:
186 case FrameLoadType::RedirectWithLockedBackForwardList:
187 case FrameLoadType::Replace:
188 case FrameLoadType::Back:
189 case FrameLoadType::Forward:
190 case FrameLoadType::IndexedBackForward:
193 ASSERT_NOT_REACHED();
197 // This is not in the FrameLoader class to emphasize that it does not depend on
198 // private FrameLoader data, and to avoid increasing the number of public functions
199 // with access to private data. Since only this .cpp file needs it, making it
200 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
203 static bool isDocumentSandboxed(Frame& frame, SandboxFlags mask)
205 return frame.document() && frame.document()->isSandboxed(mask);
208 struct ForbidPromptsScope {
209 ForbidPromptsScope(Page* page) : m_page(page)
213 m_page->forbidPrompts();
216 ~ForbidPromptsScope()
220 m_page->allowPrompts();
226 class FrameLoader::FrameProgressTracker {
227 WTF_MAKE_FAST_ALLOCATED;
229 explicit FrameProgressTracker(Frame& frame)
231 , m_inProgress(false)
235 ~FrameProgressTracker()
237 if (m_inProgress && m_frame.page())
238 m_frame.page()->progress().progressCompleted(m_frame);
241 void progressStarted()
243 ASSERT(m_frame.page());
245 m_frame.page()->progress().progressStarted(m_frame);
249 void progressCompleted()
251 ASSERT(m_inProgress);
252 ASSERT(m_frame.page());
253 m_inProgress = false;
254 m_frame.page()->progress().progressCompleted(m_frame);
256 if (auto pageID = m_frame.loader().client().pageID())
257 platformStrategies()->loaderStrategy()->pageLoadCompleted(pageID.value());
265 FrameLoader::FrameLoader(Frame& frame, FrameLoaderClient& client)
268 , m_policyChecker(std::make_unique<PolicyChecker>(frame))
269 , m_history(std::make_unique<HistoryController>(frame))
271 , m_subframeLoader(std::make_unique<SubframeLoader>(frame))
272 , m_mixedContentChecker(frame)
273 , m_state(FrameStateProvisional)
274 , m_loadType(FrameLoadType::Standard)
275 , m_quickRedirectComing(false)
276 , m_sentRedirectNotification(false)
277 , m_inStopAllLoaders(false)
278 , m_isExecutingJavaScriptFormAction(false)
279 , m_didCallImplicitClose(true)
280 , m_wasUnloadEventEmitted(false)
281 , m_isComplete(false)
282 , m_needsClear(false)
283 , m_checkTimer(*this, &FrameLoader::checkTimerFired)
284 , m_shouldCallCheckCompleted(false)
285 , m_shouldCallCheckLoadComplete(false)
287 , m_loadingFromCachedPage(false)
288 , m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
289 , m_loadsSynchronously(false)
290 , m_forcedSandboxFlags(SandboxNone)
294 FrameLoader::~FrameLoader()
298 for (auto& frame : m_openedFrames)
299 frame->loader().m_opener = nullptr;
301 m_client.frameLoaderDestroyed();
303 if (m_networkingContext)
304 m_networkingContext->invalidate();
307 void FrameLoader::init()
309 // This somewhat odd set of steps gives the frame an initial empty document.
310 setPolicyDocumentLoader(m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData()).ptr());
311 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
312 m_provisionalDocumentLoader->startLoadingMainResource(ShouldContinue::Yes);
314 Ref<Frame> protect(m_frame);
315 m_frame.document()->cancelParsing();
316 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
318 m_networkingContext = m_client.createNetworkingContext();
319 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
322 void FrameLoader::initForSynthesizedDocument(const URL&)
324 // FIXME: We need to initialize the document URL to the specified URL. Currently the URL is empty and hence
325 // FrameLoader::checkCompleted() will overwrite the URL of the document to be activeDocumentLoader()->documentURL().
327 auto loader = m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData());
328 loader->attachToFrame(m_frame);
329 loader->setResponse(ResourceResponse(URL(), "text/html"_s, 0, String()));
330 loader->setCommitted(true);
331 setDocumentLoader(loader.ptr());
333 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
334 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
335 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
336 m_client.transitionToCommittedForNewPage();
338 m_didCallImplicitClose = true;
340 m_state = FrameStateComplete;
343 m_networkingContext = m_client.createNetworkingContext();
344 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
347 void FrameLoader::setDefersLoading(bool defers)
349 if (m_documentLoader)
350 m_documentLoader->setDefersLoading(defers);
351 if (m_provisionalDocumentLoader)
352 m_provisionalDocumentLoader->setDefersLoading(defers);
353 if (m_policyDocumentLoader)
354 m_policyDocumentLoader->setDefersLoading(defers);
355 history().setDefersLoading(defers);
358 m_frame.navigationScheduler().startTimer();
359 startCheckCompleteTimer();
363 void FrameLoader::checkContentPolicy(const ResourceResponse& response, ContentPolicyDecisionFunction&& function)
365 if (!activeDocumentLoader()) {
366 // Load was cancelled
367 function(PolicyAction::Ignore);
371 client().dispatchDecidePolicyForResponse(response, activeDocumentLoader()->request(), WTFMove(function));
374 void FrameLoader::changeLocation(FrameLoadRequest&& request)
376 urlSelected(WTFMove(request), nullptr);
379 void FrameLoader::urlSelected(const URL& url, const String& passedTarget, Event* triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy, std::optional<NewFrameOpenerPolicy> openerPolicy, const AtomicString& downloadAttribute, const SystemPreviewInfo& systemPreviewInfo)
381 auto* frame = lexicalFrameFromCommonVM();
382 auto initiatedByMainFrame = frame && frame->isMainFrame() ? InitiatedByMainFrame::Yes : InitiatedByMainFrame::Unknown;
384 NewFrameOpenerPolicy newFrameOpenerPolicy = openerPolicy.value_or(shouldSendReferrer == NeverSendReferrer ? NewFrameOpenerPolicy::Suppress : NewFrameOpenerPolicy::Allow);
385 urlSelected(FrameLoadRequest(*m_frame.document(), m_frame.document()->securityOrigin(), { url }, passedTarget, lockHistory, lockBackForwardList, shouldSendReferrer, AllowNavigationToInvalidURL::Yes, newFrameOpenerPolicy, shouldOpenExternalURLsPolicy, initiatedByMainFrame, DoNotReplaceDocumentIfJavaScriptURL, downloadAttribute, systemPreviewInfo), triggeringEvent);
388 void FrameLoader::urlSelected(FrameLoadRequest&& frameRequest, Event* triggeringEvent)
390 Ref<Frame> protect(m_frame);
392 if (m_frame.script().executeIfJavaScriptURL(frameRequest.resourceRequest().url(), frameRequest.shouldReplaceDocumentIfJavaScriptURL()))
395 if (frameRequest.frameName().isEmpty())
396 frameRequest.setFrameName(m_frame.document()->baseTarget());
398 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
399 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(frameRequest.resourceRequest(), ContentSecurityPolicy::InsecureRequestType::Navigation);
401 loadFrameRequest(WTFMove(frameRequest), triggeringEvent, { });
404 void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
406 ASSERT(submission->method() == FormSubmission::Method::Post || submission->method() == FormSubmission::Method::Get);
408 // FIXME: Find a good spot for these.
409 ASSERT(!submission->state().sourceDocument().frame() || submission->state().sourceDocument().frame() == &m_frame);
414 if (submission->action().isEmpty())
417 if (isDocumentSandboxed(m_frame, SandboxForms)) {
418 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
419 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.");
423 if (protocolIsJavaScript(submission->action())) {
424 if (!m_frame.document()->contentSecurityPolicy()->allowFormAction(URL(submission->action())))
426 m_isExecutingJavaScriptFormAction = true;
427 Ref<Frame> protect(m_frame);
428 m_frame.script().executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
429 m_isExecutingJavaScriptFormAction = false;
433 Frame* targetFrame = findFrameForNavigation(submission->target(), &submission->state().sourceDocument());
435 if (!DOMWindow::allowPopUp(m_frame) && !UserGestureIndicator::processingUserGesture())
438 // FIXME: targetFrame can be null for two distinct reasons:
439 // 1. The frame was not found by name, so we should try opening a new window.
440 // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
441 // Continuing form submission makes no sense in the latter case.
442 // There is a repeat check after timer fires, so this is not a correctness issue.
444 targetFrame = &m_frame;
446 submission->clearTarget();
448 if (!targetFrame->page())
451 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
453 // We do not want to submit more than one form from the same page, nor do we want to submit a single
454 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
455 // The flag is reset in each time we start dispatching a new mouse or key down event, and
456 // also in setView since this part may get reused for a page from the back/forward cache.
457 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
459 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
460 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
461 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
463 if (m_frame.tree().isDescendantOf(targetFrame)) {
464 if (m_submittedFormURL == submission->requestURL())
466 m_submittedFormURL = submission->requestURL();
469 submission->data().generateFiles(m_frame.document());
470 submission->setReferrer(outgoingReferrer());
471 submission->setOrigin(outgoingOrigin());
473 targetFrame->navigationScheduler().scheduleFormSubmission(WTFMove(submission));
476 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
478 if (m_frame.document() && m_frame.document()->parser())
479 m_frame.document()->parser()->stopParsing();
481 if (unloadEventPolicy != UnloadEventPolicyNone)
482 dispatchUnloadEvents(unloadEventPolicy);
484 m_isComplete = true; // to avoid calling completed() in finishedParsing()
485 m_didCallImplicitClose = true; // don't want that one either
487 if (m_frame.document() && m_frame.document()->parsing()) {
489 m_frame.document()->setParsing(false);
492 if (auto* document = m_frame.document()) {
493 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
494 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
495 document->setReadyState(Document::Complete);
497 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
498 DatabaseManager::singleton().stopDatabases(*document, nullptr);
501 policyChecker().stopCheck();
503 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
504 m_frame.navigationScheduler().cancel();
507 void FrameLoader::stop()
509 // http://bugs.webkit.org/show_bug.cgi?id=10854
510 // The frame's last ref may be removed and it will be deleted by checkCompleted().
511 Ref<Frame> protect(m_frame);
513 if (DocumentParser* parser = m_frame.document()->parser()) {
514 parser->stopParsing();
519 void FrameLoader::willTransitionToCommitted()
521 // This function is called when a frame is still fully in place (not cached, not detached), but will be replaced.
523 if (m_frame.editor().hasComposition()) {
524 // The text was already present in DOM, so it's better to confirm than to cancel the composition.
525 m_frame.editor().confirmComposition();
526 if (EditorClient* editorClient = m_frame.editor().client()) {
527 editorClient->respondToChangedSelection(&m_frame);
528 editorClient->discardedComposition(&m_frame);
533 bool FrameLoader::closeURL()
535 history().saveDocumentState();
537 Document* currentDocument = m_frame.document();
538 UnloadEventPolicy unloadEventPolicy;
539 if (m_frame.page() && m_frame.page()->chrome().client().isSVGImageChromeClient()) {
540 // If this is the SVGDocument of an SVGImage, no need to dispatch events or recalcStyle.
541 unloadEventPolicy = UnloadEventPolicyNone;
543 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
544 unloadEventPolicy = currentDocument && currentDocument->pageCacheState() == Document::NotInPageCache ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly;
547 stopLoading(unloadEventPolicy);
549 m_frame.editor().clearUndoRedoOperations();
553 bool FrameLoader::didOpenURL()
555 if (m_frame.navigationScheduler().redirectScheduledDuringLoad()) {
556 // A redirect was scheduled before the document was created.
557 // This can happen when one frame changes another frame's location.
561 m_frame.navigationScheduler().cancel();
562 m_frame.editor().clearLastEditCommand();
564 m_isComplete = false;
565 m_didCallImplicitClose = false;
567 // If we are still in the process of initializing an empty document then
568 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
569 // since it may cause clients to attempt to render the frame.
570 if (!m_stateMachine.creatingInitialEmptyDocument()) {
571 DOMWindow* window = m_frame.document()->domWindow();
572 window->setStatus(String());
573 window->setDefaultStatus(String());
581 void FrameLoader::didExplicitOpen()
583 m_isComplete = false;
584 m_didCallImplicitClose = false;
586 // Calling document.open counts as committing the first real document load.
587 if (!m_stateMachine.committedFirstRealDocumentLoad())
588 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
590 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
591 // from a subsequent window.document.open / window.document.write call.
592 // Canceling redirection here works for all cases because document.open
593 // implicitly precedes document.write.
594 m_frame.navigationScheduler().cancel();
598 void FrameLoader::cancelAndClear()
600 m_frame.navigationScheduler().cancel();
605 clear(m_frame.document(), false);
606 m_frame.script().updatePlatformScriptObjects();
609 static inline bool shouldClearWindowName(const Frame& frame, const Document& newDocument)
611 if (!frame.isMainFrame())
614 if (frame.loader().opener())
617 return !newDocument.securityOrigin().isSameOriginAs(frame.document()->securityOrigin());
620 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
622 m_frame.editor().clear();
626 m_needsClear = false;
628 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
629 m_frame.document()->cancelParsing();
630 m_frame.document()->stopActiveDOMObjects();
631 bool hadLivingRenderTree = m_frame.document()->hasLivingRenderTree();
632 m_frame.document()->prepareForDestruction();
633 if (hadLivingRenderTree)
634 m_frame.document()->removeFocusedNodeOfSubtree(*m_frame.document());
637 // Do this after detaching the document so that the unload event works.
638 if (clearWindowProperties) {
639 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame.document()->domWindow());
640 m_frame.document()->domWindow()->resetUnlessSuspendedForDocumentSuspension();
641 m_frame.windowProxy().clearJSWindowProxiesNotMatchingDOMWindow(newDocument->domWindow(), m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache);
643 if (shouldClearWindowName(m_frame, *newDocument))
644 m_frame.tree().setName(nullAtom());
647 m_frame.selection().prepareForDestruction();
648 m_frame.eventHandler().clear();
650 if (clearFrameView && m_frame.view())
651 m_frame.view()->clear();
653 // Do not drop the document before the ScriptController and view are cleared
654 // as some destructors might still try to access the document.
655 m_frame.setDocument(nullptr);
657 subframeLoader().clear();
659 if (clearWindowProperties)
660 m_frame.windowProxy().setDOMWindow(newDocument->domWindow());
662 if (clearScriptObjects)
663 m_frame.script().clearScriptObjects();
665 m_frame.script().enableEval();
667 m_frame.navigationScheduler().clear();
670 m_shouldCallCheckCompleted = false;
671 m_shouldCallCheckLoadComplete = false;
673 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
674 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
677 void FrameLoader::receivedFirstData()
679 dispatchDidCommitLoad(std::nullopt);
680 dispatchDidClearWindowObjectsInAllWorlds();
681 dispatchGlobalObjectAvailableInAllWorlds();
683 if (!m_documentLoader)
686 auto& documentLoader = *m_documentLoader;
687 auto& title = documentLoader.title();
688 if (!title.string.isNull())
689 m_client.dispatchDidReceiveTitle(title);
691 ASSERT(m_frame.document());
692 auto& document = *m_frame.document();
694 LinkLoader::loadLinksFromHeader(documentLoader.response().httpHeaderField(HTTPHeaderName::Link), document.url(), document, LinkLoader::MediaAttributeCheck::MediaAttributeEmpty);
698 if (!parseHTTPRefresh(documentLoader.response().httpHeaderField(HTTPHeaderName::Refresh), delay, urlString))
700 auto completedURL = urlString.isEmpty() ? document.url() : document.completeURL(urlString);
701 if (!protocolIsJavaScript(completedURL))
702 m_frame.navigationScheduler().scheduleRedirect(document, delay, completedURL);
704 auto message = "Refused to refresh " + document.url().stringCenterEllipsizedToLength() + " to a javascript: URL";
705 document.addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
709 void FrameLoader::setOutgoingReferrer(const URL& url)
711 m_outgoingReferrer = url.strippedForUseAsReferrer();
714 void FrameLoader::didBeginDocument(bool dispatch)
717 m_isComplete = false;
718 m_didCallImplicitClose = false;
719 m_frame.document()->setReadyState(Document::Loading);
721 if (m_pendingStateObject) {
722 m_frame.document()->statePopped(*m_pendingStateObject);
723 m_pendingStateObject = nullptr;
727 dispatchDidClearWindowObjectsInAllWorlds();
729 updateFirstPartyForCookies();
730 m_frame.document()->initContentSecurityPolicy();
732 const Settings& settings = m_frame.settings();
733 m_frame.document()->cachedResourceLoader().setImagesEnabled(settings.areImagesEnabled());
734 m_frame.document()->cachedResourceLoader().setAutoLoadImages(settings.loadsImagesAutomatically());
736 if (m_documentLoader) {
737 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XDNSPrefetchControl);
738 if (!dnsPrefetchControl.isEmpty())
739 m_frame.document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
741 m_frame.document()->contentSecurityPolicy()->didReceiveHeaders(ContentSecurityPolicyResponseHeaders(m_documentLoader->response()), referrer(), ContentSecurityPolicy::ReportParsingErrors::No);
743 String referrerPolicy = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ReferrerPolicy);
744 if (!referrerPolicy.isNull())
745 m_frame.document()->processReferrerPolicy(referrerPolicy, ReferrerPolicySource::HTTPHeader);
747 String headerContentLanguage = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentLanguage);
748 if (!headerContentLanguage.isEmpty()) {
749 size_t commaIndex = headerContentLanguage.find(',');
750 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
751 headerContentLanguage = stripLeadingAndTrailingHTMLSpaces(headerContentLanguage);
752 if (!headerContentLanguage.isEmpty())
753 m_frame.document()->setContentLanguage(headerContentLanguage);
756 if (m_frame.settings().crossOriginWindowPolicySupportEnabled()) {
757 String crossOriginWindowPolicyHeader = m_documentLoader->response().httpHeaderField(HTTPHeaderName::CrossOriginWindowPolicy);
758 if (!crossOriginWindowPolicyHeader.isNull()) {
759 ASSERT(m_frame.window());
760 m_frame.window()->setCrossOriginWindowPolicy(parseCrossOriginWindowPolicyHeader(crossOriginWindowPolicyHeader));
765 history().restoreDocumentState();
768 void FrameLoader::finishedParsing()
770 LOG(Loading, "WebCoreLoading %s: Finished parsing", m_frame.tree().uniqueName().string().utf8().data());
772 m_frame.injectUserScripts(InjectAtDocumentEnd);
774 if (m_stateMachine.creatingInitialEmptyDocument())
777 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
778 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
779 // Null-checking the FrameView indicates whether or not we're in the destructor.
780 RefPtr<Frame> protector = m_frame.view() ? &m_frame : 0;
782 m_client.dispatchDidFinishDocumentLoad();
784 scrollToFragmentWithParentBoundary(m_frame.document()->url());
789 return; // We are being destroyed by something checkCompleted called.
791 // Check if the scrollbars are really needed for the content.
792 // If not, remove them, relayout, and repaint.
793 m_frame.view()->restoreScrollbar();
796 void FrameLoader::loadDone(LoadCompletionType type)
798 if (type == LoadCompletionType::Finish)
801 scheduleCheckCompleted();
804 void FrameLoader::subresourceLoadDone(LoadCompletionType type)
806 if (type == LoadCompletionType::Finish)
809 scheduleCheckLoadComplete();
812 bool FrameLoader::allChildrenAreComplete() const
814 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
815 if (!child->loader().m_isComplete)
821 bool FrameLoader::allAncestorsAreComplete() const
823 for (Frame* ancestor = &m_frame; ancestor; ancestor = ancestor->tree().parent()) {
824 if (!ancestor->loader().m_isComplete)
830 void FrameLoader::checkCompleted()
832 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
833 m_shouldCallCheckCompleted = false;
835 // Have we completed before?
840 // FIXME: Remove this code once https://webkit.org/b/185284 is fixed.
841 if (HTMLMediaElement::isRunningDestructor()) {
842 ASSERT_NOT_REACHED();
843 scheduleCheckCompleted();
848 // FIXME: It would be better if resource loads were kicked off after render tree update (or didn't complete synchronously).
849 // https://bugs.webkit.org/show_bug.cgi?id=171729
850 if (m_frame.document()->inRenderTreeUpdate()) {
851 scheduleCheckCompleted();
855 // Are we still parsing?
856 if (m_frame.document()->parsing())
859 // Still waiting for images/scripts?
860 if (m_frame.document()->cachedResourceLoader().requestCount())
863 // Still waiting for elements that don't go through a FrameLoader?
864 if (m_frame.document()->isDelayingLoadEvent())
867 auto* scriptableParser = m_frame.document()->scriptableDocumentParser();
868 if (scriptableParser && scriptableParser->hasScriptsWaitingForStylesheets())
871 // Any frame that hasn't completed yet?
872 if (!allChildrenAreComplete())
875 // Important not to protect earlier in this function, because earlier parts
876 // of this function can be called in the frame's destructor, and it's not legal
877 // to ref an object while it's being destroyed.
878 Ref<Frame> protect(m_frame);
882 m_requestedHistoryItem = nullptr;
883 m_frame.document()->setReadyState(Document::Complete);
886 if (m_frame.document()->url().isEmpty()) {
887 // We need to update the document URL of a PDF document to be non-empty so that both back/forward history navigation
888 // between PDF pages and fragment navigation works. See <rdar://problem/9544769> for more details.
889 // FIXME: Is there a better place for this code, say DocumentLoader? Also, we should explicitly only update the URL
890 // of the document when it's a PDFDocument object instead of assuming that a Document object with an empty URL is a PDFDocument.
891 // FIXME: This code is incorrect for a synthesized document (which also has an empty URL). The URL for a synthesized
892 // document should be the URL specified to FrameLoader::initForSynthesizedDocument().
893 m_frame.document()->setURL(activeDocumentLoader()->documentURL());
897 checkCallImplicitClose(); // if we didn't do it before
899 m_frame.navigationScheduler().startTimer();
906 void FrameLoader::checkTimerFired()
908 checkCompletenessNow();
911 void FrameLoader::checkCompletenessNow()
913 Ref<Frame> protect(m_frame);
915 if (Page* page = m_frame.page()) {
916 if (page->defersLoading())
919 if (m_shouldCallCheckCompleted)
921 if (m_shouldCallCheckLoadComplete)
925 void FrameLoader::startCheckCompleteTimer()
927 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
929 if (m_checkTimer.isActive())
931 m_checkTimer.startOneShot(0_s);
934 void FrameLoader::scheduleCheckCompleted()
936 m_shouldCallCheckCompleted = true;
937 startCheckCompleteTimer();
940 void FrameLoader::scheduleCheckLoadComplete()
942 m_shouldCallCheckLoadComplete = true;
943 startCheckCompleteTimer();
946 void FrameLoader::checkCallImplicitClose()
948 if (m_didCallImplicitClose || m_frame.document()->parsing() || m_frame.document()->isDelayingLoadEvent())
951 if (!allChildrenAreComplete())
952 return; // still got a frame running -> too early
954 m_didCallImplicitClose = true;
955 m_wasUnloadEventEmitted = false;
956 m_frame.document()->implicitClose();
959 void FrameLoader::loadURLIntoChildFrame(const URL& url, const String& referer, Frame* childFrame)
963 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
964 if (auto activeLoader = activeDocumentLoader()) {
965 if (auto subframeArchive = activeLoader->popArchiveForSubframe(childFrame->tree().uniqueName(), url)) {
966 childFrame->loader().loadArchive(RefPtr<Archive> { subframeArchive }.releaseNonNull());
972 // If we're moving in the back/forward list, we might want to replace the content
973 // of this child frame with whatever was there at that point.
974 auto* parentItem = history().currentItem();
975 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType()) && !m_frame.document()->loadEventFinished()) {
976 if (auto* childItem = parentItem->childItemWithTarget(childFrame->tree().uniqueName())) {
977 childFrame->loader().m_requestedHistoryItem = childItem;
978 childFrame->loader().loadDifferentDocumentItem(*childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem, ShouldTreatAsContinuingLoad::No);
983 auto* lexicalFrame = lexicalFrameFromCommonVM();
984 auto initiatedByMainFrame = lexicalFrame && lexicalFrame->isMainFrame() ? InitiatedByMainFrame::Yes : InitiatedByMainFrame::Unknown;
986 FrameLoadRequest frameLoadRequest { *m_frame.document(), m_frame.document()->securityOrigin(), { url }, "_self"_s, LockHistory::No, LockBackForwardList::Yes, ShouldSendReferrer::MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress, ShouldOpenExternalURLsPolicy::ShouldNotAllow, initiatedByMainFrame };
987 childFrame->loader().loadURL(WTFMove(frameLoadRequest), referer, FrameLoadType::RedirectWithLockedBackForwardList, nullptr, { }, [] { });
990 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
992 void FrameLoader::loadArchive(Ref<Archive>&& archive)
994 ArchiveResource* mainResource = archive->mainResource();
995 ASSERT(mainResource);
999 ResourceResponse response(URL(), mainResource->mimeType(), mainResource->data().size(), mainResource->textEncoding());
1000 SubstituteData substituteData(&mainResource->data(), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1002 ResourceRequest request(mainResource->url());
1004 auto documentLoader = m_client.createDocumentLoader(request, substituteData);
1005 documentLoader->setArchive(WTFMove(archive));
1006 load(documentLoader.ptr());
1009 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
1011 String FrameLoader::outgoingReferrer() const
1013 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
1014 // for why we walk the parent chain for srcdoc documents.
1015 Frame* frame = &m_frame;
1016 while (frame && frame->document()->isSrcdocDocument()) {
1017 frame = frame->tree().parent();
1018 // Srcdoc documents cannot be top-level documents, by definition,
1019 // because they need to be contained in iframes with the srcdoc.
1023 return emptyString();
1024 return frame->loader().m_outgoingReferrer;
1027 String FrameLoader::outgoingOrigin() const
1029 return m_frame.document()->securityOrigin().toString();
1032 bool FrameLoader::checkIfFormActionAllowedByCSP(const URL& url, bool didReceiveRedirectResponse) const
1034 if (m_submittedFormURL.isEmpty())
1037 auto redirectResponseReceived = didReceiveRedirectResponse ? ContentSecurityPolicy::RedirectResponseReceived::Yes : ContentSecurityPolicy::RedirectResponseReceived::No;
1038 return m_frame.document()->contentSecurityPolicy()->allowFormAction(url, redirectResponseReceived);
1041 Frame* FrameLoader::opener()
1046 void FrameLoader::setOpener(Frame* opener)
1048 if (m_opener && !opener)
1049 m_client.didDisownOpener();
1052 // When setOpener is called in ~FrameLoader, opener's m_frameLoader is already cleared.
1053 auto& openerFrameLoader = m_opener == &m_frame ? *this : m_opener->loader();
1054 openerFrameLoader.m_openedFrames.remove(&m_frame);
1057 opener->loader().m_openedFrames.add(&m_frame);
1060 if (m_frame.document())
1061 m_frame.document()->initSecurityContext();
1064 // FIXME: This does not belong in FrameLoader!
1065 void FrameLoader::handleFallbackContent()
1067 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
1068 if (!is<HTMLObjectElement>(owner))
1070 downcast<HTMLObjectElement>(*owner).renderFallbackContent();
1073 void FrameLoader::provisionalLoadStarted()
1075 if (m_stateMachine.firstLayoutDone())
1076 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1077 m_frame.navigationScheduler().cancel(true);
1078 m_client.provisionalLoadStarted();
1080 if (m_frame.isMainFrame()) {
1081 tracePoint(MainResourceLoadDidStartProvisional);
1083 if (auto* page = m_frame.page())
1084 page->didStartProvisionalLoad();
1088 void FrameLoader::resetMultipleFormSubmissionProtection()
1090 m_submittedFormURL = URL();
1093 void FrameLoader::updateFirstPartyForCookies()
1095 if (m_frame.tree().parent())
1096 setFirstPartyForCookies(m_frame.tree().parent()->document()->firstPartyForCookies());
1098 setFirstPartyForCookies(m_frame.document()->url());
1101 void FrameLoader::setFirstPartyForCookies(const URL& url)
1103 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
1104 frame->document()->setFirstPartyForCookies(url);
1106 String registrableDomain = ResourceRequest::partitionName(url.host().toString());
1107 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame)) {
1108 if (SecurityPolicy::shouldInheritSecurityOriginFromOwner(frame->document()->url()) || registrableDomainsAreEqual(frame->document()->url(), registrableDomain))
1109 frame->document()->setFirstPartyForSameSiteCookies(url);
1113 // This does the same kind of work that didOpenURL does, except it relies on the fact
1114 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1115 void FrameLoader::loadInSameDocument(const URL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1117 // If we have a state object, we cannot also be a new navigation.
1118 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1120 // Update the data source's request with the new URL to fake the URL change
1121 URL oldURL = m_frame.document()->url();
1122 m_frame.document()->setURL(url);
1123 setOutgoingReferrer(url);
1124 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1125 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1126 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1127 // based on the current request. Must also happen before we openURL and displace the
1128 // scroll position, since adding the BF item will save away scroll state.
1130 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1131 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1132 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1133 // though its load is not yet done. I think this all works out OK, for one because
1134 // we have already saved away the scroll and doc state for the long slow load,
1135 // but it's not an obvious case.
1137 history().updateBackForwardListForFragmentScroll();
1140 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1142 history().updateForSameDocumentNavigation();
1144 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1146 m_frame.eventHandler().stopAutoscrollTimer();
1148 // It's important to model this as a load that starts and immediately finishes.
1149 // Otherwise, the parent frame may think we never finished loading.
1152 // We need to scroll to the fragment whether or not a hash change occurred, since
1153 // the user might have scrolled since the previous navigation.
1154 scrollToFragmentWithParentBoundary(url, isNewNavigation);
1156 m_isComplete = false;
1159 if (isNewNavigation) {
1160 // This will clear previousItem from the rest of the frame tree that didn't
1161 // doing any loading. We need to make a pass on this now, since for fragment
1162 // navigation we'll not go through a real load and reach Completed state.
1163 checkLoadComplete();
1166 m_client.dispatchDidNavigateWithinPage();
1168 m_frame.document()->statePopped(stateObject ? Ref<SerializedScriptValue> { *stateObject } : SerializedScriptValue::nullValue());
1169 m_client.dispatchDidPopStateWithinPage();
1172 m_frame.document()->enqueueHashchangeEvent(oldURL, url);
1173 m_client.dispatchDidChangeLocationWithinPage();
1176 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1177 m_client.didFinishLoad();
1180 bool FrameLoader::isComplete() const
1182 return m_isComplete;
1185 void FrameLoader::completed()
1187 Ref<Frame> protect(m_frame);
1189 for (Frame* descendant = m_frame.tree().traverseNext(&m_frame); descendant; descendant = descendant->tree().traverseNext(&m_frame))
1190 descendant->navigationScheduler().startTimer();
1192 if (Frame* parent = m_frame.tree().parent())
1193 parent->loader().checkCompleted();
1196 m_frame.view()->maintainScrollPositionAtAnchor(nullptr);
1199 void FrameLoader::started()
1201 for (Frame* frame = &m_frame; frame; frame = frame->tree().parent())
1202 frame->loader().m_isComplete = false;
1205 void FrameLoader::prepareForLoadStart()
1207 RELEASE_LOG_IF_ALLOWED("prepareForLoadStart: Starting frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1209 m_progressTracker->progressStarted();
1210 m_client.dispatchDidStartProvisionalLoad();
1212 if (AXObjectCache::accessibilityEnabled()) {
1213 if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache()) {
1214 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadType::Reload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1215 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
1220 void FrameLoader::setupForReplace()
1222 m_client.revertToProvisionalState(m_documentLoader.get());
1223 setState(FrameStateProvisional);
1224 m_provisionalDocumentLoader = m_documentLoader;
1225 m_documentLoader = nullptr;
1229 void FrameLoader::loadFrameRequest(FrameLoadRequest&& request, Event* event, RefPtr<FormState>&& formState)
1231 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1232 auto protectFrame = makeRef(m_frame);
1234 URL url = request.resourceRequest().url();
1236 ASSERT(m_frame.document());
1237 if (!request.requesterSecurityOrigin().canDisplay(url)) {
1238 reportLocalLoadFailed(&m_frame, url.stringCenterEllipsizedToLength());
1242 String argsReferrer = request.resourceRequest().httpReferrer();
1243 if (argsReferrer.isEmpty())
1244 argsReferrer = outgoingReferrer();
1246 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), url, argsReferrer);
1247 if (request.shouldSendReferrer() == NeverSendReferrer)
1248 referrer = String();
1250 FrameLoadType loadType;
1251 if (request.resourceRequest().cachePolicy() == ResourceRequestCachePolicy::ReloadIgnoringCacheData)
1252 loadType = FrameLoadType::Reload;
1253 else if (request.lockBackForwardList() == LockBackForwardList::Yes)
1254 loadType = FrameLoadType::RedirectWithLockedBackForwardList;
1256 loadType = FrameLoadType::Standard;
1258 auto completionHandler = [this, protectedFrame = makeRef(m_frame), formState = makeWeakPtr(formState.get()), frameName = request.frameName()] {
1259 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1260 // load if frame names have changed.
1261 Frame* sourceFrame = formState ? formState->sourceDocument().frame() : &m_frame;
1263 sourceFrame = &m_frame;
1264 Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(frameName);
1265 if (targetFrame && targetFrame != sourceFrame) {
1266 if (Page* page = targetFrame->page())
1267 page->chrome().focus();
1271 if (request.resourceRequest().httpMethod() == "POST")
1272 loadPostRequest(WTFMove(request), referrer, loadType, event, WTFMove(formState), WTFMove(completionHandler));
1274 loadURL(WTFMove(request), referrer, loadType, event, WTFMove(formState), WTFMove(completionHandler));
1277 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& currentFrame, InitiatedByMainFrame initiatedByMainFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1279 if (UserGestureIndicator::processingUserGesture())
1280 return ShouldOpenExternalURLsPolicy::ShouldAllow;
1282 if (initiatedByMainFrame == InitiatedByMainFrame::Yes)
1283 return propagatedPolicy;
1285 if (!currentFrame.isMainFrame())
1286 return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
1288 return propagatedPolicy;
1291 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& currentFrame, const FrameLoadRequest& frameLoadRequest)
1293 return shouldOpenExternalURLsPolicyToApply(currentFrame, frameLoadRequest.initiatedByMainFrame(), frameLoadRequest.shouldOpenExternalURLsPolicy());
1296 static void applyShouldOpenExternalURLsPolicyToNewDocumentLoader(Frame& frame, DocumentLoader& documentLoader, InitiatedByMainFrame initiatedByMainFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1298 documentLoader.setShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(frame, initiatedByMainFrame, propagatedPolicy));
1301 static void applyShouldOpenExternalURLsPolicyToNewDocumentLoader(Frame& frame, DocumentLoader& documentLoader, const FrameLoadRequest& frameLoadRequest)
1303 documentLoader.setShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(frame, frameLoadRequest));
1306 bool FrameLoader::isNavigationAllowed() const
1308 return m_pageDismissalEventBeingDispatched == PageDismissalType::None && NavigationDisabler::isNavigationAllowed(m_frame);
1311 bool FrameLoader::isStopLoadingAllowed() const
1313 return m_pageDismissalEventBeingDispatched == PageDismissalType::None;
1316 void FrameLoader::loadURL(FrameLoadRequest&& frameLoadRequest, const String& referrer, FrameLoadType newLoadType, Event* event, RefPtr<FormState>&& formState, CompletionHandler<void()>&& completionHandler)
1318 CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
1319 if (m_inStopAllLoaders || m_inClearProvisionalLoadForPolicyCheck)
1322 Ref<Frame> protect(m_frame);
1324 String frameName = frameLoadRequest.frameName();
1325 AllowNavigationToInvalidURL allowNavigationToInvalidURL = frameLoadRequest.allowNavigationToInvalidURL();
1326 NewFrameOpenerPolicy openerPolicy = frameLoadRequest.newFrameOpenerPolicy();
1327 LockHistory lockHistory = frameLoadRequest.lockHistory();
1328 bool isFormSubmission = formState;
1330 const URL& newURL = frameLoadRequest.resourceRequest().url();
1331 ResourceRequest request(newURL);
1332 if (!referrer.isEmpty()) {
1333 request.setHTTPReferrer(referrer);
1334 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1335 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1337 if (&m_frame.tree().top() != &m_frame)
1338 request.setDomainForCachePartition(m_frame.tree().top().document()->domainForCachePartition());
1340 addExtraFieldsToRequest(request, newLoadType, true);
1341 if (isReload(newLoadType))
1342 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1344 ASSERT(newLoadType != FrameLoadType::Same);
1346 // The search for a target frame is done earlier in the case of form submission.
1347 Frame* targetFrame = isFormSubmission ? nullptr : findFrameForNavigation(frameName);
1348 if (targetFrame && targetFrame != &m_frame) {
1349 frameLoadRequest.setFrameName("_self");
1350 targetFrame->loader().loadURL(WTFMove(frameLoadRequest), referrer, newLoadType, event, WTFMove(formState), completionHandlerCaller.release());
1354 if (!isNavigationAllowed())
1357 NavigationAction action { frameLoadRequest.requester(), request, frameLoadRequest.initiatedByMainFrame(), newLoadType, isFormSubmission, event, frameLoadRequest.shouldOpenExternalURLsPolicy(), frameLoadRequest.downloadAttribute() };
1358 action.setIsCrossOriginWindowOpenNavigation(frameLoadRequest.isCrossOriginWindowOpenNavigation());
1359 action.setHasOpenedFrames(!m_openedFrames.isEmpty());
1360 if (auto* opener = this->opener()) {
1361 auto pageID = opener->loader().client().pageID();
1362 auto frameID = opener->loader().client().frameID();
1363 if (pageID && frameID)
1364 action.setOpener(std::make_pair(*pageID, *frameID));
1367 if (!targetFrame && !frameName.isEmpty()) {
1368 action = action.copyWithShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(m_frame, frameLoadRequest));
1369 policyChecker().checkNewWindowPolicy(WTFMove(action), WTFMove(request), WTFMove(formState), frameName, [this, allowNavigationToInvalidURL, openerPolicy, completionHandler = completionHandlerCaller.release()] (const ResourceRequest& request, WeakPtr<FormState>&& formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue) {
1370 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
1371 completionHandler();
1376 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1378 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1379 const String& httpMethod = request.httpMethod();
1381 // Make sure to do scroll to fragment processing even if the URL is
1382 // exactly the same so pages with '#' links and DHTML side effects
1384 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1385 oldDocumentLoader->setTriggeringAction(action);
1386 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1387 policyChecker().stopCheck();
1388 policyChecker().setLoadType(newLoadType);
1389 policyChecker().checkNavigationPolicy(WTFMove(request), ResourceResponse { } /* redirectResponse */, oldDocumentLoader.get(), WTFMove(formState), [this, protectedFrame = makeRef(m_frame)] (const ResourceRequest& request, WeakPtr<FormState>&&, ShouldContinue shouldContinue) {
1390 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue == ShouldContinue::Yes);
1391 }, PolicyDecisionMode::Synchronous);
1395 // Must grab this now, since this load may stop the previous load and clear this flag.
1396 bool isRedirect = m_quickRedirectComing;
1397 #if USE(SYSTEM_PREVIEW)
1398 bool isSystemPreview = frameLoadRequest.isSystemPreview();
1399 request.setSystemPreview(isSystemPreview);
1400 if (isSystemPreview)
1401 request.setSystemPreviewRect(frameLoadRequest.systemPreviewRect());
1403 loadWithNavigationAction(request, action, lockHistory, newLoadType, WTFMove(formState), allowNavigationToInvalidURL, [this, isRedirect, sameURL, newLoadType, protectedFrame = makeRef(m_frame), completionHandler = completionHandlerCaller.release()] {
1405 m_quickRedirectComing = false;
1406 if (m_provisionalDocumentLoader)
1407 m_provisionalDocumentLoader->setIsClientRedirect(true);
1408 else if (m_policyDocumentLoader)
1409 m_policyDocumentLoader->setIsClientRedirect(true);
1410 } else if (sameURL && !isReload(newLoadType)) {
1411 // Example of this case are sites that reload the same URL with a different cookie
1412 // driving the generated content, or a master frame with links that drive a target
1413 // frame, where the user has clicked on the same link repeatedly.
1414 m_loadType = FrameLoadType::Same;
1416 completionHandler();
1420 SubstituteData FrameLoader::defaultSubstituteDataForURL(const URL& url)
1422 if (!shouldTreatURLAsSrcdocDocument(url))
1423 return SubstituteData();
1424 auto& srcdoc = m_frame.ownerElement()->attributeWithoutSynchronization(srcdocAttr);
1425 ASSERT(!srcdoc.isNull());
1426 CString encodedSrcdoc = srcdoc.string().utf8();
1428 ResourceResponse response(URL(), "text/html"_s, encodedSrcdoc.length(), "UTF-8"_s);
1429 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1432 void FrameLoader::load(FrameLoadRequest&& request)
1434 if (m_inStopAllLoaders || m_inClearProvisionalLoadForPolicyCheck)
1437 if (!request.frameName().isEmpty()) {
1438 Frame* frame = findFrameForNavigation(request.frameName());
1440 request.setShouldCheckNewWindowPolicy(false);
1441 if (&frame->loader() != this) {
1442 frame->loader().load(WTFMove(request));
1448 if (request.shouldCheckNewWindowPolicy()) {
1449 NavigationAction action { request.requester(), request.resourceRequest(), InitiatedByMainFrame::Unknown, NavigationType::Other, request.shouldOpenExternalURLsPolicy() };
1450 policyChecker().checkNewWindowPolicy(WTFMove(action), WTFMove(request.resourceRequest()), { }, request.frameName(), [this] (const ResourceRequest& request, WeakPtr<FormState>&& formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue) {
1451 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress);
1457 if (!request.hasSubstituteData())
1458 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1460 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request.resourceRequest(), request.substituteData());
1461 addSameSiteInfoToRequestIfNeeded(loader->request());
1462 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, request);
1464 SetForScope<bool> currentLoadShouldBeTreatedAsContinuingLoadGuard(m_currentLoadShouldBeTreatedAsContinuingLoad, request.shouldTreatAsContinuingLoad());
1468 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, LockHistory lockHistory, FrameLoadType type, RefPtr<FormState>&& formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL, CompletionHandler<void()>&& completionHandler)
1470 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1471 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, action.initiatedByMainFrame(), action.shouldOpenExternalURLsPolicy());
1473 if (lockHistory == LockHistory::Yes && m_documentLoader)
1474 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1476 loader->setTriggeringAction(action);
1477 if (m_documentLoader)
1478 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1480 loadWithDocumentLoader(loader.ptr(), type, WTFMove(formState), allowNavigationToInvalidURL, ShouldTreatAsContinuingLoad::No, WTFMove(completionHandler));
1483 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1485 ResourceRequest& r = newDocumentLoader->request();
1486 addExtraFieldsToMainResourceRequest(r);
1489 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1490 r.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1491 type = FrameLoadType::Same;
1492 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && isReload(m_loadType))
1494 else if (m_loadType == FrameLoadType::RedirectWithLockedBackForwardList && !newDocumentLoader->unreachableURL().isEmpty() && newDocumentLoader->substituteData().isValid())
1495 type = FrameLoadType::RedirectWithLockedBackForwardList;
1497 type = FrameLoadType::Standard;
1499 if (m_documentLoader)
1500 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1502 // When we loading alternate content for an unreachable URL that we're
1503 // visiting in the history list, we treat it as a reload so the history list
1504 // is appropriately maintained.
1506 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadType::Reload" ...
1507 // shouldn't a more explicit type of reload be defined, that means roughly
1508 // "load without affecting history" ?
1509 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1510 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1511 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1512 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1513 history().saveDocumentAndScrollState();
1515 ASSERT(type == FrameLoadType::Standard);
1516 type = FrameLoadType::Reload;
1519 loadWithDocumentLoader(newDocumentLoader, type, { }, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No, [] { });
1522 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, RefPtr<FormState>&& formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL, ShouldTreatAsContinuingLoad, CompletionHandler<void()>&& completionHandler)
1524 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1525 Ref<Frame> protect(m_frame);
1527 CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
1529 ASSERT(m_client.hasWebView());
1531 // Unfortunately the view must be non-nil, this is ultimately due
1532 // to parser requiring a FrameView. We should fix this dependency.
1534 ASSERT(m_frame.view());
1536 if (!isNavigationAllowed())
1539 if (m_frame.document())
1540 m_previousURL = m_frame.document()->url();
1542 const URL& newURL = loader->request().url();
1544 // Log main frame navigation types.
1545 if (m_frame.isMainFrame()) {
1546 if (auto* page = m_frame.page()) {
1547 page->mainFrameLoadStarted(newURL, type);
1548 page->performanceLogging().didReachPointOfInterest(PerformanceLogging::MainFrameLoadStarted);
1552 policyChecker().setLoadType(type);
1553 bool isFormSubmission = formState;
1555 const String& httpMethod = loader->request().httpMethod();
1557 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker().loadType(), newURL)) {
1558 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1559 NavigationAction action { *m_frame.document(), loader->request(), InitiatedByMainFrame::Unknown, policyChecker().loadType(), isFormSubmission };
1561 oldDocumentLoader->setTriggeringAction(action);
1562 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1563 policyChecker().stopCheck();
1564 policyChecker().checkNavigationPolicy(ResourceRequest(loader->request()), ResourceResponse { } /* redirectResponse */, oldDocumentLoader.get(), WTFMove(formState), [this, protectedFrame = makeRef(m_frame)] (const ResourceRequest& request, WeakPtr<FormState>&&, ShouldContinue shouldContinue) {
1565 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue == ShouldContinue::Yes);
1566 }, PolicyDecisionMode::Synchronous);
1570 if (Frame* parent = m_frame.tree().parent())
1571 loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
1573 policyChecker().stopCheck();
1574 setPolicyDocumentLoader(loader);
1575 if (loader->triggeringAction().isEmpty())
1576 loader->setTriggeringAction({ *m_frame.document(), loader->request(), InitiatedByMainFrame::Unknown, policyChecker().loadType(), isFormSubmission });
1578 if (Element* ownerElement = m_frame.ownerElement()) {
1579 // We skip dispatching the beforeload event if we've already
1580 // committed a real document load because the event would leak
1581 // subsequent activity by the frame which the parent frame isn't
1582 // supposed to learn. For example, if the child frame navigated to
1583 // a new URL, the parent frame shouldn't learn the URL.
1584 if (!m_stateMachine.committedFirstRealDocumentLoad()
1585 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1586 continueLoadAfterNavigationPolicy(loader->request(), formState.get(), ShouldContinue::No, allowNavigationToInvalidURL);
1591 m_frame.navigationScheduler().cancel(true);
1593 if (m_currentLoadShouldBeTreatedAsContinuingLoad) {
1594 continueLoadAfterNavigationPolicy(loader->request(), formState.get(), ShouldContinue::Yes, allowNavigationToInvalidURL);
1598 policyChecker().checkNavigationPolicy(ResourceRequest(loader->request()), ResourceResponse { } /* redirectResponse */, loader, WTFMove(formState), [this, protectedFrame = makeRef(m_frame), allowNavigationToInvalidURL, completionHandler = completionHandlerCaller.release()] (const ResourceRequest& request, WeakPtr<FormState>&& formState, ShouldContinue shouldContinue) {
1599 continueLoadAfterNavigationPolicy(request, formState.get(), shouldContinue, allowNavigationToInvalidURL);
1600 completionHandler();
1604 void FrameLoader::clearProvisionalLoadForPolicyCheck()
1606 if (!m_policyDocumentLoader || !m_provisionalDocumentLoader || m_inClearProvisionalLoadForPolicyCheck)
1609 SetForScope<bool> change(m_inClearProvisionalLoadForPolicyCheck, true);
1610 m_provisionalDocumentLoader->stopLoading();
1611 setProvisionalDocumentLoader(nullptr);
1614 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1616 ASSERT(!url.isEmpty());
1620 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to load local resource: " + url);
1623 void FrameLoader::reportBlockedPortFailed(Frame* frame, const String& url)
1625 ASSERT(!url.isEmpty());
1629 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to use restricted network port: " + url);
1632 void FrameLoader::reportAuthenticationChallengeBlocked(Frame* frame, const URL& url, const String& reason)
1637 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, makeString("Blocked ", url.stringCenterEllipsizedToLength(), " from asking for credentials because ", reason, '.'));
1640 const ResourceRequest& FrameLoader::initialRequest() const
1642 return activeDocumentLoader()->originalRequest();
1645 bool FrameLoader::willLoadMediaElementURL(URL& url)
1648 // MobileStore depends on the iOS 4.0 era client delegate method because webView:resource:willSendRequest:redirectResponse:fromDataSource
1649 // doesn't let them tell when a load request is coming from a media element. See <rdar://problem/8266916> for more details.
1650 if (IOSApplication::isMobileStore())
1651 return m_client.shouldLoadMediaElementURL(url);
1654 ResourceRequest request(url);
1656 unsigned long identifier;
1657 ResourceError error;
1658 requestFromDelegate(request, identifier, error);
1659 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String()), 0, -1, -1, error);
1661 url = request.url();
1663 return error.isNull();
1666 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1668 URL unreachableURL = docLoader->unreachableURL();
1670 if (unreachableURL.isEmpty())
1673 if (!isBackForwardLoadType(policyChecker().loadType()))
1676 // We only treat unreachableURLs specially during the delegate callbacks
1677 // for provisional load errors and navigation policy decisions. The former
1678 // case handles well-formed URLs that can't be loaded, and the latter
1679 // case handles malformed URLs and unknown schemes. Loading alternate content
1680 // at other times behaves like a standard load.
1681 if (policyChecker().delegateIsDecidingNavigationPolicy() || policyChecker().delegateIsHandlingUnimplementablePolicy())
1682 return m_policyDocumentLoader && unreachableURL == m_policyDocumentLoader->request().url();
1684 return unreachableURL == m_provisionalLoadErrorBeingHandledURL;
1687 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1689 if (!m_documentLoader)
1692 ResourceRequest request = m_documentLoader->request();
1693 URL unreachableURL = m_documentLoader->unreachableURL();
1694 if (!unreachableURL.isEmpty())
1695 request.setURL(unreachableURL);
1697 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1698 // We should ask the user for confirmation in this case.
1699 request.setCachePolicy(ResourceRequestCachePolicy::ReturnCacheDataElseLoad);
1701 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1702 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, InitiatedByMainFrame::Unknown, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1704 setPolicyDocumentLoader(loader.ptr());
1706 loader->setOverrideEncoding(encoding);
1708 loadWithDocumentLoader(loader.ptr(), FrameLoadType::Reload, { }, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No, [] { });
1711 void FrameLoader::reload(OptionSet<ReloadOption> options)
1713 if (!m_documentLoader)
1716 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1717 // Reloading in this case will lose the current contents (see 4151001).
1718 if (m_documentLoader->request().url().isEmpty())
1721 // Replace error-page URL with the URL we were trying to reach.
1722 ResourceRequest initialRequest = m_documentLoader->request();
1723 URL unreachableURL = m_documentLoader->unreachableURL();
1724 if (!unreachableURL.isEmpty())
1725 initialRequest.setURL(unreachableURL);
1727 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1728 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1729 Ref<DocumentLoader> loader = m_client.createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1730 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, InitiatedByMainFrame::Unknown, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1732 loader->setUserContentExtensionsEnabled(!options.contains(ReloadOption::DisableContentBlockers));
1734 ResourceRequest& request = loader->request();
1736 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1737 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1739 addSameSiteInfoToRequestIfNeeded(request);
1741 // If we're about to re-post, set up action so the application can warn the user.
1742 if (request.httpMethod() == "POST")
1743 loader->setTriggeringAction({ *m_frame.document(), request, InitiatedByMainFrame::Unknown, NavigationType::FormResubmitted });
1745 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1747 auto frameLoadTypeForReloadOptions = [] (auto options) {
1748 if (options & ReloadOption::FromOrigin)
1749 return FrameLoadType::ReloadFromOrigin;
1750 if (options & ReloadOption::ExpiredOnly)
1751 return FrameLoadType::ReloadExpiredOnly;
1752 return FrameLoadType::Reload;
1755 loadWithDocumentLoader(loader.ptr(), frameLoadTypeForReloadOptions(options), { }, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No, [] { });
1758 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1760 ASSERT(!m_frame.document() || m_frame.document()->pageCacheState() != Document::InPageCache);
1761 if (!isStopLoadingAllowed())
1764 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1765 if (m_inStopAllLoaders)
1768 // This method might dispatch events.
1769 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
1771 // Calling stopLoading() on the provisional document loader can blow away
1772 // the frame from underneath.
1773 Ref<Frame> protect(m_frame);
1775 m_inStopAllLoaders = true;
1777 policyChecker().stopCheck();
1779 // If no new load is in progress, we should clear the provisional item from history
1780 // before we call stopLoading.
1781 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1782 history().setProvisionalItem(nullptr);
1784 for (RefPtr<Frame> child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
1785 child->loader().stopAllLoaders(clearProvisionalItemPolicy);
1786 if (m_provisionalDocumentLoader)
1787 m_provisionalDocumentLoader->stopLoading();
1788 if (m_documentLoader)
1789 m_documentLoader->stopLoading();
1791 setProvisionalDocumentLoader(nullptr);
1793 m_inStopAllLoaders = false;
1796 void FrameLoader::stopAllLoadersAndCheckCompleteness()
1800 if (!m_checkTimer.isActive())
1803 m_checkTimer.stop();
1804 m_checkingLoadCompleteForDetachment = true;
1805 checkCompletenessNow();
1806 m_checkingLoadCompleteForDetachment = false;
1809 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1811 // Calling stopAllLoaders can cause the frame to be deallocated, including the frame loader.
1812 Ref<Frame> protectedFrame(m_frame);
1817 // Lay out immediately when stopping to immediately clear the old page if we just committed this one
1818 // but haven't laid out/painted yet.
1819 // FIXME: Is this behavior specific to iOS? Or should we expose a setting to toggle this behavior?
1820 if (m_frame.view() && !m_frame.view()->didFirstLayout())
1821 m_frame.view()->layoutContext().layout();
1824 if (deferCheckLoadComplete)
1825 scheduleCheckLoadComplete();
1826 else if (m_frame.page())
1827 checkLoadComplete();
1830 DocumentLoader* FrameLoader::activeDocumentLoader() const
1832 if (m_state == FrameStateProvisional)
1833 return m_provisionalDocumentLoader.get();
1834 return m_documentLoader.get();
1837 bool FrameLoader::isLoading() const
1839 DocumentLoader* docLoader = activeDocumentLoader();
1842 return docLoader->isLoading();
1845 bool FrameLoader::frameHasLoaded() const
1847 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1850 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1852 if (!loader && !m_documentLoader)
1855 ASSERT(loader != m_documentLoader);
1856 ASSERT(!loader || loader->frameLoader() == this);
1858 m_client.prepareForDataSourceReplacement();
1861 // detachChildren() can trigger this frame's unload event, and therefore
1862 // script can run and do just about anything. For example, an unload event that calls
1863 // document.write("") on its parent frame can lead to a recursive detachChildren()
1864 // invocation for this frame. In that case, we can end up at this point with a
1865 // loader that hasn't been deleted but has been detached from its frame. Such a
1866 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1867 // state if we try to use it.
1868 if (loader && !loader->frame())
1871 if (m_documentLoader)
1872 m_documentLoader->detachFromFrame();
1874 m_documentLoader = loader;
1877 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1879 if (m_policyDocumentLoader == loader)
1883 loader->attachToFrame(m_frame);
1884 if (m_policyDocumentLoader
1885 && m_policyDocumentLoader != m_provisionalDocumentLoader
1886 && m_policyDocumentLoader != m_documentLoader)
1887 m_policyDocumentLoader->detachFromFrame();
1889 m_policyDocumentLoader = loader;
1892 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1894 ASSERT(!loader || !m_provisionalDocumentLoader);
1895 ASSERT(!loader || loader->frameLoader() == this);
1897 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1898 m_provisionalDocumentLoader->detachFromFrame();
1900 m_provisionalDocumentLoader = loader;
1903 void FrameLoader::setState(FrameState newState)
1905 FrameState oldState = m_state;
1908 if (newState == FrameStateProvisional)
1909 provisionalLoadStarted();
1910 else if (newState == FrameStateComplete) {
1911 frameLoadCompleted();
1912 if (m_documentLoader)
1913 m_documentLoader->stopRecordingResponses();
1914 if (m_frame.isMainFrame() && oldState != newState)
1915 m_frame.page()->performanceLogging().didReachPointOfInterest(PerformanceLogging::MainFrameLoadCompleted);
1919 void FrameLoader::clearProvisionalLoad()
1921 setProvisionalDocumentLoader(nullptr);
1922 m_progressTracker->progressCompleted();
1923 setState(FrameStateComplete);
1926 void FrameLoader::commitProvisionalLoad()
1928 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1929 Ref<Frame> protect(m_frame);
1931 std::unique_ptr<CachedPage> cachedPage;
1932 if (m_loadingFromCachedPage && history().provisionalItem())
1933 cachedPage = PageCache::singleton().take(*history().provisionalItem(), m_frame.page());
1935 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s' with cached page %p", m_frame.tree().uniqueName().string().utf8().data(),
1936 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
1937 pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>", cachedPage.get());
1939 willTransitionToCommitted();
1941 if (!m_frame.tree().parent() && history().currentItem()) {
1942 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1943 // We are doing this here because we know for sure that a new page is about to be loaded.
1944 PageCache::singleton().addIfCacheable(*history().currentItem(), m_frame.page());
1946 WebCore::jettisonExpensiveObjectsOnTopLevelNavigation();
1949 if (m_loadType != FrameLoadType::Replace)
1950 closeOldDataSources();
1952 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1953 m_client.makeRepresentation(pdl.get());
1955 transitionToCommitted(cachedPage.get());
1957 if (pdl && m_documentLoader) {
1958 // Check if the destination page is allowed to access the previous page's timing information.
1959 Ref<SecurityOrigin> securityOrigin(SecurityOrigin::create(pdl->request().url()));
1960 m_documentLoader->timing().setHasSameOriginAsPreviousDocument(securityOrigin.get().canRequest(m_previousURL));
1963 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1964 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1965 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1966 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1967 if (m_sentRedirectNotification)
1968 clientRedirectCancelledOrFinished(false);
1970 if (cachedPage && cachedPage->document()) {
1972 // FIXME: CachedPage::restore() would dispatch viewport change notification. However UIKit expects load
1973 // commit to happen before any changes to viewport arguments and dealing with this there is difficult.
1974 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(true);
1976 willRestoreFromCachedPage();
1978 // Start request for the main resource and dispatch didReceiveResponse before the load is committed for
1979 // consistency with all other loads. See https://bugs.webkit.org/show_bug.cgi?id=150927.
1980 ResourceError mainResouceError;
1981 unsigned long mainResourceIdentifier;
1982 ResourceRequest mainResourceRequest(cachedPage->documentLoader()->request());
1983 requestFromDelegate(mainResourceRequest, mainResourceIdentifier, mainResouceError);
1984 notifier().dispatchDidReceiveResponse(cachedPage->documentLoader(), mainResourceIdentifier, cachedPage->documentLoader()->response());
1986 std::optional<HasInsecureContent> hasInsecureContent = cachedPage->cachedMainFrame()->hasInsecureContent();
1988 // FIXME: This API should be turned around so that we ground CachedPage into the Page.
1989 cachedPage->restore(*m_frame.page());
1991 dispatchDidCommitLoad(hasInsecureContent);
1994 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(false);
1995 m_frame.page()->chrome().dispatchViewportPropertiesDidChange(m_frame.page()->viewportArguments());
1997 m_frame.page()->chrome().dispatchDisabledAdaptationsDidChange(m_frame.page()->disabledAdaptations());
1999 auto& title = m_documentLoader->title();
2000 if (!title.string.isNull())
2001 m_client.dispatchDidReceiveTitle(title);
2003 // Send remaining notifications for the main resource.
2004 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), mainResourceIdentifier, mainResourceRequest, ResourceResponse(),
2005 nullptr, static_cast<int>(m_documentLoader->response().expectedContentLength()), 0, mainResouceError);
2011 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame.tree().uniqueName().string().utf8().data(),
2012 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
2014 if (m_loadType == FrameLoadType::Standard && m_documentLoader && m_documentLoader->isClientRedirect())
2015 history().updateForClientRedirect();
2017 if (m_loadingFromCachedPage) {
2018 // Note, didReceiveDocType is expected to be called for cached pages. See <rdar://problem/5906758> for more details.
2019 if (auto* page = m_frame.page())
2020 page->chrome().didReceiveDocType(m_frame);
2021 m_frame.document()->resume(ReasonForSuspension::PageCache);
2023 // Force a layout to update view size and thereby update scrollbars.
2025 if (!m_client.forceLayoutOnRestoreFromPageCache())
2026 m_frame.view()->forceLayout();
2028 m_frame.view()->forceLayout();
2031 // Main resource delegates were already sent, so we skip the first response here.
2032 for (unsigned i = 1; i < m_documentLoader->responses().size(); ++i) {
2033 const auto& response = m_documentLoader->responses()[i];
2034 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
2035 ResourceError error;
2036 unsigned long identifier;
2037 ResourceRequest request(response.url());
2038 requestFromDelegate(request, identifier, error);
2039 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
2040 // However, with today's computers and networking speeds, this won't happen in practice.
2041 // Could be an issue with a giant local file.
2042 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
2045 // FIXME: Why only this frame and not parent frames?
2046 checkLoadCompleteForThisFrame();
2050 void FrameLoader::transitionToCommitted(CachedPage* cachedPage)
2052 ASSERT(m_client.hasWebView());
2053 ASSERT(m_state == FrameStateProvisional);
2055 if (m_state != FrameStateProvisional)
2058 if (FrameView* view = m_frame.view()) {
2059 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
2060 scrollAnimator->cancelAnimations();
2063 m_client.setCopiesOnScroll();
2064 history().updateForCommit();
2066 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
2067 // JavaScript. If the script initiates a new load, we need to abandon the current load,
2068 // or the two will stomp each other.
2069 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
2070 if (m_documentLoader)
2072 if (pdl != m_provisionalDocumentLoader)
2075 if (m_documentLoader)
2076 m_documentLoader->stopLoadingSubresources();
2077 if (m_documentLoader)
2078 m_documentLoader->stopLoadingPlugIns();
2080 // Setting our document loader invokes the unload event handler of our child frames.
2081 // Script can do anything. If the script initiates a new load, we need to abandon the
2082 // current load or the two will stomp each other.
2083 setDocumentLoader(m_provisionalDocumentLoader.get());
2084 if (pdl != m_provisionalDocumentLoader)
2086 setProvisionalDocumentLoader(nullptr);
2088 // Nothing else can interrupt this commit - set the Provisional->Committed transition in stone
2089 setState(FrameStateCommittedPage);
2091 // Handle adding the URL to the back/forward list.
2092 DocumentLoader* dl = m_documentLoader.get();
2094 switch (m_loadType) {
2095 case FrameLoadType::Forward:
2096 case FrameLoadType::Back:
2097 case FrameLoadType::IndexedBackForward:
2098 if (m_frame.page()) {
2099 // If the first load within a frame is a navigation within a back/forward list that was attached
2100 // without any of the items being loaded then we need to update the history in a similar manner as
2101 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
2102 if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame.isMainFrame())
2103 history().updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
2105 history().updateForBackForwardNavigation();
2107 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
2108 if (history().currentItem() && !cachedPage)
2109 m_pendingStateObject = history().currentItem()->stateObject();
2111 // Create a document view for this document, or used the cached view.
2113 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
2114 ASSERT(cachedDocumentLoader);
2115 cachedDocumentLoader->attachToFrame(m_frame);
2116 m_client.transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
2118 m_client.transitionToCommittedForNewPage();
2122 case FrameLoadType::Reload:
2123 case FrameLoadType::ReloadFromOrigin:
2124 case FrameLoadType::ReloadExpiredOnly:
2125 case FrameLoadType::Same:
2126 case FrameLoadType::Replace:
2127 history().updateForReload();
2128 m_client.transitionToCommittedForNewPage();
2131 case FrameLoadType::Standard:
2132 history().updateForStandardLoad();
2134 m_frame.view()->setScrollbarsSuppressed(true);
2135 m_client.transitionToCommittedForNewPage();
2138 case FrameLoadType::RedirectWithLockedBackForwardList:
2139 history().updateForRedirectWithLockedBackForwardList();
2140 m_client.transitionToCommittedForNewPage();
2144 m_documentLoader->writer().setMIMEType(dl->responseMIMEType());
2146 // Tell the client we've committed this URL.
2147 ASSERT(m_frame.view());
2149 if (m_stateMachine.creatingInitialEmptyDocument())
2152 if (!m_stateMachine.committedFirstRealDocumentLoad())
2153 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
2156 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
2158 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
2159 // the redirect succeeded. We should either rename this API, or add a new method, like
2160 // -webView:didFinishClientRedirectForFrame:
2161 m_client.dispatchDidCancelClientRedirect();
2163 if (!cancelWithLoadInProgress)
2164 m_quickRedirectComing = false;
2166 m_sentRedirectNotification = false;
2169 void FrameLoader::clientRedirected(const URL& url, double seconds, WallTime fireDate, LockBackForwardList lockBackForwardList)
2171 m_client.dispatchWillPerformClientRedirect(url, seconds, fireDate);
2173 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
2174 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
2175 m_sentRedirectNotification = true;
2177 // If a "quick" redirect comes in, we set a special mode so we treat the next
2178 // load as part of the original navigation. If we don't have a document loader, we have
2179 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
2180 // Loads triggered by JavaScript form submissions never count as quick redirects.
2181 m_quickRedirectComing = (lockBackForwardList == LockBackForwardList::Yes || history().currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
2184 bool FrameLoader::shouldReload(const URL& currentURL, const URL& destinationURL)
2186 // This function implements the rule: "Don't reload if navigating by fragment within
2187 // the same URL, but do reload if going to a new URL or to the same URL with no
2188 // fragment identifier at all."
2189 if (!destinationURL.hasFragmentIdentifier())
2191 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
2194 void FrameLoader::closeOldDataSources()
2196 // FIXME: Is it important for this traversal to be postorder instead of preorder?
2197 // If so, add helpers for postorder traversal, and use them. If not, then lets not
2198 // use a recursive algorithm here.
2199 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
2200 child->loader().closeOldDataSources();
2202 if (m_documentLoader)
2203 m_client.dispatchWillClose();
2205 m_client.setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2208 void FrameLoader::willRestoreFromCachedPage()
2210 ASSERT(!m_frame.tree().parent());
2211 ASSERT(m_frame.page());
2212 ASSERT(m_frame.isMainFrame());
2214 m_frame.navigationScheduler().cancel();
2216 // We still have to close the previous part page.
2219 // Delete old status bar messages (if it _was_ activated on last URL).
2220 if (m_frame.script().canExecuteScripts(NotAboutToExecuteScript)) {
2221 DOMWindow* window = m_frame.document()->domWindow();
2222 window->setStatus(String());
2223 window->setDefaultStatus(String());
2227 void FrameLoader::open(CachedFrameBase& cachedFrame)
2229 m_isComplete = false;
2231 // Don't re-emit the load event.
2232 m_didCallImplicitClose = true;
2234 URL url = cachedFrame.url();
2236 // FIXME: I suspect this block of code doesn't do anything.
2237 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2241 Document* document = cachedFrame.document();
2243 ASSERT(document->domWindow());
2245 clear(document, true, true, cachedFrame.isMainFrame());
2247 document->setPageCacheState(Document::NotInPageCache);
2249 m_needsClear = true;
2250 m_isComplete = false;
2251 m_didCallImplicitClose = false;
2252 m_outgoingReferrer = url.string();
2254 FrameView* view = cachedFrame.view();
2256 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2258 view->setWasScrolledByUser(false);
2260 std::optional<IntRect> previousViewFrameRect = m_frame.view() ? m_frame.view()->frameRect() : std::optional<IntRect>(std::nullopt);
2261 m_frame.setView(view);
2263 // Use the previous ScrollView's frame rect.
2264 if (previousViewFrameRect)
2265 view->setFrameRect(previousViewFrameRect.value());
2267 m_frame.setDocument(document);
2268 document->domWindow()->resumeFromDocumentSuspension();
2270 updateFirstPartyForCookies();
2272 cachedFrame.restore();
2275 bool FrameLoader::isHostedByObjectElement() const
2277 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
2278 return owner && owner->hasTagName(objectTag);
2281 bool FrameLoader::isReplacing() const
2283 return m_loadType == FrameLoadType::Replace;
2286 void FrameLoader::setReplacing()
2288 m_loadType = FrameLoadType::Replace;
2291 bool FrameLoader::subframeIsLoading() const
2293 // It's most likely that the last added frame is the last to load so we walk backwards.
2294 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling()) {
2295 FrameLoader& childLoader = child->loader();
2296 DocumentLoader* documentLoader = childLoader.documentLoader();
2297 if (documentLoader && documentLoader->isLoadingInAPISense())
2299 documentLoader = childLoader.provisionalDocumentLoader();
2300 if (documentLoader && documentLoader->isLoadingInAPISense())
2302 documentLoader = childLoader.policyDocumentLoader();
2309 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2311 m_client.willChangeTitle(loader);
2314 FrameLoadType FrameLoader::loadType() const
2319 CachePolicy FrameLoader::subresourceCachePolicy(const URL& url) const
2321 if (Page* page = m_frame.page()) {
2322 if (page->isResourceCachingDisabled())
2323 return CachePolicyReload;
2327 return CachePolicyVerify;
2329 if (m_loadType == FrameLoadType::ReloadFromOrigin)
2330 return CachePolicyReload;
2332 if (Frame* parentFrame = m_frame.tree().parent()) {
2333 CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy(url);
2334 if (parentCachePolicy != CachePolicyVerify)
2335 return parentCachePolicy;
2338 switch (m_loadType) {
2339 case FrameLoadType::Reload:
2340 return CachePolicyRevalidate;
2341 case FrameLoadType::Back:
2342 case FrameLoadType::Forward:
2343 case FrameLoadType::IndexedBackForward:
2344 return CachePolicyHistoryBuffer;
2345 case FrameLoadType::ReloadFromOrigin:
2346 ASSERT_NOT_REACHED(); // Already handled above.
2347 return CachePolicyReload;
2348 case FrameLoadType::RedirectWithLockedBackForwardList:
2349 case FrameLoadType::Replace:
2350 case FrameLoadType::Same:
2351 case FrameLoadType::Standard:
2352 return CachePolicyVerify;
2353 case FrameLoadType::ReloadExpiredOnly:
2354 // We know about expiration for HTTP and data. Do a normal reload otherwise.
2355 if (!url.protocolIsInHTTPFamily() && !url.protocolIsData())
2356 return CachePolicyReload;
2357 return CachePolicyVerify;
2360 RELEASE_ASSERT_NOT_REACHED();
2361 return CachePolicyVerify;
2364 void FrameLoader::checkLoadCompleteForThisFrame()
2366 ASSERT(m_client.hasWebView());
2368 // FIXME: Should this check be done in checkLoadComplete instead of here?
2369 // FIXME: Why does this one check need to be repeated here, and not the many others from checkCompleted?
2370 if (m_frame.document()->isDelayingLoadEvent())
2374 case FrameStateProvisional: {
2375 // FIXME: Prohibiting any provisional load failures from being sent to clients
2376 // while handling provisional load failures is too heavy. For example, the current
2377 // load will fail to cancel another ongoing load. That might prevent clients' page
2378 // load state being handled properly.
2379 if (!m_provisionalLoadErrorBeingHandledURL.isEmpty())
2382 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2386 // If we've received any errors we may be stuck in the provisional state and actually complete.
2387 const ResourceError& error = pdl->mainDocumentError();
2391 // Check all children first.
2392 RefPtr<HistoryItem> item;
2393 if (Page* page = m_frame.page())
2394 if (isBackForwardLoadType(loadType()))
2395 // Reset the back forward list to the last committed history item at the top level.
2396 item = page->mainFrame().loader().history().currentItem();
2398 // Only reset if we aren't already going to a new provisional item.
2399 bool shouldReset = !history().provisionalItem();
2400 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2401 m_provisionalLoadErrorBeingHandledURL = m_provisionalDocumentLoader->url();
2402 m_client.dispatchDidFailProvisionalLoad(error);
2403 #if ENABLE(CONTENT_FILTERING)
2404 if (auto contentFilter = pdl->contentFilter())
2405 contentFilter->handleProvisionalLoadFailure(error);
2407 m_provisionalLoadErrorBeingHandledURL = { };
2409 ASSERT(!pdl->isLoading());
2411 // If we're in the middle of loading multipart data, we need to restore the document loader.
2412 if (isReplacing() && !m_documentLoader.get())
2413 setDocumentLoader(m_provisionalDocumentLoader.get());
2415 // Finish resetting the load state, but only if another load hasn't been started by the
2416 // delegate callback.
2417 if (pdl == m_provisionalDocumentLoader)
2418 clearProvisionalLoad();
2419 else if (activeDocumentLoader()) {
2420 URL unreachableURL = activeDocumentLoader()->unreachableURL();
2421 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2422 shouldReset = false;
2425 if (shouldReset && item)
2426 if (Page* page = m_frame.page()) {
2427 page->backForward().setCurrentItem(item.get());
2428 m_frame.loader().client().updateGlobalHistoryItemForPage();
2433 case FrameStateCommittedPage: {
2434 if (!m_documentLoader)
2436 if (m_documentLoader->isLoadingInAPISense() && !m_documentLoader->isStopping() && !m_checkingLoadCompleteForDetachment)
2439 setState(FrameStateComplete);
2441 // FIXME: Is this subsequent work important if we already navigated away?
2442 // Maybe there are bugs because of that, or extra work we can skip because
2443 // the new page is ready.
2445 m_client.forceLayoutForNonHTML();
2447 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2448 if (m_frame.page()) {
2449 if (isBackForwardLoadType(m_loadType) || isReload(m_loadType))
2450 history().restoreScrollPositionAndViewState();
2453 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2456 m_progressTracker->progressCompleted();
2457 Page* page = m_frame.page();
2459 if (m_frame.isMainFrame()) {
2460 tracePoint(MainResourceLoadDidEnd);
2461 page->didFinishLoad();
2465 const ResourceError& error = m_documentLoader->mainDocumentError();
2467 AXObjectCache::AXLoadingEvent loadingEvent;
2468 if (!error.isNull()) {
2469 RELEASE_LOG_IF_ALLOWED("checkLoadCompleteForThisFrame: Finished frame load with error (frame = %p, main = %d, isTimeout = %d, isCancellation = %d, errorCode = %d)", &m_frame, m_frame.isMainFrame(), error.isTimeout(), error.isCancellation(), error.errorCode());
2470 m_client.dispatchDidFailLoad(error);
2471 loadingEvent = AXObjectCache::AXLoadingFailed;
2473 RELEASE_LOG_IF_ALLOWED("checkLoadCompleteForThisFrame: Finished frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
2474 #if ENABLE(DATA_DETECTION)
2475 auto* document = m_frame.document();
2476 if (m_frame.settings().dataDetectorTypes() != DataDetectorTypeNone && document) {
2477 if (auto* documentElement = document->documentElement()) {
2478 RefPtr<Range> documentRange = makeRange(firstPositionInNode(documentElement), lastPositionInNode(documentElement));
2479 m_frame.setDataDetectionResults(DataDetection::detectContentInRange(documentRange, m_frame.settings().dataDetectorTypes(), m_client.dataDetectionContext()));
2480 if (m_frame.isMainFrame())
2481 m_client.dispatchDidFinishDataDetection(m_frame.dataDetectionResults());
2485 m_client.dispatchDidFinishLoad();
2486 loadingEvent = AXObjectCache::AXLoadingFinished;
2489 // Notify accessibility.
2490 if (auto* document = m_frame.document()) {
2491 if (AXObjectCache* cache = document->existingAXObjectCache())
2492 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
2495 // The above calls to dispatchDidFinishLoad() might have detached the Frame
2496 // from its Page and also might have caused Page to be deleted.
2497 // Don't assume 'page' is still available to use.
2498 if (m_frame.isMainFrame() && m_frame.page()) {
2499 ASSERT(&m_frame.page()->mainFrame() == &m_frame);
2500 m_frame.page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageLoadedKey(), emptyString(), error.isNull() ? DiagnosticLoggingResultPass : DiagnosticLoggingResultFail, ShouldSample::Yes);
2506 case FrameStateComplete:
2507 m_loadType = FrameLoadType::Standard;
2508 frameLoadCompleted();
2512 ASSERT_NOT_REACHED();
2515 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2517 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2518 // The originalURL is defined as the URL of the page where the download was initiated.
2520 auto* initiator = m_frame.document();
2522 originalURL = initiator->firstPartyForCookies();
2523 // If there is no main document URL, it means that this document is newly opened and just for download purpose.
2524 // In this case, we need to set the originalURL to this document's opener's main document URL.
2525 if (originalURL.isEmpty() && opener() && opener()->document()) {
2526 originalURL = opener()->document()->firstPartyForCookies();
2527 initiator = opener()->document();
2530 // If the originalURL is the same as the requested URL, we are processing a download
2531 // initiated directly without a page and do not need to specify the originalURL.
2532 if (originalURL == request.url())
2533 request.setFirstPartyForCookies(URL());
2535 request.setFirstPartyForCookies(originalURL);
2536 addSameSiteInfoToRequestIfNeeded(request, initiator);
2539 void FrameLoader::didReachLayoutMilestone(LayoutMilestones milestones)
2541 ASSERT(m_frame.isMainFrame());
2543 m_client.dispatchDidReachLayoutMilestone(milestones);
2546 void FrameLoader::didFirstLayout()
2549 // Only send layout-related delegate callbacks synchronously for the main frame to
2550 // avoid reentering layout for the main frame while delivering a layout-related delegate
2551 // callback for a subframe.
2552 if (&m_frame != &m_frame.page()->mainFrame())
2555 if (m_frame.page() && isBackForwardLoadType(m_loadType))
2556 history().restoreScrollPositionAndViewState();
2558 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2559 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2562 void FrameLoader::frameLoadCompleted()
2564 // Note: Can be called multiple times.
2566 m_client.frameLoadCompleted();
2568 history().updateForFrameLoadCompleted();
2570 // After a canceled provisional load, firstLayoutDone is false.
2571 // Reset it to true if we're displaying a page.
2572 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2573 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2576 void FrameLoader::detachChildren()
2578 // detachChildren() will fire the unload event in each subframe and the
2579 // HTML specification states that the parent document's ignore-opens-during-unload counter while
2580 // this event is being fired in its subframes:
2581 // https://html.spec.whatwg.org/multipage/browsers.html#unload-a-document
2582 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2584 // Any subframe inserted by unload event handlers executed in the loop below will not get unloaded
2585 // because we create a copy of the subframes list before looping. Therefore, it would be unsafe to
2586 // allow loading of subframes at this point.
2587 SubframeLoadingDisabler subframeLoadingDisabler(m_frame.document());
2589 Vector<Ref<Frame>, 16> childrenToDetach;
2590 childrenToDetach.reserveInitialCapacity(m_frame.tree().childCount());
2591 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling())
2592 childrenToDetach.uncheckedAppend(*child);
2593 for (auto& child : childrenToDetach)
2594 child->loader().detachFromParent();
2597 void FrameLoader::closeAndRemoveChild(Frame& child)
2599 child.tree().detachFromParent();
2601 child.setView(nullptr);
2602 if (child.ownerElement() && child.page())
2603 child.page()->decrementSubframeCount();
2604 child.willDetachPage();
2605 child.detachFromPage();
2607 m_frame.tree().removeChild(child);
2610 // Called every time a resource is completely loaded or an error is received.
2611 void FrameLoader::checkLoadComplete()
2613 m_shouldCallCheckLoadComplete = false;
2615 if (!m_frame.page())
2618 ASSERT(m_client.hasWebView());
2620 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2621 // is currently needed in order to null out the previous history item for all frames.
2622 Vector<Ref<Frame>, 16> frames;
2623 for (Frame* frame = &m_frame.mainFrame(); frame; frame = frame->tree().traverseNext())
2624 frames.append(*frame);
2626 // To process children before their parents, iterate the vector backwards.
2627 for (auto frame = frames.rbegin(); frame != frames.rend(); ++frame) {
2628 if ((*frame)->page())
2629 (*frame)->loader().checkLoadCompleteForThisFrame();
2633 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2636 return m_frame.document()->cachedResourceLoader().requestCount();
2639 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
2640 count += frame->document()->cachedResourceLoader().requestCount();
2644 String FrameLoader::userAgent(const URL& url) const
2646 return m_client.userAgent(url);
2649 void FrameLoader::dispatchOnloadEvents()
2651 m_client.dispatchDidDispatchOnloadEvents();
2653 if (documentLoader())
2654 documentLoader()->dispatchOnloadEvents();
2657 void FrameLoader::frameDetached()
2659 // Calling stopAllLoadersAndCheckCompleteness() can cause the frame to be deallocated, including the frame loader.
2660 Ref<Frame> protectedFrame(m_frame);
2662 if (m_checkTimer.isActive()) {
2663 m_checkTimer.stop();
2664 checkCompletenessNow();
2667 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2668 stopAllLoadersAndCheckCompleteness();
2669 m_frame.document()->stopActiveDOMObjects();
2675 void FrameLoader::detachFromParent()
2677 // Calling stopAllLoaders() can cause the frame to be deallocated, including the frame loader.
2678 Ref<Frame> protect(m_frame);
2681 history().saveScrollPositionAndViewStateToItem(history().currentItem());
2683 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2684 // stopAllLoaders() needs to be called after detachChildren() if the document is not in the page cache,
2685 // because detachedChildren() will trigger the unload event handlers of any child frames, and those event
2686 // handlers might start a new subresource load in this frame.
2690 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2692 detachViewsAndDocumentLoader();
2694 m_progressTracker = nullptr;
2696 if (Frame* parent = m_frame.tree().parent()) {
2697 parent->loader().closeAndRemoveChild(m_frame);
2698 parent->loader().scheduleCheckCompleted();
2699 parent->loader().scheduleCheckLoadComplete();
2701 m_frame.setView(nullptr);
2702 m_frame.willDetachPage();
2703 m_frame.detachFromPage();
2707 void FrameLoader::detachViewsAndDocumentLoader()
2709 m_client.detachedFromParent2();
2710 setDocumentLoader(nullptr);
2711 m_client.detachedFromParent3();
2714 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2716 addExtraFieldsToRequest(request, m_loadType, false);
2719 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2721 // FIXME: Using m_loadType seems wrong for some callers.
2722 // If we are only preparing to load the main resource, that is previous load's load type!
2723 addExtraFieldsToRequest(request, m_loadType, true);
2725 // Upgrade-Insecure-Requests should only be added to main resource requests
2726 addHTTPUpgradeInsecureRequestsIfNeeded(request);
2729 ResourceRequestCachePolicy FrameLoader::defaultRequestCachingPolicy(const ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2731 if (m_overrideCachePolicyForTesting)
2732 return m_overrideCachePolicyForTesting.value();
2734 if (isMainResource) {
2735 if (isReload(loadType) || request.isConditional())
2736 return ResourceRequestCachePolicy::ReloadIgnoringCacheData;
2738 return ResourceRequestCachePolicy::UseProtocolCachePolicy;
2741 if (request.isConditional())
2742 return ResourceRequestCachePolicy::ReloadIgnoringCacheData;
2744 if (documentLoader()->isLoadingInAPISense()) {
2745 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2746 // original request cache policy for two reasons:
2747 // 1. For POST requests, we mutate the cache policy for the main resource,
2748 // but we do not want this to apply to subresources
2749 // 2. Delegates that modify the cache policy using willSendRequest: should
2750 // not affect any other resources. Such changes need to be done
2752 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2753 // 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.
2754 // This policy is set on initial request too, but should not be inherited.
2755 return (mainDocumentOriginalCachePolicy == ResourceRequestCachePolicy::ReturnCacheDataDontLoad) ? ResourceRequestCachePolicy::ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2758 return ResourceRequestCachePolicy::UseProtocolCachePolicy;
2761 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2763 if (m_currentLoadShouldBeTreatedAsContinuingLoad)
2766 // Don't set the cookie policy URL if it's already been set.
2767 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2768 if (request.firstPartyForCookies().isEmpty()) {
2769 if (isMainResource && m_frame.isMainFrame())
2770 request.setFirstPartyForCookies(request.url());
2771 else if (Document* document = m_frame.document())
2772 request.setFirstPartyForCookies(document->firstPartyForCookies());
2775 if (request.isSameSiteUnspecified()) {
2776 auto* initiator = m_frame.document();
2777 if (isMainResource) {
2778 auto* ownerFrame = m_frame.tree().parent();
2779 if (!ownerFrame && m_stateMachine.isDisplayingInitialEmptyDocument())
2780 ownerFrame = m_opener;
2782 initiator = ownerFrame->document();
2783 ASSERT(ownerFrame || m_frame.isMainFrame());
2785 addSameSiteInfoToRequestIfNeeded(request, initiator);
2786 request.setIsTopSite(isMainResource && m_frame.isMainFrame());
2789 Page* page = frame().page();
2790 bool hasSpecificCachePolicy = request.cachePolicy() != ResourceRequestCachePolicy::UseProtocolCachePolicy;
2792 if (page && page->isResourceCachingDisabled()) {
2793 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
2794 loadType = FrameLoadType::ReloadFromOrigin;
2795 } else if (!hasSpecificCachePolicy)
2796 request.setCachePolicy(defaultRequestCachingPolicy(request, loadType, isMainResource));
2798 // The remaining modifications are only necessary for HTTP and HTTPS.
2799 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2802 if (!hasSpecificCachePolicy && request.cachePolicy() == ResourceRequestCachePolicy::ReloadIgnoringCacheData) {
2803 if (loadType == FrameLoadType::Reload)
2804 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
2805 else if (loadType == FrameLoadType::ReloadFromOrigin) {
2806 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
2807 request.setHTTPHeaderField(HTTPHeaderName::Pragma, "no-cache");
2811 if (m_overrideResourceLoadPriorityForTesting)
2812 request.setPriority(m_overrideResourceLoadPriorityForTesting.value());
2814 applyUserAgentIfNeeded(request);
2817 request.setHTTPAccept(defaultAcceptHeader);
2819 // Make sure we send the Origin header.
2820 addHTTPOriginIfNeeded(request, String());
2822 // Only set fallback array if it's still empty (later attempts may be incorrect, see bug 117818).
2823 if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
2824 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2825 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame.document()->encoding(), m_frame.settings().defaultTextEncodingName());
2829 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2831 if (!request.httpOrigin().isEmpty())
2832 return; // Request already has an Origin header.
2834 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2835 // For example, if an intranet page has a hyperlink to an external web
2836 // site, we don't want to include the Origin of the request because it
2837 // will leak the internal host name. Similar privacy concerns have lead
2838 // to the widespread suppression of the Referer header at the network
2840 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2843 // For non-GET and non-HEAD methods, always send an Origin header so the
2844 // server knows we support this feature.
2846 if (origin.isEmpty()) {
2847 // If we don't know what origin header to attach, we attach the value
2848 // for an empty origin.
2849 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2853 request.setHTTPOrigin(origin);
2856 // Implements the "'Same-site' and 'cross-site' Requests" algorithm from <https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-2.1>.
2857 // The algorithm is ammended to treat URLs that inherit their security origin from their owner (e.g. about:blank)
2858 // as same-site. This matches the behavior of Chrome and Firefox.
2859 void FrameLoader::addSameSiteInfoToRequestIfNeeded(ResourceRequest& request, const Document* initiator)
2861 if (!request.isSameSiteUnspecified())
2864 request.setIsSameSite(true);
2867 if (SecurityPolicy::shouldInheritSecurityOriginFromOwner(request.url())) {
2868 request.setIsSameSite(true);
2871 request.setIsSameSite(registrableDomainsAreEqual(initiator->firstPartyForSameSiteCookies(), request.url()));
2874 void FrameLoader::addHTTPUpgradeInsecureRequestsIfNeeded(ResourceRequest& request)
2876 if (request.url().protocolIs("https")) {
2877 // FIXME: Identify HSTS cases and avoid adding the header. <https://bugs.webkit.org/show_bug.cgi?id=157885>
2881 request.setHTTPHeaderField(HTTPHeaderName::UpgradeInsecureRequests, "1"_s);
2884 void FrameLoader::loadPostRequest(FrameLoadRequest&& request, const String& referrer, FrameLoadType loadType, Event* event, RefPtr<FormState>&& formState, CompletionHandler<void()>&& completionHandler)
2886 String frameName = request.frameName();
2887 LockHistory lockHistory = request.lockHistory();
2888 AllowNavigationToInvalidURL allowNavigationToInvalidURL = request.allowNavigationToInvalidURL();
2889 NewFrameOpenerPolicy openerPolicy = request.newFrameOpenerPolicy();
2891 const ResourceRequest& inRequest = request.resourceRequest();
2892 const URL& url = inRequest.url();
2893 const String& contentType = inRequest.httpContentType();
2894 String origin = inRequest.httpOrigin();
2896 ResourceRequest workingResourceRequest(url);
2898 if (!referrer.isEmpty())
2899 workingResourceRequest.setHTTPReferrer(referrer);
2900 workingResourceRequest.setHTTPOrigin(origin);
2901 workingResourceRequest.setHTTPMethod("POST");
2902 workingResourceRequest.setHTTPBody(inRequest.httpBody());
2903 workingResourceRequest.setHTTPContentType(contentType);
2904 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2906 if (Document* document = m_frame.document())
2907 document->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(workingResourceRequest, ContentSecurityPolicy::InsecureRequestType::Load);
2909 NavigationAction action { request.requester(), workingResourceRequest, request.initiatedByMainFrame(), loadType, true, event, request.shouldOpenExternalURLsPolicy(), request.downloadAttribute() };
2911 if (!frameName.isEmpty()) {
2912 // The search for a target frame is done earlier in the case of form submission.
2913 if (auto* targetFrame = formState ? nullptr : findFrameForNavigation(frameName)) {
2914 targetFrame->loader().loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL, WTFMove(completionHandler));
2918 policyChecker().checkNewWindowPolicy(WTFMove(action), WTFMove(workingResourceRequest), WTFMove(formState), frameName, [this, allowNavigationToInvalidURL, openerPolicy, completionHandler = WTFMove(completionHandler)] (const ResourceRequest& request, WeakPtr<FormState>&& formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue) {
2919 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
2920 completionHandler();
2925 // must grab this now, since this load may stop the previous load and clear this flag
2926 bool isRedirect = m_quickRedirectComing;
2927 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL, [this, isRedirect, protectedFrame = makeRef(m_frame), completionHandler = WTFMove(completionHandler)] {
2929 m_quickRedirectComing = false;
2930 if (m_provisionalDocumentLoader)
2931 m_provisionalDocumentLoader->setIsClientRedirect(true);
2932 else if (m_policyDocumentLoader)
2933 m_policyDocumentLoader->setIsClientRedirect(true);
2935 completionHandler();
2939 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, ClientCredentialPolicy clientCredentialPolicy, const FetchOptions& options, const HTTPHeaderMap& originalRequestHeaders, ResourceError& error, ResourceResponse& response, RefPtr<SharedBuffer>& data)
2941 ASSERT(m_frame.document());
2942 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), request.url(), outgoingReferrer());
2944 ResourceRequest initialRequest = request;
2945 initialRequest.setTimeoutInterval(10);
2947 if (!referrer.isEmpty())
2948 initialRequest.setHTTPReferrer(referrer);
2949 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2951 initialRequest.setFirstPartyForCookies(m_frame.mainFrame().loader().documentLoader()->request().url());
2953 addExtraFieldsToSubresourceRequest(initialRequest);
2955 unsigned long identifier = 0;
2956 ResourceRequest newRequest(initialRequest);
2957 requestFromDelegate(newRequest, identifier, error);
2959 #if ENABLE(CONTENT_EXTENSIONS)
2960 if (error.isNull()) {
2961 if (auto* page = m_frame.page()) {
2962 if (m_documentLoader) {
2963 auto blockedStatus = page->userContentProvider().processContentExtensionRulesForLoad(newRequest.url(), ResourceType::Raw, *m_documentLoader);
2964 applyBlockedStatusToRequest(blockedStatus, page, newRequest);
2965 if (blockedStatus.blockedLoad) {
2967 error = ResourceError(errorDomainWebKitInternal, 0, initialRequest.url(), emptyString());
2976 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(newRequest, ContentSecurityPolicy::InsecureRequestType::Load);
2978 if (error.isNull()) {
2979 ASSERT(!newRequest.isNull());
2981 if (!documentLoader()->applicationCacheHost().maybeLoadSynchronously(newRequest, error, response, data)) {
2982 Vector<char> buffer;
2983 platformStrategies()->loaderStrategy()->loadResourceSynchronously(*this, identifier, newRequest, clientCredentialPolicy, options, originalRequestHeaders, error, response, buffer);
2984 data = SharedBuffer::create(WTFMove(buffer));
2985 documentLoader()->applicationCacheHost().maybeLoadFallbackSynchronously(newRequest, error, response, data);
2986 ResourceLoadObserver::shared().logSubresourceLoading(&m_frame, newRequest, response);
2989 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data ? data->data() : nullptr, data ? data->size() : 0, -1, error);
2993 const ResourceRequest& FrameLoader::originalRequest() const
2995 return activeDocumentLoader()->originalRequestCopy();
2998 void FrameLoader::receivedMainResourceError(const ResourceError& error)
3000 // Retain because the stop may release the last reference to it.
3001 Ref<Frame> protect(m_frame);
3003 RefPtr<DocumentLoader> loader = activeDocumentLoader();
3004 // FIXME: Don't want to do this if an entirely new load is going, so should check
3005 // that both data sources on the frame are either this or nil.
3007 if (m_client.shouldFallBack(error))
3008 handleFallbackContent();
3010 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
3011 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
3012 m_submittedFormURL = URL();
3014 // We might have made a page cache item, but now we're bailing out due to an error before we ever
3015 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
3016 // so that the existing view (that wenever got far enough to replace) can continue being used.
3017 history().invalidateCurrentItemCachedPage();
3019 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
3020 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
3021 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
3022 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
3024 if (m_sentRedirectNotification)
3025 clientRedirectCancelledOrFinished(false);
3030 checkLoadComplete();
3033 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
3035 m_quickRedirectComing = false;
3037 if (!shouldContinue)
3040 // Calling stopLoading() on the provisional document loader can cause the underlying
3041 // frame to be deallocated.
3042 Ref<Frame> protectedFrame(m_frame);
3044 // If we have a provisional request for a different document, a fragment scroll should cancel it.
3045 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
3046 m_provisionalDocumentLoader->stopLoading();
3047 setProvisionalDocumentLoader(nullptr);
3050 bool isRedirect = m_quickRedirectComing || policyChecker().loadType() == FrameLoadType::RedirectWithLockedBackForwardList;
3051 loadInSameDocument(request.url(), 0, !isRedirect);
3054 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const URL& url)
3056 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
3057 // currently displaying a frameset, or if the URL does not have a fragment.
3058 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
3060 // FIXME: What about load types other than Standard and Reload?
3062 return (!isFormSubmission || equalLettersIgnoringASCIICase(httpMethod, "get"))
3063 && !isReload(loadType)
3064 && loadType != FrameLoadType::Same
3065 && !shouldReload(m_frame.document()->url(), url)
3066 // We don't want to just scroll if a link from within a
3067 // frameset is trying to reload the frameset into _top.
3068 && !m_frame.document()->isFrameSet();
3071 static bool itemAllowsScrollRestoration(HistoryItem* historyItem)
3073 return !historyItem || historyItem->shouldRestoreScrollPosition();
3076 static bool isSameDocumentReload(bool isNewNavigation, FrameLoadType loadType)
3078 return !isNewNavigation && !isBackForwardLoadType(loadType);
3081 void FrameLoader::scrollToFragmentWithParentBoundary(const URL& url, bool isNewNavigation)
3083 FrameView* view = m_frame.view();
3087 if (isSameDocumentReload(isNewNavigation, m_loadType) || itemAllowsScrollRestoration(history().currentItem()))
3088 view->scrollToFragment(url);
3091 bool FrameLoader::shouldClose()
3093 Page* page = m_frame.page();
3096 if (!page->chrome().canRunBeforeUnloadConfirmPanel())
3099 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
3100 Vector<Ref<Frame>, 16> targetFrames;
3101 targetFrames.append(m_frame);
3102 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().traverseNext(&m_frame))
3103 targetFrames.append(*child);
3105 bool shouldClose = false;
3107 NavigationDisabler navigationDisabler(&m_frame);
3110 for (i = 0; i < targetFrames.size(); i++) {
3111 if (!targetFrames[i]->tree().isDescendantOf(&m_frame))
3113 if (!targetFrames[i]->loader().dispatchBeforeUnloadEvent(page->chrome(), this))
3117 if (i == targetFrames.size())
3122 m_submittedFormURL = URL();
3124 m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
3128 void FrameLoader::dispatchUnloadEvents(UnloadEventPolicy unloadEventPolicy)
3130 if (!m_frame.document())
3133 // We store the frame's page in a local variable because the frame might get detached inside dispatchEvent.
3134 ForbidPromptsScope forbidPrompts(m_frame.page());
3135 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
3137 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
3138 auto* currentFocusedElement = m_frame.document()->focusedElement();
3139 if (is<HTMLInputElement>(currentFocusedElement))
3140 downcast<HTMLInputElement>(*currentFocusedElement).endEditing();
3141 if (m_pageDismissalEventBeingDispatched == PageDismissalType::None) {
3142 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
3143 m_pageDismissalEventBeingDispatched = PageDismissalType::PageHide;
3144 m_frame.document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache), m_frame.document());
3147 // FIXME: update Page Visibility state here.
3148 // https://bugs.webkit.org/show_bug.cgi?id=116770
3150 if (m_frame.document()->pageCacheState() == Document::NotInPageCache) {
3151 Ref<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
3152 // The DocumentLoader (and thus its LoadTiming) might get destroyed
3153 // while dispatching the event, so protect it to prevent writing the end
3154 // time into freed memory.
3155 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
3156 m_pageDismissalEventBeingDispatched = PageDismissalType::Unload;
3157 if (documentLoader && documentLoader->timing().startTime() && !documentLoader->timing().unloadEventStart() && !documentLoader->timing().unloadEventEnd()) {
3158 auto& timing = documentLoader->timing();
3159 timing.markUnloadEventStart();
3160 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
3161 timing.markUnloadEventEnd();
3163 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
3166 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
3167 m_wasUnloadEventEmitted = true;
3170 // Dispatching the unload event could have made m_frame.document() null.
3171 if (!m_frame.document())
3174 if (m_frame.document()->pageCacheState() != Document::NotInPageCache)
3177 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
3178 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
3179 && m_frame.document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
3181 if (!keepEventListeners)
3182 m_frame.document()->removeAllEventListeners();
3185 static bool shouldAskForNavigationConfirmation(Document& document, const BeforeUnloadEvent& event)
3187 // Confirmation dialog should not be displayed when the allow-modals flag is not set.
3188 if (document.isSandboxed(SandboxModals))
3191 bool userDidInteractWithPage = document.topDocument().userDidInteractWithPage();
3192 // Web pages can request we ask for confirmation before navigating by:
3193 // - Cancelling the BeforeUnloadEvent (modern way)
3194 // - Setting the returnValue attribute on the BeforeUnloadEvent to a non-empty string.
3195 // - Returning a non-empty string from the event handler, which is then set as returnValue
3196 // attribute on the BeforeUnloadEvent.
3197 return userDidInteractWithPage && (event.defaultPrevented() || !event.returnValue().isEmpty());
3200 bool FrameLoader::dispatchBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
3202 DOMWindow* domWindow = m_frame.document()->domWindow();
3206 RefPtr<Document> document = m_frame.document();
3207 if (!document->bodyOrFrameset())
3210 Ref<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
3211 m_pageDismissalEventBeingDispatched = PageDismissalType::BeforeUnload;
3214 ForbidPromptsScope forbidPrompts(m_frame.page());
3215 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
3216 domWindow->dispatchEvent(beforeUnloadEvent, domWindow->document());
3219 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
3221 if (!beforeUnloadEvent->defaultPrevented())
3222 document->defaultEventHandler(beforeUnloadEvent.get());
3224 if (!shouldAskForNavigationConfirmation(*document, beforeUnloadEvent))
3227 // If the navigating FrameLoader has already shown a beforeunload confirmation panel for the current navigation attempt,
3228 // this frame is not allowed to cause another one to be shown.
3229 if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
3230 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation."_s);
3234 // We should only display the beforeunload dialog for an iframe if its SecurityOrigin matches all
3235 // ancestor frame SecurityOrigins up through the navigating FrameLoader.
3236 if (frameLoaderBeingNavigated != this) {
3237 Frame* parentFrame = m_frame.tree().parent();
3238 while (parentFrame) {
3239 Document* parentDocument = parentFrame->document();
3240 if (!parentDocument)
3242 if (!m_frame.document() || !m_frame.document()->securityOrigin().canAccess(parentDocument->securityOrigin())) {
3243 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Blocked attempt to show beforeunload confirmation dialog on behalf of a frame with different security origin. Protocols, domains, and ports must match."_s);
3247 if (&parentFrame->loader() == frameLoaderBeingNavigated)
3250 parentFrame = parentFrame->tree().parent();
3253 // The navigatingFrameLoader should always be in our ancestory.
3254 ASSERT(parentFrame);
3255 ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
3258 frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
3260 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
3261 return chrome.runBeforeUnloadConfirmPanel(text, m_frame);
3264 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest& request, FormState* formState, ShouldContinue shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
3266 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
3267 // nil policyDataSource because loading the alternate page will have passed
3268 // through this method already, nested; otherwise, policyDataSource should still be set.
3269 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
3271 bool isTargetItem = history().provisionalItem() ? history().provisionalItem()->isTargetItem() : false;
3273 bool urlIsDisallowed = allowNavigationToInvalidURL == AllowNavigationToInvalidURL::No && !request.url().isValid();
3274 bool canContinue = shouldContinue != ShouldContinue::No && shouldClose() && !urlIsDisallowed;
3277 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
3278 // need to report that the client redirect was cancelled.
3279 // FIXME: The client should be told about ignored non-quick redirects, too.
3280 if (m_quickRedirectComing)
3281 clientRedirectCancelledOrFinished(false);
3283 setPolicyDocumentLoader(nullptr);
3285 checkLoadComplete();
3287 // If the navigation request came from the back/forward menu, and we punt on it, we have the
3288 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
3289 // we only do this when punting a navigation for the target frame or top-level frame.
3290 if ((isTargetItem || m_frame.isMainFrame()) && isBackForwardLoadType(policyChecker().loadType())) {
3291 if (Page* page = m_frame.page()) {
3292 if (HistoryItem* resetItem = m_frame.mainFrame().loader().history().currentItem()) {
3293 page->backForward().setCurrentItem(resetItem);
3294 m_frame.loader().client().updateGlobalHistoryItemForPage();
3301 FrameLoadType type = policyChecker().loadType();
3302 // A new navigation is in progress, so don't clear the history's provisional item.
3303 stopAllLoaders(ShouldNotClearProvisionalItem);
3305 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
3306 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
3307 if (!m_frame.page())
3310 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
3312 setState(FrameStateProvisional);
3314 setPolicyDocumentLoader(nullptr);
3316 if (isBackForwardLoadType(type)) {
3317 auto& diagnosticLoggingClient = m_frame.page()->diagnosticLoggingClient();
3318 if (history().provisionalItem()->isInPageCache()) {
3319 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultPass, ShouldSample::Yes);
3320 loadProvisionalItemFromCachedPage();
3323 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultFail, ShouldSample::Yes);
3326 CompletionHandler<void(void)> completionHandler = [this, shouldContinue] {
3327 if (!m_provisionalDocumentLoader)
3330 prepareForLoadStart();
3332 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
3333 // so we need to null check it again.
3334 if (!m_provisionalDocumentLoader) {
3335 RELEASE_LOG_IF_ALLOWED("dispatchWillSubmitForm completionHandler: Frame load canceled (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3339 DocumentLoader* activeDocLoader = activeDocumentLoader();
3340 if (activeDocLoader && activeDocLoader->isLoadingMainResource()) {
3341 RELEASE_LOG_IF_ALLOWED("dispatchWillSubmitForm completionHandler: Main frame already being loaded (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3345 m_loadingFromCachedPage = false;
3347 // We handle suspension by navigating forward to about:blank, which leaves us setup to navigate back to resume.
3348 if (shouldContinue == ShouldContinue::ForSuspension)
3349 m_provisionalDocumentLoader->willContinueMainResourceLoadAfterRedirect({ blankURL() });
3351 m_provisionalDocumentLoader->startLoadingMainResource(shouldContinue);
3355 completionHandler();
3359 m_client.dispatchWillSubmitForm(*formState, WTFMove(completionHandler));
3362 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
3363 FormState* formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL, NewFrameOpenerPolicy openerPolicy)
3365 ASSERT(shouldContinue != ShouldContinue::ForSuspension);
3366 if (shouldContinue != ShouldContinue::Yes)
3369 Ref<Frame> frame(m_frame);
3370 RefPtr<Frame> mainFrame = m_client.dispatchCreatePage(action);
3374 SandboxFlags sandboxFlags = frame->loader().effectiveSandboxFlags();
3375 if (sandboxFlags & SandboxPropagatesToAuxiliaryBrowsingContexts)
3376 mainFrame->loader().forceSandboxFlags(sandboxFlags);
3378 if (!equalIgnoringASCIICase(frameName, "_blank"))
3379 mainFrame->tree().setName(frameName);
3381 mainFrame->page()->setOpenedByDOM();
3382 mainFrame->loader().m_client.dispatchShow();
3383 if (openerPolicy == NewFrameOpenerPolicy::Allow) {
3384 mainFrame->loader().setOpener(frame.ptr());
3385 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
3388 NavigationAction newAction { *frame->document(), request, InitiatedByMainFrame::Unknown, NavigationType::Other, action.shouldOpenExternalURLsPolicy() };
3389 mainFrame->loader().loadWithNavigationAction(request, newAction, LockHistory::No, FrameLoadType::Standard, formState, allowNavigationToInvalidURL, [] { });
3392 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
3394 ASSERT(!request.isNull());
3397 if (Page* page = m_frame.page()) {
3398 identifier = page->progress().createUniqueIdentifier();
3399 notifier().assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
3402 ResourceRequest newRequest(request);
3403 notifier().dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
3405 if (newRequest.isNull())
3406 error = cancelledError(request);
3408 error = ResourceError();
3410 request = newRequest;
3413 void FrameLoader::loadedResourceFromMemoryCache(CachedResource& resource, ResourceRequest& newRequest, ResourceError& error)
3415 Page* page = m_frame.page();