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 "ContentRuleListResults.h"
49 #include "ContentSecurityPolicy.h"
50 #include "CustomHeaderFields.h"
51 #include "DOMWindow.h"
52 #include "DatabaseManager.h"
53 #include "DiagnosticLoggingClient.h"
54 #include "DiagnosticLoggingKeys.h"
56 #include "DocumentLoader.h"
58 #include "EditorClient.h"
61 #include "EventHandler.h"
62 #include "EventNames.h"
63 #include "FloatRect.h"
64 #include "FormState.h"
65 #include "FormSubmission.h"
67 #include "FrameLoadRequest.h"
68 #include "FrameLoaderClient.h"
69 #include "FrameNetworkingContext.h"
70 #include "FrameTree.h"
71 #include "FrameView.h"
72 #include "GCController.h"
73 #include "HTMLFormElement.h"
74 #include "HTMLInputElement.h"
75 #include "HTMLNames.h"
76 #include "HTMLObjectElement.h"
77 #include "HTMLParserIdioms.h"
78 #include "HTTPHeaderNames.h"
79 #include "HTTPParsers.h"
80 #include "HistoryController.h"
81 #include "HistoryItem.h"
82 #include "IgnoreOpensDuringUnloadCountIncrementer.h"
83 #include "InspectorController.h"
84 #include "InspectorInstrumentation.h"
85 #include "LinkLoader.h"
86 #include "LoadTiming.h"
87 #include "LoaderStrategy.h"
89 #include "MemoryCache.h"
90 #include "MemoryRelease.h"
91 #include "NavigationDisabler.h"
92 #include "NavigationScheduler.h"
95 #include "PageCache.h"
96 #include "PageTransitionEvent.h"
97 #include "PerformanceLogging.h"
98 #include "PlatformStrategies.h"
99 #include "PluginData.h"
100 #include "PluginDocument.h"
101 #include "PolicyChecker.h"
102 #include "ProgressTracker.h"
103 #include "ResourceHandle.h"
104 #include "ResourceLoadInfo.h"
105 #include "ResourceLoadObserver.h"
106 #include "ResourceRequest.h"
107 #include "SVGDocument.h"
108 #include "SVGLocatable.h"
109 #include "SVGNames.h"
110 #include "SVGViewElement.h"
111 #include "SVGViewSpec.h"
112 #include "ScriptController.h"
113 #include "ScriptSourceCode.h"
114 #include "ScrollAnimator.h"
115 #include "SecurityOrigin.h"
116 #include "SecurityPolicy.h"
117 #include "SegmentedString.h"
118 #include "SerializedScriptValue.h"
119 #include "Settings.h"
120 #include "ShouldTreatAsContinuingLoad.h"
121 #include "StyleTreeResolver.h"
122 #include "SubframeLoader.h"
123 #include "SubresourceLoader.h"
124 #include "TextResourceDecoder.h"
125 #include "UserContentController.h"
126 #include "UserGestureIndicator.h"
127 #include "WindowFeatures.h"
128 #include "XMLDocumentParser.h"
129 #include <dom/ScriptDisallowedScope.h>
130 #include <wtf/CompletionHandler.h>
133 #include <wtf/SetForScope.h>
134 #include <wtf/StdLibExtras.h>
135 #include <wtf/SystemTracing.h>
136 #include <wtf/text/CString.h>
137 #include <wtf/text/WTFString.h>
139 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
143 #if ENABLE(DATA_DETECTION)
144 #include "DataDetection.h"
147 #if PLATFORM(IOS_FAMILY)
148 #include "DocumentType.h"
149 #include "ResourceLoader.h"
150 #include "RuntimeApplicationChecks.h"
153 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - FrameLoader::" fmt, this, ##__VA_ARGS__)
157 using namespace HTMLNames;
158 using namespace SVGNames;
160 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
162 bool isBackForwardLoadType(FrameLoadType type)
165 case FrameLoadType::Standard:
166 case FrameLoadType::Reload:
167 case FrameLoadType::ReloadFromOrigin:
168 case FrameLoadType::ReloadExpiredOnly:
169 case FrameLoadType::Same:
170 case FrameLoadType::RedirectWithLockedBackForwardList:
171 case FrameLoadType::Replace:
173 case FrameLoadType::Back:
174 case FrameLoadType::Forward:
175 case FrameLoadType::IndexedBackForward:
178 ASSERT_NOT_REACHED();
182 bool isReload(FrameLoadType type)
185 case FrameLoadType::Reload:
186 case FrameLoadType::ReloadFromOrigin:
187 case FrameLoadType::ReloadExpiredOnly:
189 case FrameLoadType::Standard:
190 case FrameLoadType::Same:
191 case FrameLoadType::RedirectWithLockedBackForwardList:
192 case FrameLoadType::Replace:
193 case FrameLoadType::Back:
194 case FrameLoadType::Forward:
195 case FrameLoadType::IndexedBackForward:
198 ASSERT_NOT_REACHED();
202 // This is not in the FrameLoader class to emphasize that it does not depend on
203 // private FrameLoader data, and to avoid increasing the number of public functions
204 // with access to private data. Since only this .cpp file needs it, making it
205 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
208 static bool isDocumentSandboxed(Frame& frame, SandboxFlags mask)
210 return frame.document() && frame.document()->isSandboxed(mask);
213 struct ForbidPromptsScope {
214 ForbidPromptsScope(Page* page) : m_page(page)
218 m_page->forbidPrompts();
221 ~ForbidPromptsScope()
225 m_page->allowPrompts();
231 class FrameLoader::FrameProgressTracker {
232 WTF_MAKE_FAST_ALLOCATED;
234 explicit FrameProgressTracker(Frame& frame)
236 , m_inProgress(false)
240 ~FrameProgressTracker()
242 if (m_inProgress && m_frame.page())
243 m_frame.page()->progress().progressCompleted(m_frame);
246 void progressStarted()
248 ASSERT(m_frame.page());
250 m_frame.page()->progress().progressStarted(m_frame);
254 void progressCompleted()
256 ASSERT(m_inProgress);
257 ASSERT(m_frame.page());
258 m_inProgress = false;
259 m_frame.page()->progress().progressCompleted(m_frame);
261 if (auto pageID = m_frame.loader().client().pageID())
262 platformStrategies()->loaderStrategy()->pageLoadCompleted(pageID.value());
270 FrameLoader::FrameLoader(Frame& frame, FrameLoaderClient& client)
273 , m_policyChecker(makeUnique<PolicyChecker>(frame))
274 , m_history(makeUnique<HistoryController>(frame))
276 , m_subframeLoader(makeUnique<SubframeLoader>(frame))
277 , m_mixedContentChecker(frame)
278 , m_state(FrameStateProvisional)
279 , m_loadType(FrameLoadType::Standard)
280 , m_quickRedirectComing(false)
281 , m_sentRedirectNotification(false)
282 , m_inStopAllLoaders(false)
283 , m_isExecutingJavaScriptFormAction(false)
284 , m_didCallImplicitClose(true)
285 , m_wasUnloadEventEmitted(false)
286 , m_isComplete(false)
287 , m_needsClear(false)
288 , m_checkTimer(*this, &FrameLoader::checkTimerFired)
289 , m_shouldCallCheckCompleted(false)
290 , m_shouldCallCheckLoadComplete(false)
292 , m_loadingFromCachedPage(false)
293 , m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
294 , m_loadsSynchronously(false)
295 , m_forcedSandboxFlags(SandboxNone)
299 FrameLoader::~FrameLoader()
303 for (auto& frame : m_openedFrames)
304 frame->loader().m_opener = nullptr;
306 m_client.frameLoaderDestroyed();
308 if (m_networkingContext)
309 m_networkingContext->invalidate();
312 void FrameLoader::init()
314 // This somewhat odd set of steps gives the frame an initial empty document.
315 setPolicyDocumentLoader(m_client.createDocumentLoader(ResourceRequest(URL({ }, emptyString())), SubstituteData()).ptr());
316 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
317 m_provisionalDocumentLoader->startLoadingMainResource();
319 Ref<Frame> protect(m_frame);
320 m_frame.document()->cancelParsing();
321 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
323 m_networkingContext = m_client.createNetworkingContext();
324 m_progressTracker = makeUnique<FrameProgressTracker>(m_frame);
327 void FrameLoader::initForSynthesizedDocument(const URL&)
329 // FIXME: We need to initialize the document URL to the specified URL. Currently the URL is empty and hence
330 // FrameLoader::checkCompleted() will overwrite the URL of the document to be activeDocumentLoader()->documentURL().
332 auto loader = m_client.createDocumentLoader(ResourceRequest(URL({ }, emptyString())), SubstituteData());
333 loader->attachToFrame(m_frame);
334 loader->setResponse(ResourceResponse(URL(), "text/html"_s, 0, String()));
335 loader->setCommitted(true);
336 setDocumentLoader(loader.ptr());
338 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
339 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
340 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
341 m_client.transitionToCommittedForNewPage();
343 m_didCallImplicitClose = true;
345 m_state = FrameStateComplete;
348 m_networkingContext = m_client.createNetworkingContext();
349 m_progressTracker = makeUnique<FrameProgressTracker>(m_frame);
352 void FrameLoader::setDefersLoading(bool defers)
354 if (m_documentLoader)
355 m_documentLoader->setDefersLoading(defers);
356 if (m_provisionalDocumentLoader)
357 m_provisionalDocumentLoader->setDefersLoading(defers);
358 if (m_policyDocumentLoader)
359 m_policyDocumentLoader->setDefersLoading(defers);
360 history().setDefersLoading(defers);
363 m_frame.navigationScheduler().startTimer();
364 startCheckCompleteTimer();
368 void FrameLoader::checkContentPolicy(const ResourceResponse& response, PolicyCheckIdentifier identifier, ContentPolicyDecisionFunction&& function)
370 if (!activeDocumentLoader()) {
371 // Load was cancelled
372 function(PolicyAction::Ignore, identifier);
376 // FIXME: Validate the policy check identifier.
377 client().dispatchDecidePolicyForResponse(response, activeDocumentLoader()->request(), identifier, activeDocumentLoader()->downloadAttribute(), WTFMove(function));
380 void FrameLoader::changeLocation(FrameLoadRequest&& request)
382 urlSelected(WTFMove(request), nullptr);
385 void FrameLoader::urlSelected(const URL& url, const String& passedTarget, Event* triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy, Optional<NewFrameOpenerPolicy> openerPolicy, const AtomString& downloadAttribute, const SystemPreviewInfo& systemPreviewInfo, Optional<AdClickAttribution>&& adClickAttribution)
387 auto* frame = lexicalFrameFromCommonVM();
388 auto initiatedByMainFrame = frame && frame->isMainFrame() ? InitiatedByMainFrame::Yes : InitiatedByMainFrame::Unknown;
390 NewFrameOpenerPolicy newFrameOpenerPolicy = openerPolicy.valueOr(shouldSendReferrer == NeverSendReferrer ? NewFrameOpenerPolicy::Suppress : NewFrameOpenerPolicy::Allow);
391 urlSelected(FrameLoadRequest(*m_frame.document(), m_frame.document()->securityOrigin(), { url }, passedTarget, lockHistory, lockBackForwardList, shouldSendReferrer, AllowNavigationToInvalidURL::Yes, newFrameOpenerPolicy, shouldOpenExternalURLsPolicy, initiatedByMainFrame, DoNotReplaceDocumentIfJavaScriptURL, downloadAttribute, systemPreviewInfo), triggeringEvent, WTFMove(adClickAttribution));
394 void FrameLoader::urlSelected(FrameLoadRequest&& frameRequest, Event* triggeringEvent, Optional<AdClickAttribution>&& adClickAttribution)
396 RELEASE_LOG_IF_ALLOWED("urlSelected: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
398 Ref<Frame> protect(m_frame);
400 if (m_frame.script().executeIfJavaScriptURL(frameRequest.resourceRequest().url(), frameRequest.shouldReplaceDocumentIfJavaScriptURL()))
403 if (frameRequest.frameName().isEmpty())
404 frameRequest.setFrameName(m_frame.document()->baseTarget());
406 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
407 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(frameRequest.resourceRequest(), ContentSecurityPolicy::InsecureRequestType::Navigation);
409 loadFrameRequest(WTFMove(frameRequest), triggeringEvent, { }, WTFMove(adClickAttribution));
412 void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
414 ASSERT(submission->method() == FormSubmission::Method::Post || submission->method() == FormSubmission::Method::Get);
416 // FIXME: Find a good spot for these.
417 ASSERT(!submission->state().sourceDocument().frame() || submission->state().sourceDocument().frame() == &m_frame);
422 if (submission->action().isEmpty())
425 if (isDocumentSandboxed(m_frame, SandboxForms)) {
426 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
427 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.");
431 if (WTF::protocolIsJavaScript(submission->action())) {
432 if (!m_frame.document()->contentSecurityPolicy()->allowFormAction(URL(submission->action())))
434 m_isExecutingJavaScriptFormAction = true;
435 Ref<Frame> protect(m_frame);
436 m_frame.script().executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
437 m_isExecutingJavaScriptFormAction = false;
441 Frame* targetFrame = findFrameForNavigation(submission->target(), &submission->state().sourceDocument());
443 if (!DOMWindow::allowPopUp(m_frame) && !UserGestureIndicator::processingUserGesture())
446 // FIXME: targetFrame can be null for two distinct reasons:
447 // 1. The frame was not found by name, so we should try opening a new window.
448 // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
449 // Continuing form submission makes no sense in the latter case.
450 // There is a repeat check after timer fires, so this is not a correctness issue.
452 targetFrame = &m_frame;
454 submission->clearTarget();
456 if (!targetFrame->page())
459 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
461 // We do not want to submit more than one form from the same page, nor do we want to submit a single
462 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
463 // The flag is reset in each time we start dispatching a new mouse or key down event, and
464 // also in setView since this part may get reused for a page from the back/forward cache.
465 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
467 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
468 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
469 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
471 if (m_frame.tree().isDescendantOf(targetFrame)) {
472 if (m_submittedFormURL == submission->requestURL())
474 m_submittedFormURL = submission->requestURL();
477 submission->setReferrer(outgoingReferrer());
478 submission->setOrigin(outgoingOrigin());
480 targetFrame->navigationScheduler().scheduleFormSubmission(WTFMove(submission));
483 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
485 if (m_frame.document() && m_frame.document()->parser())
486 m_frame.document()->parser()->stopParsing();
488 if (unloadEventPolicy != UnloadEventPolicyNone)
489 dispatchUnloadEvents(unloadEventPolicy);
491 m_isComplete = true; // to avoid calling completed() in finishedParsing()
492 m_didCallImplicitClose = true; // don't want that one either
494 if (m_frame.document() && m_frame.document()->parsing()) {
496 m_frame.document()->setParsing(false);
499 if (auto* document = m_frame.document()) {
500 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
501 DatabaseManager::singleton().stopDatabases(*document, nullptr);
504 policyChecker().stopCheck();
506 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
507 m_frame.navigationScheduler().cancel();
510 void FrameLoader::stop()
512 // http://bugs.webkit.org/show_bug.cgi?id=10854
513 // The frame's last ref may be removed and it will be deleted by checkCompleted().
514 Ref<Frame> protect(m_frame);
516 if (DocumentParser* parser = m_frame.document()->parser()) {
517 parser->stopParsing();
522 void FrameLoader::willTransitionToCommitted()
524 // This function is called when a frame is still fully in place (not cached, not detached), but will be replaced.
526 if (m_frame.editor().hasComposition()) {
527 // The text was already present in DOM, so it's better to confirm than to cancel the composition.
528 m_frame.editor().confirmComposition();
529 if (EditorClient* editorClient = m_frame.editor().client()) {
530 editorClient->respondToChangedSelection(&m_frame);
531 editorClient->discardedComposition(&m_frame);
536 bool FrameLoader::closeURL()
538 history().saveDocumentState();
540 Document* currentDocument = m_frame.document();
541 UnloadEventPolicy unloadEventPolicy;
542 if (m_frame.page() && m_frame.page()->chrome().client().isSVGImageChromeClient()) {
543 // If this is the SVGDocument of an SVGImage, no need to dispatch events or recalcStyle.
544 unloadEventPolicy = UnloadEventPolicyNone;
546 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
547 unloadEventPolicy = currentDocument && currentDocument->pageCacheState() == Document::NotInPageCache ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly;
550 stopLoading(unloadEventPolicy);
552 m_frame.editor().clearUndoRedoOperations();
556 bool FrameLoader::didOpenURL()
558 if (m_frame.navigationScheduler().redirectScheduledDuringLoad()) {
559 // A redirect was scheduled before the document was created.
560 // This can happen when one frame changes another frame's location.
564 m_frame.navigationScheduler().cancel();
565 m_frame.editor().clearLastEditCommand();
567 m_isComplete = false;
568 m_didCallImplicitClose = false;
570 // If we are still in the process of initializing an empty document then
571 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
572 // since it may cause clients to attempt to render the frame.
573 if (!m_stateMachine.creatingInitialEmptyDocument()) {
574 DOMWindow* window = m_frame.document()->domWindow();
575 window->setStatus(String());
576 window->setDefaultStatus(String());
584 void FrameLoader::didExplicitOpen()
586 m_isComplete = false;
587 m_didCallImplicitClose = false;
589 // Calling document.open counts as committing the first real document load.
590 if (!m_stateMachine.committedFirstRealDocumentLoad())
591 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
593 m_client.dispatchDidExplicitOpen(m_frame.document() ? m_frame.document()->url() : URL());
595 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
596 // from a subsequent window.document.open / window.document.write call.
597 // Canceling redirection here works for all cases because document.open
598 // implicitly precedes document.write.
599 m_frame.navigationScheduler().cancel();
603 void FrameLoader::cancelAndClear()
605 m_frame.navigationScheduler().cancel();
610 clear(m_frame.document(), false);
611 m_frame.script().updatePlatformScriptObjects();
614 static inline bool shouldClearWindowName(const Frame& frame, const Document& newDocument)
616 if (!frame.isMainFrame())
619 if (frame.loader().opener())
622 return !newDocument.securityOrigin().isSameOriginAs(frame.document()->securityOrigin());
625 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView, WTF::Function<void()>&& handleDOMWindowCreation)
627 m_frame.editor().clear();
629 bool neededClear = m_needsClear;
630 m_needsClear = false;
632 if (neededClear && m_frame.document()->pageCacheState() != Document::InPageCache) {
633 m_frame.document()->cancelParsing();
634 m_frame.document()->stopActiveDOMObjects();
635 bool hadLivingRenderTree = m_frame.document()->hasLivingRenderTree();
636 m_frame.document()->prepareForDestruction();
637 if (hadLivingRenderTree)
638 m_frame.document()->adjustFocusedNodeOnNodeRemoval(*m_frame.document());
641 if (handleDOMWindowCreation)
642 handleDOMWindowCreation();
647 // Do this after detaching the document so that the unload event works.
648 if (clearWindowProperties) {
649 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame.document()->domWindow());
650 m_frame.document()->domWindow()->resetUnlessSuspendedForDocumentSuspension();
651 m_frame.windowProxy().clearJSWindowProxiesNotMatchingDOMWindow(newDocument->domWindow(), m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache);
653 if (shouldClearWindowName(m_frame, *newDocument))
654 m_frame.tree().setName(nullAtom());
657 m_frame.selection().prepareForDestruction();
658 m_frame.eventHandler().clear();
660 if (clearFrameView && m_frame.view())
661 m_frame.view()->clear();
663 // Do not drop the document before the ScriptController and view are cleared
664 // as some destructors might still try to access the document.
665 m_frame.setDocument(nullptr);
667 subframeLoader().clear();
669 if (clearWindowProperties)
670 m_frame.windowProxy().setDOMWindow(newDocument->domWindow());
672 if (clearScriptObjects)
673 m_frame.script().clearScriptObjects();
675 m_frame.script().enableEval();
677 m_frame.navigationScheduler().clear();
680 m_shouldCallCheckCompleted = false;
681 m_shouldCallCheckLoadComplete = false;
683 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
684 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
687 void FrameLoader::receivedFirstData()
689 dispatchDidCommitLoad(WTF::nullopt);
690 dispatchDidClearWindowObjectsInAllWorlds();
691 dispatchGlobalObjectAvailableInAllWorlds();
693 if (!m_documentLoader)
696 auto& documentLoader = *m_documentLoader;
697 auto& title = documentLoader.title();
698 if (!title.string.isNull())
699 m_client.dispatchDidReceiveTitle(title);
701 ASSERT(m_frame.document());
702 auto& document = *m_frame.document();
704 LinkLoader::loadLinksFromHeader(documentLoader.response().httpHeaderField(HTTPHeaderName::Link), document.url(), document, LinkLoader::MediaAttributeCheck::MediaAttributeEmpty);
708 if (!parseHTTPRefresh(documentLoader.response().httpHeaderField(HTTPHeaderName::Refresh), delay, urlString))
710 auto completedURL = urlString.isEmpty() ? document.url() : document.completeURL(urlString);
711 if (!WTF::protocolIsJavaScript(completedURL))
712 m_frame.navigationScheduler().scheduleRedirect(document, delay, completedURL);
714 auto message = "Refused to refresh " + document.url().stringCenterEllipsizedToLength() + " to a javascript: URL";
715 document.addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
719 void FrameLoader::setOutgoingReferrer(const URL& url)
721 m_outgoingReferrer = url.strippedForUseAsReferrer();
724 void FrameLoader::didBeginDocument(bool dispatch, ContentSecurityPolicy* previousPolicy)
727 m_isComplete = false;
728 m_didCallImplicitClose = false;
729 m_frame.document()->setReadyState(Document::Loading);
731 if (m_pendingStateObject) {
732 m_frame.document()->statePopped(*m_pendingStateObject);
733 m_pendingStateObject = nullptr;
737 dispatchDidClearWindowObjectsInAllWorlds();
739 updateFirstPartyForCookies();
740 m_frame.document()->initContentSecurityPolicy(previousPolicy);
742 const Settings& settings = m_frame.settings();
743 m_frame.document()->cachedResourceLoader().setImagesEnabled(settings.areImagesEnabled());
744 m_frame.document()->cachedResourceLoader().setAutoLoadImages(settings.loadsImagesAutomatically());
746 if (m_documentLoader) {
747 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XDNSPrefetchControl);
748 if (!dnsPrefetchControl.isEmpty())
749 m_frame.document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
751 m_frame.document()->contentSecurityPolicy()->didReceiveHeaders(ContentSecurityPolicyResponseHeaders(m_documentLoader->response()), referrer(), ContentSecurityPolicy::ReportParsingErrors::No);
753 String referrerPolicy = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ReferrerPolicy);
754 if (!referrerPolicy.isNull())
755 m_frame.document()->processReferrerPolicy(referrerPolicy, ReferrerPolicySource::HTTPHeader);
757 String headerContentLanguage = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentLanguage);
758 if (!headerContentLanguage.isEmpty()) {
759 size_t commaIndex = headerContentLanguage.find(',');
760 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
761 headerContentLanguage = stripLeadingAndTrailingHTMLSpaces(headerContentLanguage);
762 if (!headerContentLanguage.isEmpty())
763 m_frame.document()->setContentLanguage(headerContentLanguage);
767 history().restoreDocumentState();
770 void FrameLoader::finishedParsing()
772 LOG(Loading, "WebCoreLoading %s: Finished parsing", m_frame.tree().uniqueName().string().utf8().data());
774 m_frame.injectUserScripts(InjectAtDocumentEnd);
776 if (m_stateMachine.creatingInitialEmptyDocument())
779 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
780 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
781 // Null-checking the FrameView indicates whether or not we're in the destructor.
782 RefPtr<Frame> protector = m_frame.view() ? &m_frame : 0;
784 m_client.dispatchDidFinishDocumentLoad();
786 scrollToFragmentWithParentBoundary(m_frame.document()->url());
791 return; // We are being destroyed by something checkCompleted called.
793 // Check if the scrollbars are really needed for the content.
794 // If not, remove them, relayout, and repaint.
795 m_frame.view()->restoreScrollbar();
798 void FrameLoader::loadDone(LoadCompletionType type)
800 if (type == LoadCompletionType::Finish)
803 scheduleCheckCompleted();
806 void FrameLoader::subresourceLoadDone(LoadCompletionType type)
808 if (type == LoadCompletionType::Finish)
811 scheduleCheckLoadComplete();
814 bool FrameLoader::allChildrenAreComplete() const
816 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
817 if (!child->loader().m_isComplete)
823 bool FrameLoader::allAncestorsAreComplete() const
825 for (Frame* ancestor = &m_frame; ancestor; ancestor = ancestor->tree().parent()) {
826 if (!ancestor->loader().m_isComplete)
832 void FrameLoader::checkCompleted()
834 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
835 m_shouldCallCheckCompleted = false;
837 // Have we completed before?
842 // FIXME: Remove this code once https://webkit.org/b/185284 is fixed.
843 if (HTMLMediaElement::isRunningDestructor()) {
844 ASSERT_NOT_REACHED();
845 scheduleCheckCompleted();
850 // FIXME: It would be better if resource loads were kicked off after render tree update (or didn't complete synchronously).
851 // https://bugs.webkit.org/show_bug.cgi?id=171729
852 if (m_frame.document()->inRenderTreeUpdate()) {
853 scheduleCheckCompleted();
857 // Are we still parsing?
858 if (m_frame.document()->parsing())
861 // Still waiting for images/scripts?
862 if (m_frame.document()->cachedResourceLoader().requestCount())
865 // Still waiting for elements that don't go through a FrameLoader?
866 if (m_frame.document()->isDelayingLoadEvent())
869 auto* scriptableParser = m_frame.document()->scriptableDocumentParser();
870 if (scriptableParser && scriptableParser->hasScriptsWaitingForStylesheets())
873 // Any frame that hasn't completed yet?
874 if (!allChildrenAreComplete())
877 // Important not to protect earlier in this function, because earlier parts
878 // of this function can be called in the frame's destructor, and it's not legal
879 // to ref an object while it's being destroyed.
880 Ref<Frame> protect(m_frame);
884 m_requestedHistoryItem = nullptr;
885 m_frame.document()->setReadyState(Document::Complete);
887 #if PLATFORM(IOS_FAMILY)
888 if (m_frame.document()->url().isEmpty()) {
889 // We need to update the document URL of a PDF document to be non-empty so that both back/forward history navigation
890 // between PDF pages and fragment navigation works. See <rdar://problem/9544769> for more details.
891 // FIXME: Is there a better place for this code, say DocumentLoader? Also, we should explicitly only update the URL
892 // of the document when it's a PDFDocument object instead of assuming that a Document object with an empty URL is a PDFDocument.
893 // FIXME: This code is incorrect for a synthesized document (which also has an empty URL). The URL for a synthesized
894 // document should be the URL specified to FrameLoader::initForSynthesizedDocument().
895 m_frame.document()->setURL(activeDocumentLoader()->documentURL());
899 checkCallImplicitClose(); // if we didn't do it before
901 m_frame.navigationScheduler().startTimer();
908 void FrameLoader::checkTimerFired()
910 checkCompletenessNow();
913 void FrameLoader::checkCompletenessNow()
915 Ref<Frame> protect(m_frame);
917 if (Page* page = m_frame.page()) {
918 if (page->defersLoading())
921 if (m_shouldCallCheckCompleted)
923 if (m_shouldCallCheckLoadComplete)
927 void FrameLoader::startCheckCompleteTimer()
929 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
931 if (m_checkTimer.isActive())
933 m_checkTimer.startOneShot(0_s);
936 void FrameLoader::scheduleCheckCompleted()
938 m_shouldCallCheckCompleted = true;
939 startCheckCompleteTimer();
942 void FrameLoader::scheduleCheckLoadComplete()
944 m_shouldCallCheckLoadComplete = true;
945 startCheckCompleteTimer();
948 void FrameLoader::checkCallImplicitClose()
950 if (m_didCallImplicitClose || m_frame.document()->parsing() || m_frame.document()->isDelayingLoadEvent())
953 if (!allChildrenAreComplete())
954 return; // still got a frame running -> too early
956 m_didCallImplicitClose = true;
957 m_wasUnloadEventEmitted = false;
958 m_frame.document()->implicitClose();
961 void FrameLoader::loadURLIntoChildFrame(const URL& url, const String& referer, Frame* childFrame)
963 RELEASE_LOG_IF_ALLOWED("loadURLIntoChildFrame: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
967 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
968 if (auto activeLoader = activeDocumentLoader()) {
969 if (auto subframeArchive = activeLoader->popArchiveForSubframe(childFrame->tree().uniqueName(), url)) {
970 childFrame->loader().loadArchive(RefPtr<Archive> { subframeArchive }.releaseNonNull());
976 // If we're moving in the back/forward list, we might want to replace the content
977 // of this child frame with whatever was there at that point.
978 auto* parentItem = history().currentItem();
979 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType()) && !m_frame.document()->loadEventFinished()) {
980 if (auto* childItem = parentItem->childItemWithTarget(childFrame->tree().uniqueName())) {
981 childFrame->loader().m_requestedHistoryItem = childItem;
982 childFrame->loader().loadDifferentDocumentItem(*childItem, nullptr, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem, ShouldTreatAsContinuingLoad::No);
987 auto* lexicalFrame = lexicalFrameFromCommonVM();
988 auto initiatedByMainFrame = lexicalFrame && lexicalFrame->isMainFrame() ? InitiatedByMainFrame::Yes : InitiatedByMainFrame::Unknown;
990 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 };
991 childFrame->loader().loadURL(WTFMove(frameLoadRequest), referer, FrameLoadType::RedirectWithLockedBackForwardList, nullptr, { }, WTF::nullopt, [] { });
994 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
996 void FrameLoader::loadArchive(Ref<Archive>&& archive)
998 RELEASE_LOG_IF_ALLOWED("loadArchive: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1000 ArchiveResource* mainResource = archive->mainResource();
1001 ASSERT(mainResource);
1005 ResourceResponse response(URL(), mainResource->mimeType(), mainResource->data().size(), mainResource->textEncoding());
1006 SubstituteData substituteData(&mainResource->data(), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1008 ResourceRequest request(mainResource->url());
1010 auto documentLoader = m_client.createDocumentLoader(request, substituteData);
1011 documentLoader->setArchive(WTFMove(archive));
1012 load(documentLoader.get());
1015 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
1017 String FrameLoader::outgoingReferrer() const
1019 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
1020 // for why we walk the parent chain for srcdoc documents.
1021 Frame* frame = &m_frame;
1022 while (frame && frame->document()->isSrcdocDocument()) {
1023 frame = frame->tree().parent();
1024 // Srcdoc documents cannot be top-level documents, by definition,
1025 // because they need to be contained in iframes with the srcdoc.
1029 return emptyString();
1030 return frame->loader().m_outgoingReferrer;
1033 String FrameLoader::outgoingOrigin() const
1035 return m_frame.document()->securityOrigin().toString();
1038 bool FrameLoader::checkIfFormActionAllowedByCSP(const URL& url, bool didReceiveRedirectResponse) const
1040 if (m_submittedFormURL.isEmpty())
1043 auto redirectResponseReceived = didReceiveRedirectResponse ? ContentSecurityPolicy::RedirectResponseReceived::Yes : ContentSecurityPolicy::RedirectResponseReceived::No;
1044 return m_frame.document()->contentSecurityPolicy()->allowFormAction(url, redirectResponseReceived);
1047 Frame* FrameLoader::opener()
1052 void FrameLoader::setOpener(Frame* opener)
1054 if (m_opener && !opener)
1055 m_client.didDisownOpener();
1058 // When setOpener is called in ~FrameLoader, opener's m_frameLoader is already cleared.
1059 auto& openerFrameLoader = m_opener == &m_frame ? *this : m_opener->loader();
1060 openerFrameLoader.m_openedFrames.remove(&m_frame);
1063 opener->loader().m_openedFrames.add(&m_frame);
1064 if (auto* page = m_frame.page())
1065 page->setOpenedByDOMWithOpener();
1069 if (m_frame.document())
1070 m_frame.document()->initSecurityContext();
1073 // FIXME: This does not belong in FrameLoader!
1074 void FrameLoader::handleFallbackContent()
1076 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
1077 if (!is<HTMLObjectElement>(owner))
1079 downcast<HTMLObjectElement>(*owner).renderFallbackContent();
1082 void FrameLoader::provisionalLoadStarted()
1084 if (m_stateMachine.firstLayoutDone())
1085 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1086 m_frame.navigationScheduler().cancel(NewLoadInProgress::Yes);
1087 m_client.provisionalLoadStarted();
1089 if (m_frame.isMainFrame()) {
1090 tracePoint(MainResourceLoadDidStartProvisional);
1092 if (auto* page = m_frame.page())
1093 page->didStartProvisionalLoad();
1097 void FrameLoader::resetMultipleFormSubmissionProtection()
1099 m_submittedFormURL = URL();
1102 void FrameLoader::updateFirstPartyForCookies()
1104 if (m_frame.tree().parent())
1105 setFirstPartyForCookies(m_frame.tree().parent()->document()->firstPartyForCookies());
1107 setFirstPartyForCookies(m_frame.document()->url());
1110 void FrameLoader::setFirstPartyForCookies(const URL& url)
1112 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
1113 frame->document()->setFirstPartyForCookies(url);
1115 RegistrableDomain registrableDomain(url);
1116 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame)) {
1117 if (SecurityPolicy::shouldInheritSecurityOriginFromOwner(frame->document()->url()) || registrableDomain.matches(frame->document()->url()))
1118 frame->document()->setSiteForCookies(url);
1122 // This does the same kind of work that didOpenURL does, except it relies on the fact
1123 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1124 void FrameLoader::loadInSameDocument(const URL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1126 RELEASE_LOG_IF_ALLOWED("loadInSameDocument: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1128 // If we have a state object, we cannot also be a new navigation.
1129 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1131 // Update the data source's request with the new URL to fake the URL change
1132 URL oldURL = m_frame.document()->url();
1133 m_frame.document()->setURL(url);
1134 setOutgoingReferrer(url);
1135 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1136 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1137 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1138 // based on the current request. Must also happen before we openURL and displace the
1139 // scroll position, since adding the BF item will save away scroll state.
1141 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1142 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1143 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1144 // though its load is not yet done. I think this all works out OK, for one because
1145 // we have already saved away the scroll and doc state for the long slow load,
1146 // but it's not an obvious case.
1148 history().updateBackForwardListForFragmentScroll();
1151 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1153 history().updateForSameDocumentNavigation();
1155 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1157 m_frame.eventHandler().stopAutoscrollTimer();
1159 // It's important to model this as a load that starts and immediately finishes.
1160 // Otherwise, the parent frame may think we never finished loading.
1163 if (auto* ownerElement = m_frame.ownerElement()) {
1164 auto* ownerRenderer = ownerElement->renderer();
1165 auto* view = m_frame.view();
1166 if (is<RenderWidget>(ownerRenderer) && view)
1167 downcast<RenderWidget>(*ownerRenderer).setWidget(view);
1170 // We need to scroll to the fragment whether or not a hash change occurred, since
1171 // the user might have scrolled since the previous navigation.
1172 scrollToFragmentWithParentBoundary(url, isNewNavigation);
1174 m_isComplete = false;
1177 if (isNewNavigation) {
1178 // This will clear previousItem from the rest of the frame tree that didn't
1179 // doing any loading. We need to make a pass on this now, since for fragment
1180 // navigation we'll not go through a real load and reach Completed state.
1181 checkLoadComplete();
1184 m_client.dispatchDidNavigateWithinPage();
1186 m_frame.document()->statePopped(stateObject ? Ref<SerializedScriptValue> { *stateObject } : SerializedScriptValue::nullValue());
1187 m_client.dispatchDidPopStateWithinPage();
1190 m_frame.document()->enqueueHashchangeEvent(oldURL, url);
1191 m_client.dispatchDidChangeLocationWithinPage();
1194 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1195 m_client.didFinishLoad();
1198 bool FrameLoader::isComplete() const
1200 return m_isComplete;
1203 void FrameLoader::completed()
1205 Ref<Frame> protect(m_frame);
1207 for (Frame* descendant = m_frame.tree().traverseNext(&m_frame); descendant; descendant = descendant->tree().traverseNext(&m_frame))
1208 descendant->navigationScheduler().startTimer();
1210 if (Frame* parent = m_frame.tree().parent())
1211 parent->loader().checkCompleted();
1214 m_frame.view()->maintainScrollPositionAtAnchor(nullptr);
1217 void FrameLoader::started()
1219 for (Frame* frame = &m_frame; frame; frame = frame->tree().parent())
1220 frame->loader().m_isComplete = false;
1223 void FrameLoader::prepareForLoadStart()
1225 RELEASE_LOG_IF_ALLOWED("prepareForLoadStart: Starting frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1227 m_progressTracker->progressStarted();
1228 m_client.dispatchDidStartProvisionalLoad();
1230 if (AXObjectCache::accessibilityEnabled()) {
1231 if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache()) {
1232 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadType::Reload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1233 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
1238 void FrameLoader::setupForReplace()
1240 m_client.revertToProvisionalState(m_documentLoader.get());
1241 setState(FrameStateProvisional);
1242 m_provisionalDocumentLoader = m_documentLoader;
1243 m_documentLoader = nullptr;
1247 void FrameLoader::loadFrameRequest(FrameLoadRequest&& request, Event* event, RefPtr<FormState>&& formState, Optional<AdClickAttribution>&& adClickAttribution)
1249 RELEASE_LOG_IF_ALLOWED("loadFrameRequest: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1251 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1252 auto protectFrame = makeRef(m_frame);
1254 URL url = request.resourceRequest().url();
1256 ASSERT(m_frame.document());
1257 if (!request.requesterSecurityOrigin().canDisplay(url)) {
1258 reportLocalLoadFailed(&m_frame, url.stringCenterEllipsizedToLength());
1262 String argsReferrer = request.resourceRequest().httpReferrer();
1263 if (argsReferrer.isEmpty())
1264 argsReferrer = outgoingReferrer();
1266 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), url, argsReferrer);
1267 if (request.shouldSendReferrer() == NeverSendReferrer)
1268 referrer = String();
1270 FrameLoadType loadType;
1271 if (request.resourceRequest().cachePolicy() == ResourceRequestCachePolicy::ReloadIgnoringCacheData)
1272 loadType = FrameLoadType::Reload;
1273 else if (request.lockBackForwardList() == LockBackForwardList::Yes)
1274 loadType = FrameLoadType::RedirectWithLockedBackForwardList;
1276 loadType = FrameLoadType::Standard;
1278 auto completionHandler = [this, protectedFrame = makeRef(m_frame), formState = makeWeakPtr(formState.get()), frameName = request.frameName()] {
1279 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1280 // load if frame names have changed.
1281 Frame* sourceFrame = formState ? formState->sourceDocument().frame() : &m_frame;
1283 sourceFrame = &m_frame;
1284 Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(frameName);
1285 if (targetFrame && targetFrame != sourceFrame) {
1286 if (Page* page = targetFrame->page())
1287 page->chrome().focus();
1291 if (request.resourceRequest().httpMethod() == "POST")
1292 loadPostRequest(WTFMove(request), referrer, loadType, event, WTFMove(formState), WTFMove(completionHandler));
1294 loadURL(WTFMove(request), referrer, loadType, event, WTFMove(formState), WTFMove(adClickAttribution), WTFMove(completionHandler));
1297 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& currentFrame, InitiatedByMainFrame initiatedByMainFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1299 if (UserGestureIndicator::processingUserGesture())
1300 return ShouldOpenExternalURLsPolicy::ShouldAllow;
1302 if (initiatedByMainFrame == InitiatedByMainFrame::Yes)
1303 return propagatedPolicy;
1305 if (!currentFrame.isMainFrame())
1306 return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
1308 return propagatedPolicy;
1311 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& currentFrame, const FrameLoadRequest& frameLoadRequest)
1313 return shouldOpenExternalURLsPolicyToApply(currentFrame, frameLoadRequest.initiatedByMainFrame(), frameLoadRequest.shouldOpenExternalURLsPolicy());
1316 static void applyShouldOpenExternalURLsPolicyToNewDocumentLoader(Frame& frame, DocumentLoader& documentLoader, InitiatedByMainFrame initiatedByMainFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1318 documentLoader.setShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(frame, initiatedByMainFrame, propagatedPolicy));
1321 static void applyShouldOpenExternalURLsPolicyToNewDocumentLoader(Frame& frame, DocumentLoader& documentLoader, const FrameLoadRequest& frameLoadRequest)
1323 documentLoader.setShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(frame, frameLoadRequest));
1326 bool FrameLoader::isNavigationAllowed() const
1328 return m_pageDismissalEventBeingDispatched == PageDismissalType::None && !m_frame.script().willReplaceWithResultOfExecutingJavascriptURL() && NavigationDisabler::isNavigationAllowed(m_frame);
1331 bool FrameLoader::isStopLoadingAllowed() const
1333 return m_pageDismissalEventBeingDispatched == PageDismissalType::None;
1336 void FrameLoader::loadURL(FrameLoadRequest&& frameLoadRequest, const String& referrer, FrameLoadType newLoadType, Event* event, RefPtr<FormState>&& formState, Optional<AdClickAttribution>&& adClickAttribution, CompletionHandler<void()>&& completionHandler)
1338 RELEASE_LOG_IF_ALLOWED("loadURL: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1340 CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
1341 if (m_inStopAllLoaders || m_inClearProvisionalLoadForPolicyCheck)
1344 Ref<Frame> protect(m_frame);
1346 // Anchor target is ignored when the download attribute is set since it will download the hyperlink rather than follow it.
1347 String effectiveFrameName = frameLoadRequest.downloadAttribute().isNull() ? frameLoadRequest.frameName() : String();
1348 AllowNavigationToInvalidURL allowNavigationToInvalidURL = frameLoadRequest.allowNavigationToInvalidURL();
1349 NewFrameOpenerPolicy openerPolicy = frameLoadRequest.newFrameOpenerPolicy();
1350 LockHistory lockHistory = frameLoadRequest.lockHistory();
1351 bool isFormSubmission = formState;
1353 const URL& newURL = frameLoadRequest.resourceRequest().url();
1354 ResourceRequest request(newURL);
1355 if (!referrer.isEmpty()) {
1356 request.setHTTPReferrer(referrer);
1357 auto referrerOrigin = SecurityOrigin::createFromString(referrer);
1358 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1360 if (&m_frame.tree().top() != &m_frame)
1361 request.setDomainForCachePartition(m_frame.tree().top().document()->domainForCachePartition());
1363 addExtraFieldsToRequest(request, newLoadType, true);
1364 if (isReload(newLoadType))
1365 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1367 ASSERT(newLoadType != FrameLoadType::Same);
1369 // The search for a target frame is done earlier in the case of form submission.
1370 Frame* targetFrame = isFormSubmission ? nullptr : findFrameForNavigation(effectiveFrameName);
1371 if (targetFrame && targetFrame != &m_frame) {
1372 frameLoadRequest.setFrameName("_self");
1373 targetFrame->loader().loadURL(WTFMove(frameLoadRequest), referrer, newLoadType, event, WTFMove(formState), WTFMove(adClickAttribution), completionHandlerCaller.release());
1377 if (!isNavigationAllowed())
1380 NavigationAction action { frameLoadRequest.requester(), request, frameLoadRequest.initiatedByMainFrame(), newLoadType, isFormSubmission, event, frameLoadRequest.shouldOpenExternalURLsPolicy(), frameLoadRequest.downloadAttribute() };
1381 action.setLockHistory(lockHistory);
1382 action.setLockBackForwardList(frameLoadRequest.lockBackForwardList());
1383 if (adClickAttribution && m_frame.isMainFrame())
1384 action.setAdClickAttribution(WTFMove(*adClickAttribution));
1386 if (!targetFrame && !effectiveFrameName.isEmpty()) {
1387 action = action.copyWithShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(m_frame, frameLoadRequest));
1388 policyChecker().checkNewWindowPolicy(WTFMove(action), WTFMove(request), WTFMove(formState), effectiveFrameName, [this, allowNavigationToInvalidURL, openerPolicy, completionHandler = completionHandlerCaller.release()] (const ResourceRequest& request, WeakPtr<FormState>&& formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue) mutable {
1389 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
1390 completionHandler();
1395 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1397 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1398 const String& httpMethod = request.httpMethod();
1400 // Make sure to do scroll to fragment processing even if the URL is
1401 // exactly the same so pages with '#' links and DHTML side effects
1403 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1404 oldDocumentLoader->setTriggeringAction(WTFMove(action));
1405 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1406 policyChecker().stopCheck();
1407 policyChecker().setLoadType(newLoadType);
1408 RELEASE_ASSERT(!isBackForwardLoadType(newLoadType) || history().provisionalItem());
1409 policyChecker().checkNavigationPolicy(WTFMove(request), ResourceResponse { } /* redirectResponse */, oldDocumentLoader.get(), WTFMove(formState), [this, protectedFrame = makeRef(m_frame)] (const ResourceRequest& request, WeakPtr<FormState>&&, NavigationPolicyDecision navigationPolicyDecision) {
1410 continueFragmentScrollAfterNavigationPolicy(request, navigationPolicyDecision == NavigationPolicyDecision::ContinueLoad);
1411 }, PolicyDecisionMode::Synchronous);
1415 // Must grab this now, since this load may stop the previous load and clear this flag.
1416 bool isRedirect = m_quickRedirectComing;
1417 #if USE(SYSTEM_PREVIEW)
1418 bool isSystemPreview = frameLoadRequest.isSystemPreview();
1419 request.setSystemPreview(isSystemPreview);
1420 if (isSystemPreview)
1421 request.setSystemPreviewRect(frameLoadRequest.systemPreviewRect());
1423 loadWithNavigationAction(request, WTFMove(action), lockHistory, newLoadType, WTFMove(formState), allowNavigationToInvalidURL, frameLoadRequest.downloadAttribute(), [this, isRedirect, sameURL, newLoadType, protectedFrame = makeRef(m_frame), completionHandler = completionHandlerCaller.release()] () mutable {
1425 m_quickRedirectComing = false;
1426 if (m_provisionalDocumentLoader)
1427 m_provisionalDocumentLoader->setIsClientRedirect(true);
1428 else if (m_policyDocumentLoader)
1429 m_policyDocumentLoader->setIsClientRedirect(true);
1430 } else if (sameURL && !isReload(newLoadType)) {
1431 // Example of this case are sites that reload the same URL with a different cookie
1432 // driving the generated content, or a master frame with links that drive a target
1433 // frame, where the user has clicked on the same link repeatedly.
1434 m_loadType = FrameLoadType::Same;
1436 completionHandler();
1440 SubstituteData FrameLoader::defaultSubstituteDataForURL(const URL& url)
1442 if (!shouldTreatURLAsSrcdocDocument(url))
1443 return SubstituteData();
1444 auto& srcdoc = m_frame.ownerElement()->attributeWithoutSynchronization(srcdocAttr);
1445 ASSERT(!srcdoc.isNull());
1446 CString encodedSrcdoc = srcdoc.string().utf8();
1448 ResourceResponse response(URL(), "text/html"_s, encodedSrcdoc.length(), "UTF-8"_s);
1449 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1452 void FrameLoader::load(FrameLoadRequest&& request)
1454 RELEASE_LOG_IF_ALLOWED("load (FrameLoadRequest): frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1456 if (m_inStopAllLoaders || m_inClearProvisionalLoadForPolicyCheck)
1459 if (!request.frameName().isEmpty()) {
1460 Frame* frame = findFrameForNavigation(request.frameName());
1462 request.setShouldCheckNewWindowPolicy(false);
1463 if (&frame->loader() != this) {
1464 frame->loader().load(WTFMove(request));
1470 if (request.shouldCheckNewWindowPolicy()) {
1471 NavigationAction action { request.requester(), request.resourceRequest(), InitiatedByMainFrame::Unknown, NavigationType::Other, request.shouldOpenExternalURLsPolicy() };
1472 policyChecker().checkNewWindowPolicy(WTFMove(action), WTFMove(request.resourceRequest()), { }, request.frameName(), [this] (const ResourceRequest& request, WeakPtr<FormState>&& formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue) {
1473 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress);
1479 if (!request.hasSubstituteData())
1480 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1482 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request.resourceRequest(), request.substituteData());
1483 loader->setAllowsWebArchiveForMainFrame(request.isRequestFromClientOrUserInput());
1484 addSameSiteInfoToRequestIfNeeded(loader->request());
1485 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, request);
1487 if (request.shouldTreatAsContinuingLoad()) {
1488 loader->setClientRedirectSourceForHistory(request.clientRedirectSourceForHistory());
1489 if (request.lockBackForwardList() == LockBackForwardList::Yes) {
1490 loader->setIsClientRedirect(true);
1491 m_loadType = FrameLoadType::RedirectWithLockedBackForwardList;
1495 SetForScope<LoadContinuingState> continuingLoadGuard(m_currentLoadContinuingState, request.shouldTreatAsContinuingLoad() ? LoadContinuingState::ContinuingWithRequest : LoadContinuingState::NotContinuing);
1499 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, NavigationAction&& action, LockHistory lockHistory, FrameLoadType type, RefPtr<FormState>&& formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL, const String& downloadAttribute, CompletionHandler<void()>&& completionHandler)
1501 RELEASE_LOG_IF_ALLOWED("loadWithNavigationAction: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1503 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1504 loader->setDownloadAttribute(downloadAttribute);
1505 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, action.initiatedByMainFrame(), action.shouldOpenExternalURLsPolicy());
1507 if (lockHistory == LockHistory::Yes && m_documentLoader)
1508 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1510 loader->setTriggeringAction(WTFMove(action));
1511 if (m_documentLoader)
1512 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1514 loadWithDocumentLoader(loader.ptr(), type, WTFMove(formState), allowNavigationToInvalidURL, ShouldTreatAsContinuingLoad::No, WTFMove(completionHandler));
1517 void FrameLoader::load(DocumentLoader& newDocumentLoader)
1519 RELEASE_LOG_IF_ALLOWED("load (DocumentLoader): frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1521 ResourceRequest& r = newDocumentLoader.request();
1522 addExtraFieldsToMainResourceRequest(r);
1525 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader.originalRequest().url())) {
1526 r.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1527 type = FrameLoadType::Same;
1528 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader.unreachableURL()) && isReload(m_loadType))
1530 else if (m_loadType == FrameLoadType::RedirectWithLockedBackForwardList && ((!newDocumentLoader.unreachableURL().isEmpty() && newDocumentLoader.substituteData().isValid()) || shouldTreatCurrentLoadAsContinuingLoad()))
1531 type = FrameLoadType::RedirectWithLockedBackForwardList;
1533 type = FrameLoadType::Standard;
1535 if (m_documentLoader)
1536 newDocumentLoader.setOverrideEncoding(m_documentLoader->overrideEncoding());
1538 // When we loading alternate content for an unreachable URL that we're
1539 // visiting in the history list, we treat it as a reload so the history list
1540 // is appropriately maintained.
1542 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadType::Reload" ...
1543 // shouldn't a more explicit type of reload be defined, that means roughly
1544 // "load without affecting history" ?
1545 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1546 // shouldReloadToHandleUnreachableURL returns true only when the original load type is back-forward.
1547 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1548 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1549 history().saveDocumentAndScrollState();
1551 ASSERT(type == FrameLoadType::Standard);
1552 type = FrameLoadType::Reload;
1555 loadWithDocumentLoader(&newDocumentLoader, type, nullptr, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No);
1558 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, RefPtr<FormState>&& formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL, ShouldTreatAsContinuingLoad, CompletionHandler<void()>&& completionHandler)
1560 RELEASE_LOG_IF_ALLOWED("loadWithDocumentLoader: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1562 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1563 Ref<Frame> protect(m_frame);
1565 CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
1567 ASSERT(m_client.hasWebView());
1569 // Unfortunately the view must be non-nil, this is ultimately due
1570 // to parser requiring a FrameView. We should fix this dependency.
1572 ASSERT(m_frame.view());
1574 if (!isNavigationAllowed())
1577 if (m_frame.document())
1578 m_previousURL = m_frame.document()->url();
1580 const URL& newURL = loader->request().url();
1582 // Only the first iframe navigation or the first iframe navigation after about:blank should be reported.
1583 // https://www.w3.org/TR/resource-timing-2/#resources-included-in-the-performanceresourcetiming-interface
1584 if (m_shouldReportResourceTimingToParentFrame && !m_previousURL.isNull() && m_previousURL != WTF::blankURL())
1585 m_shouldReportResourceTimingToParentFrame = false;
1587 // Log main frame navigation types.
1588 if (m_frame.isMainFrame()) {
1589 if (auto* page = m_frame.page()) {
1590 RELEASE_LOG_IF_ALLOWED("loadWithDocumentLoader: main frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1591 page->mainFrameLoadStarted(newURL, type);
1592 page->performanceLogging().didReachPointOfInterest(PerformanceLogging::MainFrameLoadStarted);
1596 policyChecker().setLoadType(type);
1597 RELEASE_ASSERT(!isBackForwardLoadType(type) || history().provisionalItem());
1598 bool isFormSubmission = formState;
1600 const String& httpMethod = loader->request().httpMethod();
1602 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker().loadType(), newURL)) {
1603 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1604 NavigationAction action { *m_frame.document(), loader->request(), InitiatedByMainFrame::Unknown, policyChecker().loadType(), isFormSubmission };
1606 oldDocumentLoader->setTriggeringAction(WTFMove(action));
1607 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1608 policyChecker().stopCheck();
1609 RELEASE_ASSERT(!isBackForwardLoadType(policyChecker().loadType()) || history().provisionalItem());
1610 policyChecker().checkNavigationPolicy(ResourceRequest(loader->request()), ResourceResponse { } /* redirectResponse */, oldDocumentLoader.get(), WTFMove(formState), [this, protectedFrame = makeRef(m_frame)] (const ResourceRequest& request, WeakPtr<FormState>&&, NavigationPolicyDecision navigationPolicyDecision) {
1611 continueFragmentScrollAfterNavigationPolicy(request, navigationPolicyDecision == NavigationPolicyDecision::ContinueLoad);
1612 }, PolicyDecisionMode::Synchronous);
1616 if (Frame* parent = m_frame.tree().parent())
1617 loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
1619 policyChecker().stopCheck();
1620 setPolicyDocumentLoader(loader);
1621 if (loader->triggeringAction().isEmpty())
1622 loader->setTriggeringAction({ *m_frame.document(), loader->request(), InitiatedByMainFrame::Unknown, policyChecker().loadType(), isFormSubmission });
1624 if (Element* ownerElement = m_frame.ownerElement()) {
1625 // We skip dispatching the beforeload event if we've already
1626 // committed a real document load because the event would leak
1627 // subsequent activity by the frame which the parent frame isn't
1628 // supposed to learn. For example, if the child frame navigated to
1629 // a new URL, the parent frame shouldn't learn the URL.
1630 if (!m_stateMachine.committedFirstRealDocumentLoad()
1631 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1632 continueLoadAfterNavigationPolicy(loader->request(), formState.get(), NavigationPolicyDecision::IgnoreLoad, allowNavigationToInvalidURL);
1637 m_frame.navigationScheduler().cancel(NewLoadInProgress::Yes);
1639 if (shouldTreatCurrentLoadAsContinuingLoad()) {
1640 continueLoadAfterNavigationPolicy(loader->request(), formState.get(), NavigationPolicyDecision::ContinueLoad, allowNavigationToInvalidURL);
1644 RELEASE_ASSERT(!isBackForwardLoadType(policyChecker().loadType()) || history().provisionalItem());
1645 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, NavigationPolicyDecision navigationPolicyDecision) mutable {
1646 continueLoadAfterNavigationPolicy(request, formState.get(), navigationPolicyDecision, allowNavigationToInvalidURL);
1647 completionHandler();
1648 }, PolicyDecisionMode::Asynchronous);
1651 void FrameLoader::clearProvisionalLoadForPolicyCheck()
1653 if (!m_policyDocumentLoader || !m_provisionalDocumentLoader || m_inClearProvisionalLoadForPolicyCheck)
1656 SetForScope<bool> change(m_inClearProvisionalLoadForPolicyCheck, true);
1657 m_provisionalDocumentLoader->stopLoading();
1658 setProvisionalDocumentLoader(nullptr);
1661 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1663 ASSERT(!url.isEmpty());
1667 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to load local resource: " + url);
1670 void FrameLoader::reportBlockedPortFailed(Frame* frame, const String& url)
1672 ASSERT(!url.isEmpty());
1676 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to use restricted network port: " + url);
1679 void FrameLoader::reportAuthenticationChallengeBlocked(Frame* frame, const URL& url, const String& reason)
1684 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, makeString("Blocked ", url.stringCenterEllipsizedToLength(), " from asking for credentials because ", reason, '.'));
1687 const ResourceRequest& FrameLoader::initialRequest() const
1689 return activeDocumentLoader()->originalRequest();
1692 bool FrameLoader::willLoadMediaElementURL(URL& url, Node& initiatorNode)
1694 #if PLATFORM(IOS_FAMILY)
1695 // MobileStore depends on the iOS 4.0 era client delegate method because webView:resource:willSendRequest:redirectResponse:fromDataSource
1696 // doesn't let them tell when a load request is coming from a media element. See <rdar://problem/8266916> for more details.
1697 if (IOSApplication::isMobileStore())
1698 return m_client.shouldLoadMediaElementURL(url);
1701 ResourceRequest request(url);
1702 request.setInspectorInitiatorNodeIdentifier(InspectorInstrumentation::identifierForNode(initiatorNode));
1704 unsigned long identifier;
1705 ResourceError error;
1706 requestFromDelegate(request, identifier, error);
1707 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String()), 0, -1, -1, error);
1709 url = request.url();
1711 return error.isNull();
1714 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader& docLoader)
1716 URL unreachableURL = docLoader.unreachableURL();
1718 if (unreachableURL.isEmpty())
1721 if (!isBackForwardLoadType(policyChecker().loadType()))
1724 // We only treat unreachableURLs specially during the delegate callbacks
1725 // for provisional load errors and navigation policy decisions. The former
1726 // case handles well-formed URLs that can't be loaded, and the latter
1727 // case handles malformed URLs and unknown schemes. Loading alternate content
1728 // at other times behaves like a standard load.
1729 if (policyChecker().delegateIsDecidingNavigationPolicy() || policyChecker().delegateIsHandlingUnimplementablePolicy())
1730 return m_policyDocumentLoader && unreachableURL == m_policyDocumentLoader->request().url();
1732 return unreachableURL == m_provisionalLoadErrorBeingHandledURL;
1735 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1737 if (!m_documentLoader)
1740 RELEASE_LOG_IF_ALLOWED("reloadWithOverrideEncoding: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1742 ResourceRequest request = m_documentLoader->request();
1743 URL unreachableURL = m_documentLoader->unreachableURL();
1744 if (!unreachableURL.isEmpty())
1745 request.setURL(unreachableURL);
1747 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1748 // We should ask the user for confirmation in this case.
1749 request.setCachePolicy(ResourceRequestCachePolicy::ReturnCacheDataElseLoad);
1751 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1752 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, InitiatedByMainFrame::Unknown, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1754 setPolicyDocumentLoader(loader.ptr());
1756 loader->setOverrideEncoding(encoding);
1758 loadWithDocumentLoader(loader.ptr(), FrameLoadType::Reload, { }, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No);
1761 void FrameLoader::reload(OptionSet<ReloadOption> options)
1763 if (!m_documentLoader)
1766 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1767 // Reloading in this case will lose the current contents (see 4151001).
1768 if (m_documentLoader->request().url().isEmpty())
1771 RELEASE_LOG_IF_ALLOWED("reload: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1773 // Replace error-page URL with the URL we were trying to reach.
1774 ResourceRequest initialRequest = m_documentLoader->request();
1775 URL unreachableURL = m_documentLoader->unreachableURL();
1776 if (!unreachableURL.isEmpty())
1777 initialRequest.setURL(unreachableURL);
1779 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1780 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1781 Ref<DocumentLoader> loader = m_client.createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1782 loader->setAllowsWebArchiveForMainFrame(m_documentLoader->allowsWebArchiveForMainFrame());
1783 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(m_frame, loader, InitiatedByMainFrame::Unknown, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1785 loader->setUserContentExtensionsEnabled(!options.contains(ReloadOption::DisableContentBlockers));
1787 ResourceRequest& request = loader->request();
1789 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1790 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
1792 addSameSiteInfoToRequestIfNeeded(request);
1794 // If we're about to re-post, set up action so the application can warn the user.
1795 if (request.httpMethod() == "POST")
1796 loader->setTriggeringAction({ *m_frame.document(), request, InitiatedByMainFrame::Unknown, NavigationType::FormResubmitted });
1798 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1800 auto frameLoadTypeForReloadOptions = [] (auto options) {
1801 if (options & ReloadOption::FromOrigin)
1802 return FrameLoadType::ReloadFromOrigin;
1803 if (options & ReloadOption::ExpiredOnly)
1804 return FrameLoadType::ReloadExpiredOnly;
1805 return FrameLoadType::Reload;
1808 loadWithDocumentLoader(loader.ptr(), frameLoadTypeForReloadOptions(options), { }, AllowNavigationToInvalidURL::Yes, ShouldTreatAsContinuingLoad::No);
1811 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1813 if (m_frame.document() && m_frame.document()->pageCacheState() == Document::InPageCache)
1816 if (!isStopLoadingAllowed())
1819 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1820 if (m_inStopAllLoaders)
1823 // This method might dispatch events.
1824 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
1826 // Calling stopLoading() on the provisional document loader can blow away
1827 // the frame from underneath.
1828 Ref<Frame> protect(m_frame);
1830 m_inStopAllLoaders = true;
1832 policyChecker().stopCheck();
1834 // If no new load is in progress, we should clear the provisional item from history
1835 // before we call stopLoading.
1836 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1837 history().setProvisionalItem(nullptr);
1839 for (RefPtr<Frame> child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
1840 child->loader().stopAllLoaders(clearProvisionalItemPolicy);
1841 if (m_provisionalDocumentLoader)
1842 m_provisionalDocumentLoader->stopLoading();
1843 if (m_documentLoader)
1844 m_documentLoader->stopLoading();
1846 setProvisionalDocumentLoader(nullptr);
1848 m_inStopAllLoaders = false;
1851 void FrameLoader::stopAllLoadersAndCheckCompleteness()
1855 if (!m_checkTimer.isActive())
1858 m_checkTimer.stop();
1859 m_checkingLoadCompleteForDetachment = true;
1860 checkCompletenessNow();
1861 m_checkingLoadCompleteForDetachment = false;
1864 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1866 // Calling stopAllLoaders can cause the frame to be deallocated, including the frame loader.
1867 Ref<Frame> protectedFrame(m_frame);
1871 #if PLATFORM(IOS_FAMILY)
1872 // Lay out immediately when stopping to immediately clear the old page if we just committed this one
1873 // but haven't laid out/painted yet.
1874 // FIXME: Is this behavior specific to iOS? Or should we expose a setting to toggle this behavior?
1875 if (m_frame.view() && !m_frame.view()->didFirstLayout())
1876 m_frame.view()->layoutContext().layout();
1879 if (deferCheckLoadComplete)
1880 scheduleCheckLoadComplete();
1881 else if (m_frame.page())
1882 checkLoadComplete();
1885 DocumentLoader* FrameLoader::activeDocumentLoader() const
1887 if (m_state == FrameStateProvisional)
1888 return m_provisionalDocumentLoader.get();
1889 return m_documentLoader.get();
1892 bool FrameLoader::isLoading() const
1894 DocumentLoader* docLoader = activeDocumentLoader();
1897 return docLoader->isLoading();
1900 bool FrameLoader::frameHasLoaded() const
1902 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1905 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1907 if (!loader && !m_documentLoader)
1910 if (loader == m_documentLoader)
1913 ASSERT(loader != m_documentLoader);
1914 ASSERT(!loader || loader->frameLoader() == this);
1916 m_client.prepareForDataSourceReplacement();
1919 // detachChildren() can trigger this frame's unload event, and therefore
1920 // script can run and do just about anything. For example, an unload event that calls
1921 // document.write("") on its parent frame can lead to a recursive detachChildren()
1922 // invocation for this frame. In that case, we can end up at this point with a
1923 // loader that hasn't been deleted but has been detached from its frame. Such a
1924 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1925 // state if we try to use it.
1926 if (loader && !loader->frame())
1929 if (m_documentLoader)
1930 m_documentLoader->detachFromFrame();
1932 m_documentLoader = loader;
1935 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1937 if (m_policyDocumentLoader == loader)
1941 loader->attachToFrame(m_frame);
1942 if (m_policyDocumentLoader
1943 && m_policyDocumentLoader != m_provisionalDocumentLoader
1944 && m_policyDocumentLoader != m_documentLoader)
1945 m_policyDocumentLoader->detachFromFrame();
1947 m_policyDocumentLoader = loader;
1950 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1952 ASSERT(!loader || !m_provisionalDocumentLoader);
1953 ASSERT(!loader || loader->frameLoader() == this);
1955 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1956 m_provisionalDocumentLoader->detachFromFrame();
1958 m_provisionalDocumentLoader = loader;
1961 void FrameLoader::setState(FrameState newState)
1963 FrameState oldState = m_state;
1966 if (newState == FrameStateProvisional)
1967 provisionalLoadStarted();
1968 else if (newState == FrameStateComplete) {
1969 frameLoadCompleted();
1970 if (m_documentLoader)
1971 m_documentLoader->stopRecordingResponses();
1972 if (m_frame.isMainFrame() && oldState != newState) {
1973 RELEASE_LOG_IF_ALLOWED("setState: main frame load completed (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1974 m_frame.page()->performanceLogging().didReachPointOfInterest(PerformanceLogging::MainFrameLoadCompleted);
1979 void FrameLoader::clearProvisionalLoad()
1981 setProvisionalDocumentLoader(nullptr);
1982 m_progressTracker->progressCompleted();
1983 setState(FrameStateComplete);
1986 void FrameLoader::commitProvisionalLoad()
1988 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1989 Ref<Frame> protect(m_frame);
1991 std::unique_ptr<CachedPage> cachedPage;
1992 if (m_loadingFromCachedPage && history().provisionalItem())
1993 cachedPage = PageCache::singleton().take(*history().provisionalItem(), m_frame.page());
1995 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(),
1996 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
1997 pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>", cachedPage.get());
1999 willTransitionToCommitted();
2001 if (!m_frame.tree().parent() && history().currentItem() && history().currentItem() != history().provisionalItem()) {
2002 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
2003 // We are doing this here because we know for sure that a new page is about to be loaded.
2004 PageCache::singleton().addIfCacheable(*history().currentItem(), m_frame.page());
2006 WebCore::jettisonExpensiveObjectsOnTopLevelNavigation();
2009 if (m_loadType != FrameLoadType::Replace)
2010 closeOldDataSources();
2012 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
2013 m_client.makeRepresentation(pdl.get());
2015 transitionToCommitted(cachedPage.get());
2017 if (pdl && m_documentLoader) {
2018 // Check if the destination page is allowed to access the previous page's timing information.
2019 Ref<SecurityOrigin> securityOrigin(SecurityOrigin::create(pdl->request().url()));
2020 m_documentLoader->timing().setHasSameOriginAsPreviousDocument(securityOrigin.get().canRequest(m_previousURL));
2023 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
2024 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2025 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
2026 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
2027 if (m_sentRedirectNotification)
2028 clientRedirectCancelledOrFinished(NewLoadInProgress::No);
2030 if (cachedPage && cachedPage->document()) {
2031 #if PLATFORM(IOS_FAMILY)
2032 // FIXME: CachedPage::restore() would dispatch viewport change notification. However UIKit expects load
2033 // commit to happen before any changes to viewport arguments and dealing with this there is difficult.
2034 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(true);
2036 willRestoreFromCachedPage();
2038 // Start request for the main resource and dispatch didReceiveResponse before the load is committed for
2039 // consistency with all other loads. See https://bugs.webkit.org/show_bug.cgi?id=150927.
2040 ResourceError mainResouceError;
2041 unsigned long mainResourceIdentifier;
2042 ResourceRequest mainResourceRequest(cachedPage->documentLoader()->request());
2043 requestFromDelegate(mainResourceRequest, mainResourceIdentifier, mainResouceError);
2044 notifier().dispatchDidReceiveResponse(cachedPage->documentLoader(), mainResourceIdentifier, cachedPage->documentLoader()->response());
2046 Optional<HasInsecureContent> hasInsecureContent = cachedPage->cachedMainFrame()->hasInsecureContent();
2048 dispatchDidCommitLoad(hasInsecureContent);
2050 // FIXME: This API should be turned around so that we ground CachedPage into the Page.
2051 cachedPage->restore(*m_frame.page());
2053 #if PLATFORM(IOS_FAMILY)
2054 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(false);
2055 m_frame.page()->chrome().dispatchViewportPropertiesDidChange(m_frame.page()->viewportArguments());
2057 m_frame.page()->chrome().dispatchDisabledAdaptationsDidChange(m_frame.page()->disabledAdaptations());
2059 auto& title = m_documentLoader->title();
2060 if (!title.string.isNull())
2061 m_client.dispatchDidReceiveTitle(title);
2063 // Send remaining notifications for the main resource.
2064 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), mainResourceIdentifier, mainResourceRequest, ResourceResponse(),
2065 nullptr, static_cast<int>(m_documentLoader->response().expectedContentLength()), 0, mainResouceError);
2071 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame.tree().uniqueName().string().utf8().data(),
2072 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
2074 if (m_loadType == FrameLoadType::Standard && m_documentLoader && m_documentLoader->isClientRedirect())
2075 history().updateForClientRedirect();
2077 if (m_loadingFromCachedPage) {
2078 // Note, didReceiveDocType is expected to be called for cached pages. See <rdar://problem/5906758> for more details.
2079 if (auto* page = m_frame.page())
2080 page->chrome().didReceiveDocType(m_frame);
2081 m_frame.document()->resume(ReasonForSuspension::PageCache);
2083 // Force a layout to update view size and thereby update scrollbars.
2084 #if PLATFORM(IOS_FAMILY)
2085 if (!m_client.forceLayoutOnRestoreFromPageCache())
2086 m_frame.view()->forceLayout();
2088 m_frame.view()->forceLayout();
2091 // Main resource delegates were already sent, so we skip the first response here.
2092 for (unsigned i = 1; i < m_documentLoader->responses().size(); ++i) {
2093 const auto& response = m_documentLoader->responses()[i];
2094 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
2095 ResourceError error;
2096 unsigned long identifier;
2097 ResourceRequest request(response.url());
2098 requestFromDelegate(request, identifier, error);
2099 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
2100 // However, with today's computers and networking speeds, this won't happen in practice.
2101 // Could be an issue with a giant local file.
2102 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
2105 // FIXME: Why only this frame and not parent frames?
2106 checkLoadCompleteForThisFrame();
2110 void FrameLoader::transitionToCommitted(CachedPage* cachedPage)
2112 ASSERT(m_client.hasWebView());
2113 ASSERT(m_state == FrameStateProvisional);
2115 if (m_state != FrameStateProvisional)
2118 if (FrameView* view = m_frame.view()) {
2119 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
2120 scrollAnimator->cancelAnimations();
2123 m_client.setCopiesOnScroll();
2124 history().updateForCommit();
2126 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
2127 // JavaScript. If the script initiates a new load, we need to abandon the current load,
2128 // or the two will stomp each other.
2129 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
2130 if (m_documentLoader)
2132 if (pdl != m_provisionalDocumentLoader)
2135 if (m_documentLoader)
2136 m_documentLoader->stopLoadingSubresources();
2137 if (m_documentLoader)
2138 m_documentLoader->stopLoadingPlugIns();
2140 // Setting our document loader invokes the unload event handler of our child frames.
2141 // Script can do anything. If the script initiates a new load, we need to abandon the
2142 // current load or the two will stomp each other.
2143 setDocumentLoader(m_provisionalDocumentLoader.get());
2144 if (pdl != m_provisionalDocumentLoader)
2146 setProvisionalDocumentLoader(nullptr);
2148 // Nothing else can interrupt this commit - set the Provisional->Committed transition in stone
2149 setState(FrameStateCommittedPage);
2151 // Handle adding the URL to the back/forward list.
2152 DocumentLoader* dl = m_documentLoader.get();
2154 switch (m_loadType) {
2155 case FrameLoadType::Forward:
2156 case FrameLoadType::Back:
2157 case FrameLoadType::IndexedBackForward:
2158 if (m_frame.page()) {
2159 // If the first load within a frame is a navigation within a back/forward list that was attached
2160 // without any of the items being loaded then we need to update the history in a similar manner as
2161 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
2162 if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame.isMainFrame())
2163 history().updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
2165 history().updateForBackForwardNavigation();
2167 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
2168 if (history().currentItem() && !cachedPage)
2169 m_pendingStateObject = history().currentItem()->stateObject();
2171 // Create a document view for this document, or used the cached view.
2173 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
2174 ASSERT(cachedDocumentLoader);
2175 cachedDocumentLoader->attachToFrame(m_frame);
2176 m_client.transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
2178 m_client.transitionToCommittedForNewPage();
2182 case FrameLoadType::Reload:
2183 case FrameLoadType::ReloadFromOrigin:
2184 case FrameLoadType::ReloadExpiredOnly:
2185 case FrameLoadType::Same:
2186 case FrameLoadType::Replace:
2187 history().updateForReload();
2188 m_client.transitionToCommittedForNewPage();
2191 case FrameLoadType::Standard:
2192 history().updateForStandardLoad();
2194 m_frame.view()->setScrollbarsSuppressed(true);
2195 m_client.transitionToCommittedForNewPage();
2198 case FrameLoadType::RedirectWithLockedBackForwardList:
2199 history().updateForRedirectWithLockedBackForwardList();
2200 m_client.transitionToCommittedForNewPage();
2204 m_documentLoader->writer().setMIMEType(dl->responseMIMEType());
2206 // Tell the client we've committed this URL.
2207 ASSERT(m_frame.view());
2209 if (m_stateMachine.creatingInitialEmptyDocument())
2212 if (!m_stateMachine.committedFirstRealDocumentLoad())
2213 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
2216 void FrameLoader::clientRedirectCancelledOrFinished(NewLoadInProgress newLoadInProgress)
2218 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
2219 // the redirect succeeded. We should either rename this API, or add a new method, like
2220 // -webView:didFinishClientRedirectForFrame:
2221 m_client.dispatchDidCancelClientRedirect();
2223 if (newLoadInProgress == NewLoadInProgress::No)
2224 m_quickRedirectComing = false;
2226 m_sentRedirectNotification = false;
2229 void FrameLoader::clientRedirected(const URL& url, double seconds, WallTime fireDate, LockBackForwardList lockBackForwardList)
2231 m_client.dispatchWillPerformClientRedirect(url, seconds, fireDate, lockBackForwardList);
2233 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
2234 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
2235 m_sentRedirectNotification = true;
2237 // If a "quick" redirect comes in, we set a special mode so we treat the next
2238 // load as part of the original navigation. If we don't have a document loader, we have
2239 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
2240 // Loads triggered by JavaScript form submissions never count as quick redirects.
2241 m_quickRedirectComing = (lockBackForwardList == LockBackForwardList::Yes || history().currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
2244 bool FrameLoader::shouldReload(const URL& currentURL, const URL& destinationURL)
2246 // This function implements the rule: "Don't reload if navigating by fragment within
2247 // the same URL, but do reload if going to a new URL or to the same URL with no
2248 // fragment identifier at all."
2249 if (!destinationURL.hasFragmentIdentifier())
2251 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
2254 void FrameLoader::closeOldDataSources()
2256 // FIXME: Is it important for this traversal to be postorder instead of preorder?
2257 // If so, add helpers for postorder traversal, and use them. If not, then lets not
2258 // use a recursive algorithm here.
2259 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
2260 child->loader().closeOldDataSources();
2262 if (m_documentLoader)
2263 m_client.dispatchWillClose();
2265 m_client.setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2268 void FrameLoader::willRestoreFromCachedPage()
2270 ASSERT(!m_frame.tree().parent());
2271 ASSERT(m_frame.page());
2272 ASSERT(m_frame.isMainFrame());
2274 m_frame.navigationScheduler().cancel();
2276 // We still have to close the previous part page.
2279 // Delete old status bar messages (if it _was_ activated on last URL).
2280 if (m_frame.script().canExecuteScripts(NotAboutToExecuteScript)) {
2281 DOMWindow* window = m_frame.document()->domWindow();
2282 window->setStatus(String());
2283 window->setDefaultStatus(String());
2287 void FrameLoader::open(CachedFrameBase& cachedFrame)
2289 m_isComplete = false;
2291 // Don't re-emit the load event.
2292 m_didCallImplicitClose = true;
2294 URL url = cachedFrame.url();
2296 // FIXME: I suspect this block of code doesn't do anything.
2297 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2301 auto document = makeRef(*cachedFrame.document());
2302 ASSERT(document->domWindow());
2304 clear(document.ptr(), true, true, cachedFrame.isMainFrame());
2306 document->attachToCachedFrame(cachedFrame);
2307 document->setPageCacheState(Document::NotInPageCache);
2309 m_needsClear = true;
2310 m_isComplete = false;
2311 m_didCallImplicitClose = false;
2312 setOutgoingReferrer(url);
2314 FrameView* view = cachedFrame.view();
2316 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2318 view->setWasScrolledByUser(false);
2320 Optional<IntRect> previousViewFrameRect = m_frame.view() ? m_frame.view()->frameRect() : Optional<IntRect>(WTF::nullopt);
2321 m_frame.setView(view);
2323 // Use the previous ScrollView's frame rect.
2324 if (previousViewFrameRect)
2325 view->setFrameRect(previousViewFrameRect.value());
2328 // Setting the document builds the render tree and runs post style resolution callbacks that can do anything,
2329 // including loading a child frame before its been re-attached to the frame tree as part of this restore.
2330 // For example, the HTML object element may load its content into a frame in a post style resolution callback.
2331 Style::PostResolutionCallbackDisabler disabler(document.get());
2332 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2333 NavigationDisabler disableNavigation { &m_frame };
2335 m_frame.setDocument(document.copyRef());
2337 document->domWindow()->resumeFromPageCache();
2339 updateFirstPartyForCookies();
2341 cachedFrame.restore();
2344 bool FrameLoader::isHostedByObjectElement() const
2346 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
2347 return owner && owner->hasTagName(objectTag);
2350 bool FrameLoader::isReplacing() const
2352 return m_loadType == FrameLoadType::Replace;
2355 void FrameLoader::setReplacing()
2357 m_loadType = FrameLoadType::Replace;
2360 bool FrameLoader::subframeIsLoading() const
2362 // It's most likely that the last added frame is the last to load so we walk backwards.
2363 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling()) {
2364 FrameLoader& childLoader = child->loader();
2365 DocumentLoader* documentLoader = childLoader.documentLoader();
2366 if (documentLoader && documentLoader->isLoadingInAPISense())
2368 documentLoader = childLoader.provisionalDocumentLoader();
2369 if (documentLoader && documentLoader->isLoadingInAPISense())
2371 documentLoader = childLoader.policyDocumentLoader();
2378 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2380 m_client.willChangeTitle(loader);
2383 FrameLoadType FrameLoader::loadType() const
2388 CachePolicy FrameLoader::subresourceCachePolicy(const URL& url) const
2390 if (Page* page = m_frame.page()) {
2391 if (page->isResourceCachingDisabled())
2392 return CachePolicyReload;
2396 return CachePolicyVerify;
2398 if (m_loadType == FrameLoadType::ReloadFromOrigin)
2399 return CachePolicyReload;
2401 if (Frame* parentFrame = m_frame.tree().parent()) {
2402 CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy(url);
2403 if (parentCachePolicy != CachePolicyVerify)
2404 return parentCachePolicy;
2407 switch (m_loadType) {
2408 case FrameLoadType::Reload:
2409 return CachePolicyRevalidate;
2410 case FrameLoadType::Back:
2411 case FrameLoadType::Forward:
2412 case FrameLoadType::IndexedBackForward:
2413 return CachePolicyHistoryBuffer;
2414 case FrameLoadType::ReloadFromOrigin:
2415 ASSERT_NOT_REACHED(); // Already handled above.
2416 return CachePolicyReload;
2417 case FrameLoadType::RedirectWithLockedBackForwardList:
2418 case FrameLoadType::Replace:
2419 case FrameLoadType::Same:
2420 case FrameLoadType::Standard:
2421 return CachePolicyVerify;
2422 case FrameLoadType::ReloadExpiredOnly:
2423 // We know about expiration for HTTP and data. Do a normal reload otherwise.
2424 if (!url.protocolIsInHTTPFamily() && !url.protocolIsData())
2425 return CachePolicyReload;
2426 return CachePolicyVerify;
2429 RELEASE_ASSERT_NOT_REACHED();
2430 return CachePolicyVerify;
2433 void FrameLoader::dispatchDidFailProvisionalLoad(DocumentLoader& provisionalDocumentLoader, const ResourceError& error)
2435 m_provisionalLoadErrorBeingHandledURL = provisionalDocumentLoader.url();
2437 #if ENABLE(CONTENT_FILTERING)
2438 auto contentFilter = provisionalDocumentLoader.contentFilter();
2439 auto contentFilterWillContinueLoading = false;
2442 auto willContinueLoading = WillContinueLoading::No;
2443 if (history().provisionalItem())
2444 willContinueLoading = WillContinueLoading::Yes;
2445 #if ENABLE(CONTENT_FILTERING)
2446 if (contentFilter && contentFilter->willHandleProvisionalLoadFailure(error)) {
2447 willContinueLoading = WillContinueLoading::Yes;
2448 contentFilterWillContinueLoading = true;
2452 m_client.dispatchDidFailProvisionalLoad(error, willContinueLoading);
2454 #if ENABLE(CONTENT_FILTERING)
2455 if (contentFilterWillContinueLoading)
2456 contentFilter->handleProvisionalLoadFailure(error);
2459 m_provisionalLoadErrorBeingHandledURL = { };
2462 void FrameLoader::checkLoadCompleteForThisFrame()
2464 ASSERT(m_client.hasWebView());
2466 // FIXME: Should this check be done in checkLoadComplete instead of here?
2467 // FIXME: Why does this one check need to be repeated here, and not the many others from checkCompleted?
2468 if (m_frame.document()->isDelayingLoadEvent())
2472 case FrameStateProvisional: {
2473 // FIXME: Prohibiting any provisional load failures from being sent to clients
2474 // while handling provisional load failures is too heavy. For example, the current
2475 // load will fail to cancel another ongoing load. That might prevent clients' page
2476 // load state being handled properly.
2477 if (!m_provisionalLoadErrorBeingHandledURL.isEmpty())
2480 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2484 // If we've received any errors we may be stuck in the provisional state and actually complete.
2485 const ResourceError& error = pdl->mainDocumentError();
2489 // Check all children first.
2490 RefPtr<HistoryItem> item;
2491 if (Page* page = m_frame.page())
2492 if (isBackForwardLoadType(loadType()))
2493 // Reset the back forward list to the last committed history item at the top level.
2494 item = page->mainFrame().loader().history().currentItem();
2496 // Only reset if we aren't already going to a new provisional item.
2497 bool shouldReset = !history().provisionalItem();
2498 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2499 RELEASE_LOG_IF_ALLOWED("checkLoadCompleteForThisFrame: Failed provisional load (frame = %p, main = %d, isTimeout = %d, isCancellation = %d, errorCode = %d)", &m_frame, m_frame.isMainFrame(), error.isTimeout(), error.isCancellation(), error.errorCode());
2501 dispatchDidFailProvisionalLoad(*pdl, error);
2502 ASSERT(!pdl->isLoading());
2504 // If we're in the middle of loading multipart data, we need to restore the document loader.
2505 if (isReplacing() && !m_documentLoader.get())
2506 setDocumentLoader(m_provisionalDocumentLoader.get());
2508 // Finish resetting the load state, but only if another load hasn't been started by the
2509 // delegate callback.
2510 if (pdl == m_provisionalDocumentLoader)
2511 clearProvisionalLoad();
2512 else if (activeDocumentLoader()) {
2513 URL unreachableURL = activeDocumentLoader()->unreachableURL();
2514 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2515 shouldReset = false;
2518 if (shouldReset && item)
2519 if (Page* page = m_frame.page()) {
2520 page->backForward().setCurrentItem(*item);
2525 case FrameStateCommittedPage: {
2526 if (!m_documentLoader)
2528 if (m_documentLoader->isLoadingInAPISense() && !m_documentLoader->isStopping() && !m_checkingLoadCompleteForDetachment)
2531 setState(FrameStateComplete);
2533 // FIXME: Is this subsequent work important if we already navigated away?
2534 // Maybe there are bugs because of that, or extra work we can skip because
2535 // the new page is ready.
2537 m_client.forceLayoutForNonHTML();
2539 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2540 if (m_frame.page()) {
2541 if (isBackForwardLoadType(m_loadType) || isReload(m_loadType))
2542 history().restoreScrollPositionAndViewState();
2545 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2548 m_progressTracker->progressCompleted();
2549 Page* page = m_frame.page();
2551 if (m_frame.isMainFrame()) {
2552 tracePoint(MainResourceLoadDidEnd);
2553 page->didFinishLoad();
2557 const ResourceError& error = m_documentLoader->mainDocumentError();
2559 AXObjectCache::AXLoadingEvent loadingEvent;
2560 if (!error.isNull()) {
2561 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());
2562 m_client.dispatchDidFailLoad(error);
2563 loadingEvent = AXObjectCache::AXLoadingFailed;
2565 RELEASE_LOG_IF_ALLOWED("checkLoadCompleteForThisFrame: Finished frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
2566 #if ENABLE(DATA_DETECTION)
2567 auto* document = m_frame.document();
2568 if (m_frame.settings().dataDetectorTypes() != DataDetectorTypeNone && document) {
2569 if (auto* documentElement = document->documentElement()) {
2570 RefPtr<Range> documentRange = makeRange(firstPositionInNode(documentElement), lastPositionInNode(documentElement));
2571 m_frame.setDataDetectionResults(DataDetection::detectContentInRange(documentRange, m_frame.settings().dataDetectorTypes(), m_client.dataDetectionContext()));
2572 if (m_frame.isMainFrame())
2573 m_client.dispatchDidFinishDataDetection(m_frame.dataDetectionResults());
2577 m_client.dispatchDidFinishLoad();
2578 loadingEvent = AXObjectCache::AXLoadingFinished;
2581 // Notify accessibility.
2582 if (auto* document = m_frame.document()) {
2583 if (AXObjectCache* cache = document->existingAXObjectCache())
2584 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
2587 // The above calls to dispatchDidFinishLoad() might have detached the Frame
2588 // from its Page and also might have caused Page to be deleted.
2589 // Don't assume 'page' is still available to use.
2590 if (m_frame.isMainFrame() && m_frame.page()) {
2591 ASSERT(&m_frame.page()->mainFrame() == &m_frame);
2592 m_frame.page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageLoadedKey(), emptyString(), error.isNull() ? DiagnosticLoggingResultPass : DiagnosticLoggingResultFail, ShouldSample::Yes);
2598 case FrameStateComplete:
2599 m_loadType = FrameLoadType::Standard;
2600 frameLoadCompleted();
2604 ASSERT_NOT_REACHED();
2607 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2609 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2610 // The originalURL is defined as the URL of the page where the download was initiated.
2612 auto* initiator = m_frame.document();
2614 originalURL = initiator->firstPartyForCookies();
2615 // If there is no main document URL, it means that this document is newly opened and just for download purpose.
2616 // In this case, we need to set the originalURL to this document's opener's main document URL.
2617 if (originalURL.isEmpty() && opener() && opener()->document()) {
2618 originalURL = opener()->document()->firstPartyForCookies();
2619 initiator = opener()->document();
2622 // If the originalURL is the same as the requested URL, we are processing a download
2623 // initiated directly without a page and do not need to specify the originalURL.
2624 if (originalURL == request.url())
2625 request.setFirstPartyForCookies(URL());
2627 request.setFirstPartyForCookies(originalURL);
2628 addSameSiteInfoToRequestIfNeeded(request, initiator);
2631 void FrameLoader::didReachLayoutMilestone(OptionSet<LayoutMilestone> milestones)
2633 ASSERT(m_frame.isMainFrame());
2635 m_client.dispatchDidReachLayoutMilestone(milestones);
2638 void FrameLoader::didFirstLayout()
2640 #if PLATFORM(IOS_FAMILY)
2641 // Only send layout-related delegate callbacks synchronously for the main frame to
2642 // avoid reentering layout for the main frame while delivering a layout-related delegate
2643 // callback for a subframe.
2644 if (&m_frame != &m_frame.page()->mainFrame())
2647 if (m_frame.page() && isBackForwardLoadType(m_loadType))
2648 history().restoreScrollPositionAndViewState();
2650 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2651 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2654 void FrameLoader::frameLoadCompleted()
2656 // Note: Can be called multiple times.
2658 m_client.frameLoadCompleted();
2660 history().updateForFrameLoadCompleted();
2662 // After a canceled provisional load, firstLayoutDone is false.
2663 // Reset it to true if we're displaying a page.
2664 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2665 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2668 void FrameLoader::detachChildren()
2670 // detachChildren() will fire the unload event in each subframe and the
2671 // HTML specification states that the parent document's ignore-opens-during-unload counter while
2672 // this event is being fired in its subframes:
2673 // https://html.spec.whatwg.org/multipage/browsers.html#unload-a-document
2674 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2676 // detachChildren() will fire the unload event in each subframe and the
2677 // HTML specification states that navigations should be prevented during the prompt to unload algorithm:
2678 // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
2679 std::unique_ptr<NavigationDisabler> navigationDisabler;
2680 if (m_frame.isMainFrame())
2681 navigationDisabler = makeUnique<NavigationDisabler>(&m_frame);
2683 // Any subframe inserted by unload event handlers executed in the loop below will not get unloaded
2684 // because we create a copy of the subframes list before looping. Therefore, it would be unsafe to
2685 // allow loading of subframes at this point.
2686 SubframeLoadingDisabler subframeLoadingDisabler(m_frame.document());
2688 Vector<Ref<Frame>, 16> childrenToDetach;
2689 childrenToDetach.reserveInitialCapacity(m_frame.tree().childCount());
2690 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling())
2691 childrenToDetach.uncheckedAppend(*child);
2692 for (auto& child : childrenToDetach)
2693 child->loader().detachFromParent();
2696 void FrameLoader::closeAndRemoveChild(Frame& child)
2698 child.tree().detachFromParent();
2700 child.setView(nullptr);
2701 if (child.ownerElement() && child.page())
2702 child.page()->decrementSubframeCount();
2703 child.willDetachPage();
2704 child.detachFromPage();
2706 m_frame.tree().removeChild(child);
2709 // Called every time a resource is completely loaded or an error is received.
2710 void FrameLoader::checkLoadComplete()
2712 m_shouldCallCheckLoadComplete = false;
2714 if (!m_frame.page())
2717 ASSERT(m_client.hasWebView());
2719 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2720 // is currently needed in order to null out the previous history item for all frames.
2721 Vector<Ref<Frame>, 16> frames;
2722 for (Frame* frame = &m_frame.mainFrame(); frame; frame = frame->tree().traverseNext())
2723 frames.append(*frame);
2725 // To process children before their parents, iterate the vector backwards.
2726 for (auto frame = frames.rbegin(); frame != frames.rend(); ++frame) {
2727 if ((*frame)->page())
2728 (*frame)->loader().checkLoadCompleteForThisFrame();
2732 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2735 return m_frame.document()->cachedResourceLoader().requestCount();
2738 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
2739 count += frame->document()->cachedResourceLoader().requestCount();
2743 String FrameLoader::userAgent(const URL& url) const
2747 if (auto* documentLoader = m_frame.mainFrame().loader().activeDocumentLoader())
2748 userAgent = documentLoader->customUserAgent();
2750 InspectorInstrumentation::applyUserAgentOverride(m_frame, userAgent);
2752 if (!userAgent.isEmpty())
2755 return m_client.userAgent(url);
2758 String FrameLoader::userAgentForJavaScript(const URL& url) const
2762 if (auto* documentLoader = m_frame.mainFrame().loader().activeDocumentLoader()) {
2763 if (m_frame.settings().needsSiteSpecificQuirks())
2764 userAgent = documentLoader->customJavaScriptUserAgentAsSiteSpecificQuirks();
2765 if (userAgent.isEmpty())
2766 userAgent = documentLoader->customUserAgent();
2769 InspectorInstrumentation::applyUserAgentOverride(m_frame, userAgent);
2771 if (!userAgent.isEmpty())
2774 return m_client.userAgent(url);
2777 String FrameLoader::navigatorPlatform() const
2779 if (auto* documentLoader = m_frame.mainFrame().loader().activeDocumentLoader()) {
2780 auto& customNavigatorPlatform = documentLoader->customNavigatorPlatform();
2781 if (!customNavigatorPlatform.isEmpty())
2782 return customNavigatorPlatform;
2787 void FrameLoader::dispatchOnloadEvents()
2789 m_client.dispatchDidDispatchOnloadEvents();
2791 if (documentLoader())
2792 documentLoader()->dispatchOnloadEvents();
2795 void FrameLoader::frameDetached()
2797 // Calling stopAllLoadersAndCheckCompleteness() can cause the frame to be deallocated, including the frame loader.
2798 Ref<Frame> protectedFrame(m_frame);
2800 if (m_checkTimer.isActive()) {
2801 m_checkTimer.stop();
2802 checkCompletenessNow();
2805 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2806 stopAllLoadersAndCheckCompleteness();
2807 m_frame.document()->stopActiveDOMObjects();
2813 void FrameLoader::detachFromParent()
2815 // Calling stopAllLoaders() can cause the frame to be deallocated, including the frame loader.
2816 Ref<Frame> protect(m_frame);
2819 history().saveScrollPositionAndViewStateToItem(history().currentItem());
2821 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2822 // stopAllLoaders() needs to be called after detachChildren() if the document is not in the page cache,
2823 // because detachedChildren() will trigger the unload event handlers of any child frames, and those event
2824 // handlers might start a new subresource load in this frame.
2828 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2830 detachViewsAndDocumentLoader();
2832 m_progressTracker = nullptr;
2834 if (Frame* parent = m_frame.tree().parent()) {
2835 parent->loader().closeAndRemoveChild(m_frame);
2836 parent->loader().scheduleCheckCompleted();
2837 parent->loader().scheduleCheckLoadComplete();
2839 m_frame.setView(nullptr);
2840 m_frame.willDetachPage();
2841 m_frame.detachFromPage();
2845 void FrameLoader::detachViewsAndDocumentLoader()
2847 m_client.detachedFromParent2();
2848 setDocumentLoader(nullptr);
2849 m_client.detachedFromParent3();
2852 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2854 addExtraFieldsToRequest(request, m_loadType, false);
2857 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2859 // FIXME: Using m_loadType seems wrong for some callers.
2860 // If we are only preparing to load the main resource, that is previous load's load type!
2861 addExtraFieldsToRequest(request, m_loadType, true);
2863 // Upgrade-Insecure-Requests should only be added to main resource requests
2864 addHTTPUpgradeInsecureRequestsIfNeeded(request);
2867 ResourceRequestCachePolicy FrameLoader::defaultRequestCachingPolicy(const ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2869 if (m_overrideCachePolicyForTesting)
2870 return m_overrideCachePolicyForTesting.value();
2872 if (isMainResource) {
2873 if (isReload(loadType) || request.isConditional())
2874 return ResourceRequestCachePolicy::ReloadIgnoringCacheData;
2876 return ResourceRequestCachePolicy::UseProtocolCachePolicy;
2879 if (request.isConditional())
2880 return ResourceRequestCachePolicy::ReloadIgnoringCacheData;
2882 if (documentLoader()->isLoadingInAPISense()) {
2883 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2884 // original request cache policy for two reasons:
2885 // 1. For POST requests, we mutate the cache policy for the main resource,
2886 // but we do not want this to apply to subresources
2887 // 2. Delegates that modify the cache policy using willSendRequest: should
2888 // not affect any other resources. Such changes need to be done
2890 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2891 // 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.
2892 // This policy is set on initial request too, but should not be inherited.
2893 return (mainDocumentOriginalCachePolicy == ResourceRequestCachePolicy::ReturnCacheDataDontLoad) ? ResourceRequestCachePolicy::ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2896 return ResourceRequestCachePolicy::UseProtocolCachePolicy;
2899 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2901 // If the request came from a previous process due to process-swap-on-navigation then we should not modify the request.
2902 if (m_currentLoadContinuingState == LoadContinuingState::ContinuingWithRequest)
2905 // Don't set the cookie policy URL if it's already been set.
2906 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2907 bool isMainFrameMainResource = isMainResource && m_frame.isMainFrame();
2908 if (request.firstPartyForCookies().isEmpty()) {
2909 if (isMainFrameMainResource)
2910 request.setFirstPartyForCookies(request.url());
2911 else if (Document* document = m_frame.document())
2912 request.setFirstPartyForCookies(document->firstPartyForCookies());
2915 if (request.isSameSiteUnspecified()) {
2916 auto* initiator = m_frame.document();
2917 if (isMainResource) {
2918 auto* ownerFrame = m_frame.tree().parent();
2919 if (!ownerFrame && m_stateMachine.isDisplayingInitialEmptyDocument())
2920 ownerFrame = m_opener;
2922 initiator = ownerFrame->document();
2923 ASSERT(ownerFrame || m_frame.isMainFrame());
2925 addSameSiteInfoToRequestIfNeeded(request, initiator);
2927 request.setIsTopSite(isMainFrameMainResource);
2929 Page* page = frame().page();
2930 bool hasSpecificCachePolicy = request.cachePolicy() != ResourceRequestCachePolicy::UseProtocolCachePolicy;
2932 if (page && page->isResourceCachingDisabled()) {
2933 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
2934 loadType = FrameLoadType::ReloadFromOrigin;
2935 } else if (!hasSpecificCachePolicy)
2936 request.setCachePolicy(defaultRequestCachingPolicy(request, loadType, isMainResource));
2938 // The remaining modifications are only necessary for HTTP and HTTPS.
2939 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2942 if (!hasSpecificCachePolicy && request.cachePolicy() == ResourceRequestCachePolicy::ReloadIgnoringCacheData) {
2943 if (loadType == FrameLoadType::Reload)
2944 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
2945 else if (loadType == FrameLoadType::ReloadFromOrigin) {
2946 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
2947 request.setHTTPHeaderField(HTTPHeaderName::Pragma, "no-cache");
2951 if (m_overrideResourceLoadPriorityForTesting)
2952 request.setPriority(m_overrideResourceLoadPriorityForTesting.value());
2954 applyUserAgentIfNeeded(request);
2957 request.setHTTPAccept(defaultAcceptHeader);
2959 // Make sure we send the Origin header.
2960 addHTTPOriginIfNeeded(request, String());
2962 // Only set fallback array if it's still empty (later attempts may be incorrect, see bug 117818).
2963 if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
2964 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2965 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame.document()->encoding(), m_frame.settings().defaultTextEncodingName());
2969 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2971 if (!request.httpOrigin().isEmpty())
2972 return; // Request already has an Origin header.
2974 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2975 // For example, if an intranet page has a hyperlink to an external web
2976 // site, we don't want to include the Origin of the request because it
2977 // will leak the internal host name. Similar privacy concerns have lead
2978 // to the widespread suppression of the Referer header at the network
2980 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2983 // For non-GET and non-HEAD methods, always send an Origin header so the
2984 // server knows we support this feature.
2986 if (origin.isEmpty()) {
2987 // If we don't know what origin header to attach, we attach the value
2988 // for an empty origin.
2989 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2993 request.setHTTPOrigin(origin);
2996 // 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>.
2997 // The algorithm is ammended to treat URLs that inherit their security origin from their owner (e.g. about:blank)
2998 // as same-site. This matches the behavior of Chrome and Firefox.
2999 void FrameLoader::addSameSiteInfoToRequestIfNeeded(ResourceRequest& request, const Document* initiator)
3001 if (!request.isSameSiteUnspecified())
3004 request.setIsSameSite(true);
3007 if (SecurityPolicy::shouldInheritSecurityOriginFromOwner(request.url())) {
3008 request.setIsSameSite(true);
3011 request.setIsSameSite(areRegistrableDomainsEqual(initiator->siteForCookies(), request.url()));
3014 void FrameLoader::addHTTPUpgradeInsecureRequestsIfNeeded(ResourceRequest& request)
3016 if (request.url().protocolIs("https")) {
3017 // FIXME: Identify HSTS cases and avoid adding the header. <https://bugs.webkit.org/show_bug.cgi?id=157885>
3021 request.setHTTPHeaderField(HTTPHeaderName::UpgradeInsecureRequests, "1"_s);
3024 void FrameLoader::loadPostRequest(FrameLoadRequest&& request, const String& referrer, FrameLoadType loadType, Event* event, RefPtr<FormState>&& formState, CompletionHandler<void()>&& completionHandler)
3026 RELEASE_LOG_IF_ALLOWED("loadPostRequest: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3028 String frameName = request.frameName();
3029 LockHistory lockHistory = request.lockHistory();
3030 AllowNavigationToInvalidURL allowNavigationToInvalidURL = request.allowNavigationToInvalidURL();
3031 NewFrameOpenerPolicy openerPolicy = request.newFrameOpenerPolicy();
3033 const ResourceRequest& inRequest = request.resourceRequest();
3034 const URL& url = inRequest.url();
3035 const String& contentType = inRequest.httpContentType();
3036 String origin = inRequest.httpOrigin();
3038 ResourceRequest workingResourceRequest(url);
3040 if (!referrer.isEmpty())
3041 workingResourceRequest.setHTTPReferrer(referrer);
3042 workingResourceRequest.setHTTPOrigin(origin);
3043 workingResourceRequest.setHTTPMethod("POST");
3044 workingResourceRequest.setHTTPBody(inRequest.httpBody());
3045 workingResourceRequest.setHTTPContentType(contentType);
3046 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
3048 if (Document* document = m_frame.document())
3049 document->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(workingResourceRequest, ContentSecurityPolicy::InsecureRequestType::Load);
3051 NavigationAction action { request.requester(), workingResourceRequest, request.initiatedByMainFrame(), loadType, true, event, request.shouldOpenExternalURLsPolicy(), request.downloadAttribute() };
3053 if (!frameName.isEmpty()) {
3054 // The search for a target frame is done earlier in the case of form submission.
3055 if (auto* targetFrame = formState ? nullptr : findFrameForNavigation(frameName)) {
3056 targetFrame->loader().loadWithNavigationAction(workingResourceRequest, WTFMove(action), lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL, { }, WTFMove(completionHandler));
3060 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) mutable {
3061 continueLoadAfterNewWindowPolicy(request, formState.get(), frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
3062 completionHandler();
3067 // must grab this now, since this load may stop the previous load and clear this flag
3068 bool isRedirect = m_quickRedirectComing;
3069 loadWithNavigationAction(workingResourceRequest, WTFMove(action), lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL, { }, [this, isRedirect, protectedFrame = makeRef(m_frame), completionHandler = WTFMove(completionHandler)] () mutable {
3071 m_quickRedirectComing = false;
3072 if (m_provisionalDocumentLoader)
3073 m_provisionalDocumentLoader->setIsClientRedirect(true);
3074 else if (m_policyDocumentLoader)
3075 m_policyDocumentLoader->setIsClientRedirect(true);
3077 completionHandler();
3081 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, ClientCredentialPolicy clientCredentialPolicy, const FetchOptions& options, const HTTPHeaderMap& originalRequestHeaders, ResourceError& error, ResourceResponse& response, RefPtr<SharedBuffer>& data)
3083 ASSERT(m_frame.document());
3084 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), request.url(), outgoingReferrer());
3086 ResourceRequest initialRequest = request;
3087 initialRequest.setTimeoutInterval(10);
3089 if (!referrer.isEmpty())
3090 initialRequest.setHTTPReferrer(referrer);
3091 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
3093 initialRequest.setFirstPartyForCookies(m_frame.mainFrame().loader().documentLoader()->request().url());
3095 addExtraFieldsToSubresourceRequest(initialRequest);
3097 unsigned long identifier = 0;
3098 ResourceRequest newRequest(initialRequest);
3099 requestFromDelegate(newRequest, identifier, error);
3101 #if ENABLE(CONTENT_EXTENSIONS)
3102 if (error.isNull()) {
3103 if (auto* page = m_frame.page()) {
3104 if (m_documentLoader) {
3105 auto results = page->userContentProvider().processContentRuleListsForLoad(newRequest.url(), ContentExtensions::ResourceType::Raw, *m_documentLoader);
3106 bool blockedLoad = results.summary.blockedLoad;
3107 ContentExtensions::applyResultsToRequest(WTFMove(results), page, newRequest);
3110 error = ResourceError(errorDomainWebKitInternal, 0, initialRequest.url(), emptyString());
3119 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(newRequest, ContentSecurityPolicy::InsecureRequestType::Load);
3121 if (error.isNull()) {
3122 ASSERT(!newRequest.isNull());
3124 if (!documentLoader()->applicationCacheHost().maybeLoadSynchronously(newRequest, error, response, data)) {
3125 Vector<char> buffer;
3126 platformStrategies()->loaderStrategy()->loadResourceSynchronously(*this, identifier, newRequest, clientCredentialPolicy, options, originalRequestHeaders, error, response, buffer);
3127 data = SharedBuffer::create(WTFMove(buffer));
3128 documentLoader()->applicationCacheHost().maybeLoadFallbackSynchronously(newRequest, error, response, data);
3129 ResourceLoadObserver::shared().logSubresourceLoading(&m_frame, newRequest, response);
3132 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data ? data->data() : nullptr, data ? data->size() : 0, -1, error);
3136 const ResourceRequest& FrameLoader::originalRequest() const
3138 return activeDocumentLoader()->originalRequestCopy();
3141 void FrameLoader::receivedMainResourceError(const ResourceError& error)
3143 // Retain because the stop may release the last reference to it.
3144 Ref<Frame> protect(m_frame);
3146 RefPtr<DocumentLoader> loader = activeDocumentLoader();
3147 // FIXME: Don't want to do this if an entirely new load is going, so should check
3148 // that both data sources on the frame are either this or nil.
3150 if (m_client.shouldFallBack(error))
3151 handleFallbackContent();
3153 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
3154 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
3155 m_submittedFormURL = URL();
3157 // We might have made a page cache item, but now we're bailing out due to an error before we ever
3158 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
3159 // so that the existing view (that wenever got far enough to replace) can continue being used.
3160 history().invalidateCurrentItemCachedPage();
3162 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
3163 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
3164 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
3165 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
3167 if (m_sentRedirectNotification)
3168 clientRedirectCancelledOrFinished(NewLoadInProgress::No);
3173 checkLoadComplete();
3176 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
3178 m_quickRedirectComing = false;
3180 if (!shouldContinue)
3183 // Calling stopLoading() on the provisional document loader can cause the underlying
3184 // frame to be deallocated.
3185 Ref<Frame> protectedFrame(m_frame);
3187 // If we have a provisional request for a different document, a fragment scroll should cancel it.
3188 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
3189 m_provisionalDocumentLoader->stopLoading();
3190 setProvisionalDocumentLoader(nullptr);
3193 bool isRedirect = m_quickRedirectComing || policyChecker().loadType() == FrameLoadType::RedirectWithLockedBackForwardList;
3194 loadInSameDocument(request.url(), 0, !isRedirect);
3197 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const URL& url)
3199 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
3200 // currently displaying a frameset, or if the URL does not have a fragment.
3201 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
3203 // FIXME: What about load types other than Standard and Reload?
3205 return (!isFormSubmission || equalLettersIgnoringASCIICase(httpMethod, "get"))
3206 && !isReload(loadType)
3207 && loadType != FrameLoadType::Same
3208 && m_frame.document()->pageCacheState() != Document::InPageCache
3209 && !shouldReload(m_frame.document()->url(), url)
3210 // We don't want to just scroll if a link from within a
3211 // frameset is trying to reload the frameset into _top.
3212 && !m_frame.document()->isFrameSet();
3215 static bool itemAllowsScrollRestoration(HistoryItem* historyItem)
3217 return !historyItem || historyItem->shouldRestoreScrollPosition();
3220 static bool isSameDocumentReload(bool isNewNavigation, FrameLoadType loadType)
3222 return !isNewNavigation && !isBackForwardLoadType(loadType);
3225 void FrameLoader::scrollToFragmentWithParentBoundary(const URL& url, bool isNewNavigation)
3227 FrameView* view = m_frame.view();
3231 if (isSameDocumentReload(isNewNavigation, m_loadType) || itemAllowsScrollRestoration(history().currentItem()))
3232 view->scrollToFragment(url);
3235 bool FrameLoader::shouldClose()
3237 Page* page = m_frame.page();
3240 if (!page->chrome().canRunBeforeUnloadConfirmPanel())
3243 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
3244 Vector<Ref<Frame>, 16> targetFrames;
3245 targetFrames.append(m_frame);
3246 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().traverseNext(&m_frame))
3247 targetFrames.append(*child);
3249 bool shouldClose = false;
3251 NavigationDisabler navigationDisabler(&m_frame);
3252 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
3255 for (i = 0; i < targetFrames.size(); i++) {
3256 if (!targetFrames[i]->tree().isDescendantOf(&m_frame))
3258 if (!targetFrames[i]->loader().dispatchBeforeUnloadEvent(page->chrome(), this))
3262 if (i == targetFrames.size())
3267 m_submittedFormURL = URL();
3269 m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
3273 void FrameLoader::dispatchUnloadEvents(UnloadEventPolicy unloadEventPolicy)
3275 if (!m_frame.document())
3278 // We store the frame's page in a local variable because the frame might get detached inside dispatchEvent.
3279 ForbidPromptsScope forbidPrompts(m_frame.page());
3280 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
3282 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
3283 auto* currentFocusedElement = m_frame.document()->focusedElement();
3284 if (is<HTMLInputElement>(currentFocusedElement))
3285 downcast<HTMLInputElement>(*currentFocusedElement).endEditing();
3286 if (m_pageDismissalEventBeingDispatched == PageDismissalType::None) {
3287 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
3288 m_pageDismissalEventBeingDispatched = PageDismissalType::PageHide;
3289 m_frame.document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache), m_frame.document());
3292 // FIXME: update Page Visibility state here.
3293 // https://bugs.webkit.org/show_bug.cgi?id=116770
3295 if (m_frame.document()->pageCacheState() == Document::NotInPageCache) {
3296 Ref<Event> unloadEvent(Event::create(eventNames().unloadEvent, Event::CanBubble::No, Event::IsCancelable::No));
3297 // The DocumentLoader (and thus its LoadTiming) might get destroyed
3298 // while dispatching the event, so protect it to prevent writing the end
3299 // time into freed memory.
3300 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
3301 m_pageDismissalEventBeingDispatched = PageDismissalType::Unload;
3302 if (documentLoader && documentLoader->timing().startTime() && !documentLoader->timing().unloadEventStart() && !documentLoader->timing().unloadEventEnd()) {
3303 auto& timing = documentLoader->timing();
3304 timing.markUnloadEventStart();
3305 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
3306 timing.markUnloadEventEnd();
3308 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
3311 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
3312 m_wasUnloadEventEmitted = true;
3315 // Dispatching the unload event could have made m_frame.document() null.
3316 if (!m_frame.document())
3319 if (m_frame.document()->pageCacheState() != Document::NotInPageCache)
3322 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
3323 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
3324 && m_frame.document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
3326 if (!keepEventListeners)
3327 m_frame.document()->removeAllEventListeners();
3330 static bool shouldAskForNavigationConfirmation(Document& document, const BeforeUnloadEvent& event)
3332 // Confirmation dialog should not be displayed when the allow-modals flag is not set.
3333 if (document.isSandboxed(SandboxModals))
3336 bool userDidInteractWithPage = document.topDocument().userDidInteractWithPage();
3337 // Web pages can request we ask for confirmation before navigating by:
3338 // - Cancelling the BeforeUnloadEvent (modern way)
3339 // - Setting the returnValue attribute on the BeforeUnloadEvent to a non-empty string.
3340 // - Returning a non-empty string from the event handler, which is then set as returnValue
3341 // attribute on the BeforeUnloadEvent.
3342 return userDidInteractWithPage && (event.defaultPrevented() || !event.returnValue().isEmpty());
3345 bool FrameLoader::dispatchBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
3347 DOMWindow* domWindow = m_frame.document()->domWindow();
3351 RefPtr<Document> document = m_frame.document();
3352 if (!document->bodyOrFrameset())
3355 Ref<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
3356 m_pageDismissalEventBeingDispatched = PageDismissalType::BeforeUnload;
3359 ForbidPromptsScope forbidPrompts(m_frame.page());
3360 domWindow->dispatchEvent(beforeUnloadEvent, domWindow->document());
3363 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
3365 if (!beforeUnloadEvent->defaultPrevented())
3366 document->defaultEventHandler(beforeUnloadEvent.get());
3368 if (!shouldAskForNavigationConfirmation(*document, beforeUnloadEvent))
3371 // If the navigating FrameLoader has already shown a beforeunload confirmation panel for the current navigation attempt,
3372 // this frame is not allowed to cause another one to be shown.
3373 if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
3374 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation."_s);
3378 // We should only display the beforeunload dialog for an iframe if its SecurityOrigin matches all
3379 // ancestor frame SecurityOrigins up through the navigating FrameLoader.
3380 if (frameLoaderBeingNavigated != this) {
3381 Frame* parentFrame = m_frame.tree().parent();
3382 while (parentFrame) {
3383 Document* parentDocument = parentFrame->document();
3384 if (!parentDocument)
3386 if (!m_frame.document() || !m_frame.document()->securityOrigin().canAccess(parentDocument->securityOrigin())) {
3387 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);
3391 if (&parentFrame->loader() == frameLoaderBeingNavigated)
3394 parentFrame = parentFrame->tree().parent();
3397 // The navigatingFrameLoader should always be in our ancestory.
3398 ASSERT(parentFrame);
3399 ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
3402 frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
3404 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
3405 return chrome.runBeforeUnloadConfirmPanel(text, m_frame);
3408 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest& request, FormState* formState, NavigationPolicyDecision navigationPolicyDecision, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
3410 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
3411 // nil policyDataSource because loading the alternate page will have passed
3412 // through this method already, nested; otherwise, policyDataSource should still be set.
3413 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
3415 bool isTargetItem = history().provisionalItem() ? history().provisionalItem()->isTargetItem() : false;
3417 bool urlIsDisallowed = allowNavigationToInvalidURL == AllowNavigationToInvalidURL::No && !request.url().isValid();
3418 bool canContinue = navigationPolicyDecision == NavigationPolicyDecision::ContinueLoad && shouldClose() && !urlIsDisallowed;
3421 RELEASE_LOG_IF_ALLOWED("continueLoadAfterNavigationPolicy: can't continue loading frame due to the following reasons ("
3424 "allowNavigationToInvalidURL = %d, "
3425 "requestURLIsValid = %d, "
3426 "navigationPolicyDecision = %d)",
3428 m_frame.isMainFrame(),
3429 static_cast<int>(allowNavigationToInvalidURL),
3430 request.url().isValid(),
3431 static_cast<int>(navigationPolicyDecision));
3433 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
3434 // need to report that the client redirect was cancelled.
3435 // FIXME: The client should be told about ignored non-quick redirects, too.
3436 if (m_quickRedirectComing)
3437 clientRedirectCancelledOrFinished(NewLoadInProgress::No);
3439 if (navigationPolicyDecision == NavigationPolicyDecision::StopAllLoads) {
3441 m_checkTimer.stop();
3444 setPolicyDocumentLoader(nullptr);
3447 if (navigationPolicyDecision != NavigationPolicyDecision::StopAllLoads)
3448 checkLoadComplete();
3450 // If the navigation request came from the back/forward menu, and we punt on it, we have the
3451 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
3452 // we only do this when punting a navigation for the target frame or top-level frame.
3453 if ((isTargetItem || m_frame.isMainFrame()) && isBackForwardLoadType(policyChecker().loadType())) {
3454 if (Page* page = m_frame.page()) {
3455 if (HistoryItem* resetItem = m_frame.mainFrame().loader().history().currentItem())
3456 page->backForward().setCurrentItem(*resetItem);
3462 FrameLoadType type = policyChecker().loadType();
3463 // A new navigation is in progress, so don't clear the history's provisional item.
3464 stopAllLoaders(ShouldNotClearProvisionalItem);
3466 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
3467 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
3468 if (!m_frame.page()) {
3469 RELEASE_LOG_IF_ALLOWED("continueLoadAfterNavigationPolicy: can't continue loading frame because it became defunct (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3473 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
3475 setState(FrameStateProvisional);
3477 setPolicyDocumentLoader(nullptr);
3479 if (isBackForwardLoadType(type)) {
3480 auto& diagnosticLoggingClient = m_frame.page()->diagnosticLoggingClient();
3481 if (history().provisionalItem() && history().provisionalItem()->isInPageCache()) {
3482 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultPass, ShouldSample::Yes);
3483 loadProvisionalItemFromCachedPage();
3484 RELEASE_LOG_IF_ALLOWED("continueLoadAfterNavigationPolicy: can't continue loading frame because it will be loaded from cache (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3487 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultFail, ShouldSample::Yes);
3490 CompletionHandler<void()> completionHandler = [this, protectedFrame = makeRef(m_frame)] () mutable {
3491 if (!m_provisionalDocumentLoader) {
3492 RELEASE_LOG_IF_ALLOWED("continueLoadAfterNavigationPolicy completionHandler: Frame load canceled #1 (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3496 prepareForLoadStart();
3498 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
3499 // so we need to null check it again.
3500 if (!m_provisionalDocumentLoader) {
3501 RELEASE_LOG_IF_ALLOWED("prepareForLoadStart completionHandler: Frame load canceled #2 (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3505 DocumentLoader* activeDocLoader = activeDocumentLoader();
3506 if (activeDocLoader && activeDocLoader->isLoadingMainResource()) {
3507 RELEASE_LOG_IF_ALLOWED("prepareForLoadStart completionHandler: Main frame already being loaded (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3511 m_loadingFromCachedPage = false;
3513 m_provisionalDocumentLoader->startLoadingMainResource();
3517 completionHandler();
3521 m_client.dispatchWillSubmitForm(*formState, WTFMove(completionHandler));
3524 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
3525 FormState* formState, const String& frameName, const NavigationAction& action, ShouldContinue shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL, NewFrameOpenerPolicy openerPolicy)
3527 if (shouldContinue != ShouldContinue::Yes)
3530 Ref<Frame> frame(m_frame);
3531 RefPtr<Frame> mainFrame = m_client.dispatchCreatePage(action);
3535 SandboxFlags sandboxFlags = frame->loader().effectiveSandboxFlags();
3536 if (sandboxFlags & SandboxPropagatesToAuxiliaryBrowsingContexts)
3537 mainFrame->loader().forceSandboxFlags(sandboxFlags);
3539 if (!equalIgnoringASCIICase(frameName, "_blank"))
3540 mainFrame->tree().setName(frameName);
3542 mainFrame->page()->setOpenedByDOM();
3543 mainFrame->loader().m_client.dispatchShow();
3544 if (openerPolicy == NewFrameOpenerPolicy::Allow) {
3545 mainFrame->loader().setOpener(frame.ptr());
3546 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
3549 NavigationAction newAction { *frame->document(), request, InitiatedByMainFrame::Unknown, NavigationType::Other, action.shouldOpenExternalURLsPolicy(), nullptr, action.downloadAttribute() };
3550 mainFrame->loader().loadWithNavigationAction(request, WTFMove(newAction), LockHistory::No, FrameLoadType::Standard, formState, allowNavigationToInvalidURL);
3553 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
3555 ASSERT(!request.isNull());
3558 if (Page* page = m_frame.page()) {
3559 identifier = page->progress().createUniqueIdentifier();
3560 notifier().assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
3563 ResourceRequest newRequest(request);
3564 notifier().dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
3566 if (newRequest.isNull())
3567 error = cancelledError(request);
3569 error = ResourceError();
3571 request = newRequest;
3574 void FrameLoader::loadedResourceFromMemoryCache(CachedResource& resource, ResourceRequest& newRequest, ResourceError& error)
3576 Page* page = m_frame.page();
3580 if (!resource.shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource.url()))
3583 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
3584 if (resource.type() == CachedResource::Type::MainResource)
3587 if (!page->areMemoryCacheClientCallsEnabled()) {
3588 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), &resource);
3589 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource.resourceRequest());
3590 m_documentLoader->didTellClientAboutLoad(resource.url());
3594 if (m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource.response(), resource.encodedSize())) {
3595 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), &resource);
3596 m_documentLoader->didTellClientAboutLoad(resource.url());
3600 unsigned long identifier;
3601 requestFromDelegate(newRequest, identifier, error);
3603 ResourceResponse response = resource.response();
3604 response.setSource(ResourceResponse::Source::MemoryCache);
3605 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, response, 0, resource.encodedSize(), 0, error);
3608 void FrameLoader::applyUserAgentIfNeeded(ResourceRequest& request)
3610 if (!request.hasHTTPHeaderField(HTTPHeaderName::UserAgent)) {
3611 String userAgent = this->userAgent(request.url());
3612 ASSERT(!userAgent.isNull());
3613 request.setHTTPUserAgent(userAgent);
3617 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const URL& url, unsigned long requestIdentifier)
3619 Frame& topFrame = m_frame.tree().top();
3620 if (&m_frame == &topFrame)
3623 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
3625 switch (disposition) {
3626 case XFrameOptionsSameOrigin: {
3627 auto origin = SecurityOrigin::create(url);
3628 if (!origin->isSameSchemeHostPort(topFrame.document()->securityOrigin()))
3630 for (Frame* frame = m_frame.tree().parent(); frame; frame = frame->tree().parent()) {
3631 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin()))
3636 case XFrameOptionsDeny:
3638 case XFrameOptionsAllowAll:
3640 case XFrameOptionsConflict:
3641 m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.", requestIdentifier);
3643 case XFrameOptionsInvalid:
3644 m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
3646 case XFrameOptionsNone:
3649 ASSERT_NOT_REACHED();
3653 void FrameLoader::loadProvisionalItemFromCachedPage()
3655 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
3656 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().stringCenterEllipsizedToLength().utf8().data());
3658 prepareForLoadStart();
3660 m_loadingFromCachedPage = true;
3662 // Should have timing data from previous time(s) the page was shown.
3663 ASSERT(provisionalLoader->timing().startTime());
3664 provisionalLoader->resetTiming();
3665 provisionalLoader->timing().markStartTime();
3667 provisionalLoader->setCommitted(true);
3668 commitProvisionalLoad();
3671 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const URL& url) const
3673 if (!history().currentItem())
3675 return url == history().currentItem()->url() || url == history().currentItem()->originalURL();
3678 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const URL& url) const
3680 if (!equalLettersIgnoringASCIICase(url.string(), "about:srcdoc"))
3682 HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement();
3685 if (!ownerElement->hasTagName(iframeTag))
3687 return ownerElement->hasAttributeWithoutSynchronization(srcdocAttr);
3690 Frame* FrameLoader::findFrameForNavigation(const AtomString& name, Document* activeDocument)
3692 // FIXME: Eventually all callers should supply the actual activeDocument so we can call canNavigate with the right document.
3693 if (!activeDocument)
3694 activeDocument = m_frame.document();
3696 auto* frame = m_frame.tree().find(name, activeDocument->frame() ? *activeDocument->frame() : m_frame);
3698 if (!activeDocument->canNavigate(frame))
3704 void FrameLoader::loadSameDocumentItem(HistoryItem& item)
3706 ASSERT(item.documentSequenceNumber() == history().currentItem()->documentSequenceNumber());
3708 Ref<Frame> protect(m_frame);
3710 // Save user view state to the current history item here since we don't do a normal load.
3711 // FIXME: Does form state need to be saved here too?
3712 history().saveScrollPositionAndViewStateToItem(history().currentItem());
3713 if (FrameView* view = m_frame.view())
3714 view->setWasScrolledByUser(false);
3716 history().setCurrentItem(item);
3718 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3719 loadInSameDocument(item.url(), item.stateObject(), false);
3721 // Restore user view state from the current history item here since we don't do a normal load.
3722 history().restoreScrollPositionAndViewState();
3725 // FIXME: This function should really be split into a couple pieces, some of
3726 // which should be methods of HistoryController and some of which should be
3727 // methods of FrameLoader.
3728 void FrameLoader::loadDifferentDocumentItem(HistoryItem& item, HistoryItem* fromItem, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
3730 RELEASE_LOG_IF_ALLOWED("loadDifferentDocumentItem: frame load started (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
3732 Ref<Frame> protectedFrame(m_frame);
3734 // History items should not be reported to the parent.
3735 m_shouldReportResourceTimingToParentFrame = false;
3737 // Remember this item so we can traverse any child items as child frames load
3738 history().setProvisionalItem(&item);
3740 auto initiatedByMainFrame = InitiatedByMainFrame::Unknown;
3742 SetForScope<LoadContinuingState> continuingLoadGuard(m_currentLoadContinuingState, shouldTreatAsContinuingLoad == ShouldTreatAsContinuingLoad::Yes ? LoadContinuingState::ContinuingWithHistoryItem : LoadContinuingState::NotContinuing);
3744 if (CachedPage* cachedPage = PageCache::singleton().get(item, m_frame.page())) {
3745 auto documentLoader = cachedPage->documentLoader();
3746 m_client.updateCachedDocumentLoader(*documentLoader);
3748 auto action = NavigationAction { *m_frame.document(), documentLoader->request(), initiatedByMainFrame, loadType, false };
3749 action.setTargetBackForwardItem(item);
3750 action.setSourceBackForwardItem(fromItem);
3751 documentLoader->setTriggeringAction(WTFMove(action));
3753 documentLoader->setLastCheckedRequest(ResourceRequest());
3754 loadWithDocumentLoader(documentLoader, loadType, { }, AllowNavigationToInvalidURL::Yes, shouldTreatAsContinuingLoad);
3758 URL itemURL = item.url();
3759 URL itemOriginalURL = item.originalURL();
3761 if (documentLoader())
3762 currentURL = documentLoader()->url();
3763 RefPtr<FormData> formData = item.formData();
3765 ResourceRequest request(itemURL);
3767 if (!item.referrer().isNull())
3768 request.setHTTPReferrer(item.referrer());
3770 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = shouldOpenExternalURLsPolicyToApply(m_frame, initiatedByMainFrame, item.shouldOpenExternalURLsPolicy());
3771 bool isFormSubmission = false;
3772 Event* event = nullptr;
3774 // If this was a repost that failed the page cache, we might try to repost the form.
3775 NavigationAction action;
3777 request.setHTTPMethod("POST");
3778 request.setHTTPBody(WTFMove(formData));
3779 request.setHTTPContentType(item.formContentType());
3780 auto securityOrigin = SecurityOrigin::createFromString(item.referrer());
3781 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3782 addHTTPUpgradeInsecureRequestsIfNeeded(request);
3784 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3785 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3786 addExtraFieldsToRequest(request, loadType, true);
3788 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3789 // We want to know this before talking to the policy delegate, since it affects whether
3790 // we show the DoYouReallyWantToRepost nag.
3792 // This trick has a small bug (3123893) where we might find a cache hit, but then
3793 // have the item vanish when we try to use it in the ensuing nav. This should be
3794 // extremely rare, but in that case the user will get an error on the navigation.
3796 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3797 request.setCachePolicy(ResourceRequestCachePolicy::ReturnCacheDataDontLoad);
3798 action = { *m_frame.document(), request, initiatedByMainFrame, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy };
3800 request.setCachePolicy(ResourceRequestCachePolicy::ReturnCacheDataElseLoad);
3801 action = { *m_frame.document(), request, initiatedByMainFrame, NavigationType::FormResubmitted, shouldOpenExternalURLsPolicy, event };
3805 case FrameLoadType::Reload:
3806 case FrameLoadType::ReloadFromOrigin:
3807 case FrameLoadType::ReloadExpiredOnly:
3808 request.setCachePolicy(ResourceRequestCachePolicy::ReloadIgnoringCacheData);
3810 case FrameLoadType::Back:
3811 case FrameLoadType::Forward:
3812 case FrameLoadType::IndexedBackForward: {
3814 bool allowStaleData = true;
3816 bool allowStaleData = !item.wasRestoredFromSession();
3819 request.setCachePolicy(ResourceRequestCachePolicy::ReturnCacheDataElseLoad);
3820 item.setWasRestoredFromSession(false);
3823 case FrameLoadType::Standard:
3824 case FrameLoadType::RedirectWithLockedBackForwardList:
3826 case FrameLoadType::Same:
3827 case FrameLoadType::Replace:
3828 ASSERT_NOT_REACHED();
3831 addExtraFieldsToRequest(request, loadType, true);
3833 ResourceRequest requestForOriginalURL(request);
3834 requestForOriginalURL.setURL(itemOriginalURL);
3835 action = { *m_frame.document(), requestForOriginalURL, initiatedByMainFrame, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy };
3838 action.setTargetBackForwardItem(item);
3839 action.setSourceBackForwardItem(fromItem);
3841 loadWithNavigationAction(request, WTFMove(action), LockHistory::No, loadType, { }, AllowNavigationToInvalidURL::Yes);
3844 // Loads content into this frame, as specified by history item
3845 void FrameLoader::loadItem(HistoryItem& item, HistoryItem* fromItem, FrameLoadType loadType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
3847 m_requestedHistoryItem = &item;
3848 HistoryItem* currentItem = history().currentItem();
3849 bool sameDocumentNavigation = currentItem && item.shouldDoSameDocumentNavigationTo(*currentItem);
3851 if (sameDocumentNavigation)
3852 loadSameDocumentItem(item);
3854 loadDifferentDocumentItem(item, fromItem, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem, shouldTreatAsContinuingLoad);
3857 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3859 ASSERT(m_state == FrameStateProvisional);
3860 ASSERT(!m_loadingFromCachedPage);
3861 ASSERT(history().provisionalItem());
3862 ASSERT(history().provisionalItem()->formData());
3863 ASSERT(history().provisionalItem() == m_requestedHistoryItem.get());
3865 FrameLoadType loadType = m_loadType;
3866 HistoryItem* item = history().provisionalItem();
3868 stopAllLoaders(ShouldNotClearProvisionalItem);
3870 loadDifferentDocumentItem(*item, history().currentItem(), loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem, ShouldTreatAsContinuingLoad::No);
3872 ASSERT_NOT_REACHED();
3873 RELEASE_LOG_ERROR(ResourceLoading, "Retrying load after failed cache-only main resource load failed because there is no provisional history item.");
3877 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3879 ResourceError error = m_client.cancelledError(request);
3880 error.setType(ResourceError::Type::Cancellation);
3884 ResourceError FrameLoader::blockedByContentBlockerError(const ResourceRequest& request) const
3886 return m_client.blockedByContentBlockerError(request);
3889 ResourceError FrameLoader::blockedError(const ResourceRequest& request) const
3891 ResourceError error = m_client.blockedError(request);
3892 error.setType(ResourceError::Type::Cancellation);
3896 #if ENABLE(CONTENT_FILTERING)
3897 ResourceError FrameLoader::blockedByContentFilterError(const ResourceRequest& request) const
3899 ResourceError error = m_client.blockedByContentFilterError(request);
3900 error.setType(ResourceError::Type::General);
3905 #if PLATFORM(IOS_FAMILY)
3906 RetainPtr<CFDictionaryRef> FrameLoader::connectionProperties(ResourceLoader* loader)
3908 return m_client.connectionProperties(loader->documentLoader(), loader->identifier());
3912 ReferrerPolicy FrameLoader::effectiveReferrerPolicy() const
3914 if (auto* parentFrame = m_frame.tree().parent())
3915 return parentFrame->document()->referrerPolicy();
3917 return m_opener->document()->referrerPolicy();
3918 return ReferrerPolicy::NoReferrerWhenDowngrade;
3921 String FrameLoader::referrer() const
3923 return m_documentLoader ? m_documentLoader->request().httpReferrer() : emptyString();
3926 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3928 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript))
3931 Vector<Ref<DOMWrapperWorld>> worlds;
3932 ScriptController::getAllWorlds(worlds);
3933 for (auto& world : worlds)
3934 dispatchDidClearWindowObjectInWorld(world);
3937 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
3939 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame.windowProxy().existingJSWindowProxy(world))
3942 m_client.dispatchDidClearWindowObjectInWorld(world);
3944 if (Page* page = m_frame.page())
3945 page->inspectorController().didClearWindowObjectInWorld(m_frame, world);
3947 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3950 void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
3952 Vector<Ref<DOMWrapperWorld>> worlds;
3953 ScriptController::getAllWorlds(worlds);
3954 for (auto& world : worlds)
3955 m_client.dispatchGlobalObjectAvailable(world);
3958 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3960 SandboxFlags flags = m_forcedSandboxFlags;
3961 if (Frame* parentFrame = m_frame.tree().parent())
3962 flags |= parentFrame->document()->sandboxFlags();
3963 if (HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement())
3964 flags |= ownerElement->sandboxFlags();
3968 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3970 m_client.didChangeTitle(loader);
3972 if (loader == m_documentLoader) {
3973 // Must update the entries in the back-forward list too.
3974 history().setCurrentItemTitle(loader->title());
3975 // This must go through the WebFrame because it has the right notion of the current b/f item.
3976 m_client.setTitle(loader->title(), loader->urlForHistory());
3977 m_client.setMainFrameDocumentReady(true); // update observers with new DOMDocument
3978 m_client.dispatchDidReceiveTitle(loader->title());
3981 #if ENABLE(REMOTE_INSPECTOR)
3982 if (m_frame.isMainFrame())
3983 m_frame.page()->remoteInspectorInformationDidChange();
3987 void FrameLoader::dispatchDidCommitLoad(Optional<HasInsecureContent> initialHasInsecureContent)
3989 if (m_stateMachine.creatingInitialEmptyDocument())