2 * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
6 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
7 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
8 * Copyright (C) 2011 Google Inc. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
20 * its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
27 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "FrameLoader.h"
38 #include "AXObjectCache.h"
39 #include "ApplicationCacheHost.h"
40 #include "BackForwardController.h"
41 #include "BeforeUnloadEvent.h"
42 #include "CachedPage.h"
43 #include "CachedResourceLoader.h"
45 #include "ChromeClient.h"
46 #include "ContentFilter.h"
47 #include "ContentSecurityPolicy.h"
48 #include "DOMWindow.h"
49 #include "DatabaseManager.h"
50 #include "DiagnosticLoggingClient.h"
51 #include "DiagnosticLoggingKeys.h"
53 #include "DocumentLoader.h"
55 #include "EditorClient.h"
58 #include "EventHandler.h"
59 #include "EventNames.h"
60 #include "FloatRect.h"
61 #include "FormState.h"
62 #include "FormSubmission.h"
63 #include "FrameLoadRequest.h"
64 #include "FrameLoaderClient.h"
65 #include "FrameNetworkingContext.h"
66 #include "FrameTree.h"
67 #include "FrameView.h"
68 #include "GCController.h"
69 #include "HTMLFormElement.h"
70 #include "HTMLInputElement.h"
71 #include "HTMLNames.h"
72 #include "HTMLObjectElement.h"
73 #include "HTMLParserIdioms.h"
74 #include "HTTPHeaderNames.h"
75 #include "HTTPParsers.h"
76 #include "HistoryController.h"
77 #include "HistoryItem.h"
78 #include "IconController.h"
79 #include "IgnoreOpensDuringUnloadCountIncrementer.h"
80 #include "InspectorController.h"
81 #include "InspectorInstrumentation.h"
82 #include "LinkLoader.h"
83 #include "LoadTiming.h"
84 #include "LoaderStrategy.h"
86 #include "MainFrame.h"
87 #include "MemoryCache.h"
88 #include "MemoryRelease.h"
90 #include "PageCache.h"
91 #include "PageTransitionEvent.h"
92 #include "PerformanceLogging.h"
93 #include "PlatformStrategies.h"
94 #include "PluginData.h"
95 #include "PluginDocument.h"
96 #include "PolicyChecker.h"
97 #include "ProgressTracker.h"
98 #include "PublicSuffix.h"
99 #include "ResourceHandle.h"
100 #include "ResourceLoadInfo.h"
101 #include "ResourceLoadObserver.h"
102 #include "ResourceRequest.h"
103 #include "SVGDocument.h"
104 #include "SVGLocatable.h"
105 #include "SVGNames.h"
106 #include "SVGViewElement.h"
107 #include "SVGViewSpec.h"
108 #include "ScriptController.h"
109 #include "ScriptSourceCode.h"
110 #include "ScrollAnimator.h"
111 #include "SecurityOrigin.h"
112 #include "SecurityPolicy.h"
113 #include "SegmentedString.h"
114 #include "SerializedScriptValue.h"
115 #include "Settings.h"
116 #include "SubframeLoader.h"
117 #include "TextResourceDecoder.h"
118 #include "UserContentController.h"
119 #include "WindowFeatures.h"
120 #include "XMLDocumentParser.h"
121 #include <wtf/CurrentTime.h>
123 #include <wtf/StdLibExtras.h>
124 #include <wtf/text/CString.h>
125 #include <wtf/text/WTFString.h>
127 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
131 #if ENABLE(DATA_DETECTION)
132 #include "DataDetection.h"
136 #include "DocumentType.h"
137 #include "ResourceLoader.h"
138 #include "RuntimeApplicationChecks.h"
139 #include "WKContentObservation.h"
142 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - FrameLoader::" fmt, this, ##__VA_ARGS__)
146 using namespace HTMLNames;
147 using namespace SVGNames;
149 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
151 bool isBackForwardLoadType(FrameLoadType type)
154 case FrameLoadType::Standard:
155 case FrameLoadType::Reload:
156 case FrameLoadType::ReloadFromOrigin:
157 case FrameLoadType::Same:
158 case FrameLoadType::RedirectWithLockedBackForwardList:
159 case FrameLoadType::Replace:
161 case FrameLoadType::Back:
162 case FrameLoadType::Forward:
163 case FrameLoadType::IndexedBackForward:
166 ASSERT_NOT_REACHED();
170 // This is not in the FrameLoader class to emphasize that it does not depend on
171 // private FrameLoader data, and to avoid increasing the number of public functions
172 // with access to private data. Since only this .cpp file needs it, making it
173 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
176 static bool isDocumentSandboxed(Frame& frame, SandboxFlags mask)
178 return frame.document() && frame.document()->isSandboxed(mask);
181 struct ForbidPromptsScope {
182 ForbidPromptsScope(Page* page) : m_page(page)
186 m_page->forbidPrompts();
189 ~ForbidPromptsScope()
193 m_page->allowPrompts();
199 class FrameLoader::FrameProgressTracker {
200 WTF_MAKE_FAST_ALLOCATED;
202 explicit FrameProgressTracker(Frame& frame)
204 , m_inProgress(false)
208 ~FrameProgressTracker()
210 if (m_inProgress && m_frame.page())
211 m_frame.page()->progress().progressCompleted(m_frame);
214 void progressStarted()
216 ASSERT(m_frame.page());
218 m_frame.page()->progress().progressStarted(m_frame);
222 void progressCompleted()
224 ASSERT(m_inProgress);
225 ASSERT(m_frame.page());
226 m_inProgress = false;
227 m_frame.page()->progress().progressCompleted(m_frame);
235 FrameLoader::FrameLoader(Frame& frame, FrameLoaderClient& client)
238 , m_policyChecker(std::make_unique<PolicyChecker>(frame))
239 , m_history(std::make_unique<HistoryController>(frame))
241 , m_subframeLoader(std::make_unique<SubframeLoader>(frame))
242 , m_icon(std::make_unique<IconController>(frame))
243 , m_mixedContentChecker(frame)
244 , m_state(FrameStateProvisional)
245 , m_loadType(FrameLoadType::Standard)
246 , m_quickRedirectComing(false)
247 , m_sentRedirectNotification(false)
248 , m_inStopAllLoaders(false)
249 , m_isExecutingJavaScriptFormAction(false)
250 , m_didCallImplicitClose(true)
251 , m_wasUnloadEventEmitted(false)
252 , m_isComplete(false)
253 , m_needsClear(false)
254 , m_checkTimer(*this, &FrameLoader::checkTimerFired)
255 , m_shouldCallCheckCompleted(false)
256 , m_shouldCallCheckLoadComplete(false)
258 , m_loadingFromCachedPage(false)
259 , m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
260 , m_loadsSynchronously(false)
261 , m_forcedSandboxFlags(SandboxNone)
265 FrameLoader::~FrameLoader()
269 for (auto& frame : m_openedFrames)
270 frame->loader().m_opener = nullptr;
272 m_client.frameLoaderDestroyed();
274 if (m_networkingContext)
275 m_networkingContext->invalidate();
278 void FrameLoader::init()
280 // This somewhat odd set of steps gives the frame an initial empty document.
281 setPolicyDocumentLoader(m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData()).ptr());
282 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
283 m_provisionalDocumentLoader->startLoadingMainResource();
285 Ref<Frame> protect(m_frame);
286 m_frame.document()->cancelParsing();
287 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
289 m_networkingContext = m_client.createNetworkingContext();
290 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
294 void FrameLoader::initForSynthesizedDocument(const URL&)
296 // FIXME: We need to initialize the document URL to the specified URL. Currently the URL is empty and hence
297 // FrameLoader::checkCompleted() will overwrite the URL of the document to be activeDocumentLoader()->documentURL().
299 RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData());
300 loader->attachToFrame(m_frame);
301 loader->setResponse(ResourceResponse(URL(), ASCIILiteral("text/html"), 0, String()));
302 loader->setCommitted(true);
303 setDocumentLoader(loader.get());
305 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
306 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
307 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
308 m_client.transitionToCommittedForNewPage();
310 m_didCallImplicitClose = true;
312 m_state = FrameStateComplete;
315 m_networkingContext = m_client.createNetworkingContext();
316 m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
320 void FrameLoader::setDefersLoading(bool defers)
322 if (m_documentLoader)
323 m_documentLoader->setDefersLoading(defers);
324 if (m_provisionalDocumentLoader)
325 m_provisionalDocumentLoader->setDefersLoading(defers);
326 if (m_policyDocumentLoader)
327 m_policyDocumentLoader->setDefersLoading(defers);
328 history().setDefersLoading(defers);
331 m_frame.navigationScheduler().startTimer();
332 startCheckCompleteTimer();
336 void FrameLoader::changeLocation(const FrameLoadRequest& request)
338 urlSelected(request, nullptr);
341 void FrameLoader::urlSelected(const URL& url, const String& passedTarget, Event* triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy, std::optional<NewFrameOpenerPolicy> openerPolicy, const AtomicString& downloadAttribute)
343 NewFrameOpenerPolicy newFrameOpenerPolicy = openerPolicy.value_or(shouldSendReferrer == NeverSendReferrer ? NewFrameOpenerPolicy::Suppress : NewFrameOpenerPolicy::Allow);
344 urlSelected(FrameLoadRequest(m_frame.document()->securityOrigin(), ResourceRequest(url), passedTarget, lockHistory, lockBackForwardList, shouldSendReferrer, AllowNavigationToInvalidURL::Yes, newFrameOpenerPolicy, DoNotReplaceDocumentIfJavaScriptURL, shouldOpenExternalURLsPolicy, downloadAttribute), triggeringEvent);
347 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, Event* triggeringEvent)
349 Ref<Frame> protect(m_frame);
350 FrameLoadRequest frameRequest(passedRequest);
352 if (m_frame.script().executeIfJavaScriptURL(frameRequest.resourceRequest().url(), frameRequest.shouldReplaceDocumentIfJavaScriptURL()))
355 if (frameRequest.frameName().isEmpty())
356 frameRequest.setFrameName(m_frame.document()->baseTarget());
358 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
359 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(frameRequest.resourceRequest(), ContentSecurityPolicy::InsecureRequestType::Navigation);
361 loadFrameRequest(frameRequest, triggeringEvent, nullptr);
364 void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
366 ASSERT(submission->method() == FormSubmission::Method::Post || submission->method() == FormSubmission::Method::Get);
368 // FIXME: Find a good spot for these.
369 ASSERT(!submission->state().sourceDocument().frame() || submission->state().sourceDocument().frame() == &m_frame);
374 if (submission->action().isEmpty())
377 if (isDocumentSandboxed(m_frame, SandboxForms)) {
378 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
379 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.");
383 if (protocolIsJavaScript(submission->action())) {
384 if (!m_frame.document()->contentSecurityPolicy()->allowFormAction(URL(submission->action())))
386 m_isExecutingJavaScriptFormAction = true;
387 Ref<Frame> protect(m_frame);
388 m_frame.script().executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
389 m_isExecutingJavaScriptFormAction = false;
393 Frame* targetFrame = findFrameForNavigation(submission->target(), &submission->state().sourceDocument());
395 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
398 // FIXME: targetFrame can be null for two distinct reasons:
399 // 1. The frame was not found by name, so we should try opening a new window.
400 // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
401 // Continuing form submission makes no sense in the latter case.
402 // There is a repeat check after timer fires, so this is not a correctness issue.
404 targetFrame = &m_frame;
406 submission->clearTarget();
408 if (!targetFrame->page())
411 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
413 // We do not want to submit more than one form from the same page, nor do we want to submit a single
414 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
415 // The flag is reset in each time we start dispatching a new mouse or key down event, and
416 // also in setView since this part may get reused for a page from the back/forward cache.
417 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
419 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
420 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
421 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
423 if (m_frame.tree().isDescendantOf(targetFrame)) {
424 if (m_submittedFormURL == submission->requestURL())
426 m_submittedFormURL = submission->requestURL();
429 submission->data().generateFiles(m_frame.document());
430 submission->setReferrer(outgoingReferrer());
431 submission->setOrigin(outgoingOrigin());
433 targetFrame->navigationScheduler().scheduleFormSubmission(WTFMove(submission));
436 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
438 if (m_frame.document() && m_frame.document()->parser())
439 m_frame.document()->parser()->stopParsing();
441 if (unloadEventPolicy != UnloadEventPolicyNone)
442 dispatchUnloadEvents(unloadEventPolicy);
444 m_isComplete = true; // to avoid calling completed() in finishedParsing()
445 m_didCallImplicitClose = true; // don't want that one either
447 if (m_frame.document() && m_frame.document()->parsing()) {
449 m_frame.document()->setParsing(false);
452 if (auto* document = m_frame.document()) {
453 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
454 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
455 document->setReadyState(Document::Complete);
457 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
458 DatabaseManager::singleton().stopDatabases(*document, nullptr);
461 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
462 m_frame.navigationScheduler().cancel();
465 void FrameLoader::stop()
467 // http://bugs.webkit.org/show_bug.cgi?id=10854
468 // The frame's last ref may be removed and it will be deleted by checkCompleted().
469 Ref<Frame> protect(m_frame);
471 if (DocumentParser* parser = m_frame.document()->parser()) {
472 parser->stopParsing();
479 void FrameLoader::willTransitionToCommitted()
481 // This function is called when a frame is still fully in place (not cached, not detached), but will be replaced.
483 if (m_frame.editor().hasComposition()) {
484 // The text was already present in DOM, so it's better to confirm than to cancel the composition.
485 m_frame.editor().confirmComposition();
486 if (EditorClient* editorClient = m_frame.editor().client()) {
487 editorClient->respondToChangedSelection(&m_frame);
488 editorClient->discardedComposition(&m_frame);
493 bool FrameLoader::closeURL()
495 history().saveDocumentState();
497 Document* currentDocument = m_frame.document();
498 UnloadEventPolicy unloadEventPolicy;
499 if (m_frame.page() && m_frame.page()->chrome().client().isSVGImageChromeClient()) {
500 // If this is the SVGDocument of an SVGImage, no need to dispatch events or recalcStyle.
501 unloadEventPolicy = UnloadEventPolicyNone;
503 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
504 unloadEventPolicy = currentDocument && currentDocument->pageCacheState() == Document::NotInPageCache ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly;
507 stopLoading(unloadEventPolicy);
509 m_frame.editor().clearUndoRedoOperations();
513 bool FrameLoader::didOpenURL()
515 if (m_frame.navigationScheduler().redirectScheduledDuringLoad()) {
516 // A redirect was scheduled before the document was created.
517 // This can happen when one frame changes another frame's location.
521 m_frame.navigationScheduler().cancel();
522 m_frame.editor().clearLastEditCommand();
524 m_isComplete = false;
525 m_didCallImplicitClose = false;
527 // If we are still in the process of initializing an empty document then
528 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
529 // since it may cause clients to attempt to render the frame.
530 if (!m_stateMachine.creatingInitialEmptyDocument()) {
531 DOMWindow* window = m_frame.document()->domWindow();
532 window->setStatus(String());
533 window->setDefaultStatus(String());
541 void FrameLoader::didExplicitOpen()
543 m_isComplete = false;
544 m_didCallImplicitClose = false;
546 // Calling document.open counts as committing the first real document load.
547 if (!m_stateMachine.committedFirstRealDocumentLoad())
548 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
550 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
551 // from a subsequent window.document.open / window.document.write call.
552 // Canceling redirection here works for all cases because document.open
553 // implicitly precedes document.write.
554 m_frame.navigationScheduler().cancel();
558 void FrameLoader::cancelAndClear()
560 m_frame.navigationScheduler().cancel();
565 clear(m_frame.document(), false);
566 m_frame.script().updatePlatformScriptObjects();
569 static inline bool shouldClearWindowName(const Frame& frame, const Document& newDocument)
571 if (!frame.isMainFrame())
574 if (frame.loader().opener())
577 return !newDocument.securityOrigin().isSameOriginAs(frame.document()->securityOrigin());
580 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
582 m_frame.editor().clear();
586 m_needsClear = false;
588 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
589 m_frame.document()->cancelParsing();
590 m_frame.document()->stopActiveDOMObjects();
591 bool hadLivingRenderTree = m_frame.document()->hasLivingRenderTree();
592 m_frame.document()->prepareForDestruction();
593 if (hadLivingRenderTree)
594 m_frame.document()->removeFocusedNodeOfSubtree(*m_frame.document());
597 // Do this after detaching the document so that the unload event works.
598 if (clearWindowProperties) {
599 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame.document()->domWindow());
600 m_frame.document()->domWindow()->resetUnlessSuspendedForDocumentSuspension();
601 m_frame.script().clearWindowShellsNotMatchingDOMWindow(newDocument->domWindow(), m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache);
603 if (shouldClearWindowName(m_frame, *newDocument))
604 m_frame.tree().setName(nullAtom);
607 m_frame.selection().prepareForDestruction();
609 // We may call this code during object destruction, so need to make sure eventHandler is present.
610 if (auto eventHandler = m_frame.eventHandlerPtr())
611 eventHandler->clear();
613 if (clearFrameView && m_frame.view())
614 m_frame.view()->clear();
616 // Do not drop the document before the ScriptController and view are cleared
617 // as some destructors might still try to access the document.
618 m_frame.setDocument(nullptr);
620 subframeLoader().clear();
622 if (clearWindowProperties)
623 m_frame.script().setDOMWindowForWindowShell(newDocument->domWindow());
625 if (clearScriptObjects)
626 m_frame.script().clearScriptObjects();
628 m_frame.script().enableEval();
630 m_frame.navigationScheduler().clear();
633 m_shouldCallCheckCompleted = false;
634 m_shouldCallCheckLoadComplete = false;
636 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
637 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
640 void FrameLoader::receivedFirstData()
642 dispatchDidCommitLoad(std::nullopt);
643 dispatchDidClearWindowObjectsInAllWorlds();
644 dispatchGlobalObjectAvailableInAllWorlds();
646 if (m_documentLoader) {
647 auto& title = m_documentLoader->title();
648 if (!title.string.isNull())
649 m_client.dispatchDidReceiveTitle(title);
652 if (!m_documentLoader)
655 ASSERT(m_frame.document());
656 auto& document = *m_frame.document();
658 ASSERT(m_frame.document());
659 LinkLoader::loadLinksFromHeader(m_documentLoader->response().httpHeaderField(HTTPHeaderName::Link), m_frame.document()->url(), *m_frame.document());
663 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField(HTTPHeaderName::Refresh), delay, urlString))
665 auto completedURL = urlString.isEmpty() ? document.url() : document.completeURL(urlString);
666 if (!protocolIsJavaScript(completedURL))
667 m_frame.navigationScheduler().scheduleRedirect(document, delay, completedURL);
669 auto message = "Refused to refresh " + document.url().stringCenterEllipsizedToLength() + " to a javascript: URL";
670 m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
674 void FrameLoader::setOutgoingReferrer(const URL& url)
676 m_outgoingReferrer = url.strippedForUseAsReferrer();
679 void FrameLoader::didBeginDocument(bool dispatch)
682 m_isComplete = false;
683 m_didCallImplicitClose = false;
684 m_frame.document()->setReadyState(Document::Loading);
686 if (m_pendingStateObject) {
687 m_frame.document()->statePopped(*m_pendingStateObject);
688 m_pendingStateObject = nullptr;
692 dispatchDidClearWindowObjectsInAllWorlds();
694 updateFirstPartyForCookies();
695 m_frame.document()->initContentSecurityPolicy();
697 const Settings& settings = m_frame.settings();
698 m_frame.document()->cachedResourceLoader().setImagesEnabled(settings.areImagesEnabled());
699 m_frame.document()->cachedResourceLoader().setAutoLoadImages(settings.loadsImagesAutomatically());
701 if (m_documentLoader) {
702 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XDNSPrefetchControl);
703 if (!dnsPrefetchControl.isEmpty())
704 m_frame.document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
706 m_frame.document()->contentSecurityPolicy()->didReceiveHeaders(ContentSecurityPolicyResponseHeaders(m_documentLoader->response()), ContentSecurityPolicy::ReportParsingErrors::No);
708 String headerContentLanguage = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentLanguage);
709 if (!headerContentLanguage.isEmpty()) {
710 size_t commaIndex = headerContentLanguage.find(',');
711 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
712 headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
713 if (!headerContentLanguage.isEmpty())
714 m_frame.document()->setContentLanguage(headerContentLanguage);
718 history().restoreDocumentState();
721 void FrameLoader::finishedParsing()
723 m_frame.injectUserScripts(InjectAtDocumentEnd);
725 if (m_stateMachine.creatingInitialEmptyDocument())
728 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
729 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
730 // Null-checking the FrameView indicates whether or not we're in the destructor.
731 RefPtr<Frame> protector = m_frame.view() ? &m_frame : 0;
733 m_client.dispatchDidFinishDocumentLoad();
735 scrollToFragmentWithParentBoundary(m_frame.document()->url());
740 return; // We are being destroyed by something checkCompleted called.
742 // Check if the scrollbars are really needed for the content.
743 // If not, remove them, relayout, and repaint.
744 m_frame.view()->restoreScrollbar();
747 void FrameLoader::loadDone()
752 bool FrameLoader::allChildrenAreComplete() const
754 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
755 if (!child->loader().m_isComplete)
761 bool FrameLoader::allAncestorsAreComplete() const
763 for (Frame* ancestor = &m_frame; ancestor; ancestor = ancestor->tree().parent()) {
764 if (!ancestor->loader().m_isComplete)
770 void FrameLoader::checkCompleted()
772 m_shouldCallCheckCompleted = false;
774 // Have we completed before?
778 // Are we still parsing?
779 if (m_frame.document()->parsing())
782 // Still waiting for images/scripts?
783 if (m_frame.document()->cachedResourceLoader().requestCount())
786 // Still waiting for elements that don't go through a FrameLoader?
787 if (m_frame.document()->isDelayingLoadEvent())
790 auto* scriptableParser = m_frame.document()->scriptableDocumentParser();
791 if (scriptableParser && scriptableParser->hasScriptsWaitingForStylesheets())
794 // Any frame that hasn't completed yet?
795 if (!allChildrenAreComplete())
798 // Important not to protect earlier in this function, because earlier parts
799 // of this function can be called in the frame's destructor, and it's not legal
800 // to ref an object while it's being destroyed.
801 Ref<Frame> protect(m_frame);
805 m_requestedHistoryItem = nullptr;
806 m_frame.document()->setReadyState(Document::Complete);
809 if (m_frame.document()->url().isEmpty()) {
810 // We need to update the document URL of a PDF document to be non-empty so that both back/forward history navigation
811 // between PDF pages and fragment navigation works. See <rdar://problem/9544769> for more details.
812 // FIXME: Is there a better place for this code, say DocumentLoader? Also, we should explicitly only update the URL
813 // of the document when it's a PDFDocument object instead of assuming that a Document object with an empty URL is a PDFDocument.
814 // FIXME: This code is incorrect for a synthesized document (which also has an empty URL). The URL for a synthesized
815 // document should be the URL specified to FrameLoader::initForSynthesizedDocument().
816 m_frame.document()->setURL(activeDocumentLoader()->documentURL());
820 checkCallImplicitClose(); // if we didn't do it before
822 m_frame.navigationScheduler().startTimer();
829 void FrameLoader::checkTimerFired()
831 Ref<Frame> protect(m_frame);
833 if (Page* page = m_frame.page()) {
834 if (page->defersLoading())
837 if (m_shouldCallCheckCompleted)
839 if (m_shouldCallCheckLoadComplete)
843 void FrameLoader::startCheckCompleteTimer()
845 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
847 if (m_checkTimer.isActive())
849 m_checkTimer.startOneShot(0);
852 void FrameLoader::scheduleCheckCompleted()
854 m_shouldCallCheckCompleted = true;
855 startCheckCompleteTimer();
858 void FrameLoader::scheduleCheckLoadComplete()
860 m_shouldCallCheckLoadComplete = true;
861 startCheckCompleteTimer();
864 void FrameLoader::checkCallImplicitClose()
866 if (m_didCallImplicitClose || m_frame.document()->parsing() || m_frame.document()->isDelayingLoadEvent())
869 if (!allChildrenAreComplete())
870 return; // still got a frame running -> too early
872 m_didCallImplicitClose = true;
873 m_wasUnloadEventEmitted = false;
874 m_frame.document()->implicitClose();
877 void FrameLoader::loadURLIntoChildFrame(const URL& url, const String& referer, Frame* childFrame)
881 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
882 if (auto activeLoader = activeDocumentLoader()) {
883 if (auto subframeArchive = activeLoader->popArchiveForSubframe(childFrame->tree().uniqueName(), url)) {
884 childFrame->loader().loadArchive(RefPtr<Archive> { subframeArchive }.releaseNonNull());
890 // If we're moving in the back/forward list, we might want to replace the content
891 // of this child frame with whatever was there at that point.
892 auto* parentItem = history().currentItem();
893 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType()) && !m_frame.document()->loadEventFinished()) {
894 if (auto* childItem = parentItem->childItemWithTarget(childFrame->tree().uniqueName())) {
895 childFrame->loader().m_requestedHistoryItem = childItem;
896 childFrame->loader().loadDifferentDocumentItem(*childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
901 FrameLoadRequest frameLoadRequest(m_frame.document()->securityOrigin(), ResourceRequest(url), "_self", LockHistory::No, LockBackForwardList::Yes, ShouldSendReferrer::MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress, ReplaceDocumentIfJavaScriptURL, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
902 childFrame->loader().loadURL(frameLoadRequest, referer, FrameLoadType::RedirectWithLockedBackForwardList, 0, 0);
905 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
907 void FrameLoader::loadArchive(Ref<Archive>&& archive)
909 ArchiveResource* mainResource = archive->mainResource();
910 ASSERT(mainResource);
914 ResourceResponse response(URL(), mainResource->mimeType(), mainResource->data().size(), mainResource->textEncoding());
915 SubstituteData substituteData(&mainResource->data(), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
917 ResourceRequest request(mainResource->url());
919 auto documentLoader = m_client.createDocumentLoader(request, substituteData);
920 documentLoader->setArchive(WTFMove(archive));
921 load(documentLoader.ptr());
924 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
926 String FrameLoader::outgoingReferrer() const
928 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
929 // for why we walk the parent chain for srcdoc documents.
930 Frame* frame = &m_frame;
931 while (frame && frame->document()->isSrcdocDocument()) {
932 frame = frame->tree().parent();
933 // Srcdoc documents cannot be top-level documents, by definition,
934 // because they need to be contained in iframes with the srcdoc.
938 return emptyString();
939 return frame->loader().m_outgoingReferrer;
942 String FrameLoader::outgoingOrigin() const
944 return m_frame.document()->securityOrigin().toString();
947 bool FrameLoader::checkIfFormActionAllowedByCSP(const URL& url, bool didReceiveRedirectResponse) const
949 if (m_submittedFormURL.isEmpty())
952 auto redirectResponseReceived = didReceiveRedirectResponse ? ContentSecurityPolicy::RedirectResponseReceived::Yes : ContentSecurityPolicy::RedirectResponseReceived::No;
953 return m_frame.document()->contentSecurityPolicy()->allowFormAction(url, redirectResponseReceived);
956 Frame* FrameLoader::opener()
961 void FrameLoader::setOpener(Frame* opener)
963 if (m_opener && !opener)
964 m_client.didDisownOpener();
967 m_opener->loader().m_openedFrames.remove(&m_frame);
969 opener->loader().m_openedFrames.add(&m_frame);
972 if (m_frame.document())
973 m_frame.document()->initSecurityContext();
976 // FIXME: This does not belong in FrameLoader!
977 void FrameLoader::handleFallbackContent()
979 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
980 if (!is<HTMLObjectElement>(owner))
982 downcast<HTMLObjectElement>(*owner).renderFallbackContent();
985 void FrameLoader::provisionalLoadStarted()
987 if (m_stateMachine.firstLayoutDone())
988 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
989 m_frame.navigationScheduler().cancel(true);
990 m_client.provisionalLoadStarted();
992 if (m_frame.isMainFrame()) {
993 if (auto* page = m_frame.page())
994 page->didStartProvisionalLoad();
998 void FrameLoader::resetMultipleFormSubmissionProtection()
1000 m_submittedFormURL = URL();
1003 void FrameLoader::updateFirstPartyForCookies()
1005 if (m_frame.tree().parent())
1006 setFirstPartyForCookies(m_frame.tree().parent()->document()->firstPartyForCookies());
1008 setFirstPartyForCookies(m_frame.document()->url());
1011 void FrameLoader::setFirstPartyForCookies(const URL& url)
1013 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
1014 frame->document()->setFirstPartyForCookies(url);
1017 // This does the same kind of work that didOpenURL does, except it relies on the fact
1018 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1019 void FrameLoader::loadInSameDocument(const URL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1021 // If we have a state object, we cannot also be a new navigation.
1022 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1024 // Update the data source's request with the new URL to fake the URL change
1025 URL oldURL = m_frame.document()->url();
1026 m_frame.document()->setURL(url);
1027 setOutgoingReferrer(url);
1028 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1029 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1030 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1031 // based on the current request. Must also happen before we openURL and displace the
1032 // scroll position, since adding the BF item will save away scroll state.
1034 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1035 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1036 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1037 // though its load is not yet done. I think this all works out OK, for one because
1038 // we have already saved away the scroll and doc state for the long slow load,
1039 // but it's not an obvious case.
1041 history().updateBackForwardListForFragmentScroll();
1044 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1046 history().updateForSameDocumentNavigation();
1048 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1050 m_frame.eventHandler().stopAutoscrollTimer();
1052 // It's important to model this as a load that starts and immediately finishes.
1053 // Otherwise, the parent frame may think we never finished loading.
1056 // We need to scroll to the fragment whether or not a hash change occurred, since
1057 // the user might have scrolled since the previous navigation.
1058 scrollToFragmentWithParentBoundary(url);
1060 m_isComplete = false;
1063 if (isNewNavigation) {
1064 // This will clear previousItem from the rest of the frame tree that didn't
1065 // doing any loading. We need to make a pass on this now, since for fragment
1066 // navigation we'll not go through a real load and reach Completed state.
1067 checkLoadComplete();
1070 m_client.dispatchDidNavigateWithinPage();
1072 m_frame.document()->statePopped(stateObject ? Ref<SerializedScriptValue> { *stateObject } : SerializedScriptValue::nullValue());
1073 m_client.dispatchDidPopStateWithinPage();
1076 m_frame.document()->enqueueHashchangeEvent(oldURL, url);
1077 m_client.dispatchDidChangeLocationWithinPage();
1080 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1081 m_client.didFinishLoad();
1084 bool FrameLoader::isComplete() const
1086 return m_isComplete;
1089 void FrameLoader::completed()
1091 Ref<Frame> protect(m_frame);
1093 for (Frame* descendant = m_frame.tree().traverseNext(&m_frame); descendant; descendant = descendant->tree().traverseNext(&m_frame))
1094 descendant->navigationScheduler().startTimer();
1096 if (Frame* parent = m_frame.tree().parent())
1097 parent->loader().checkCompleted();
1100 m_frame.view()->maintainScrollPositionAtAnchor(nullptr);
1103 void FrameLoader::started()
1105 for (Frame* frame = &m_frame; frame; frame = frame->tree().parent())
1106 frame->loader().m_isComplete = false;
1109 void FrameLoader::prepareForLoadStart()
1111 RELEASE_LOG_IF_ALLOWED("prepareForLoadStart: Starting frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
1113 m_progressTracker->progressStarted();
1114 m_client.dispatchDidStartProvisionalLoad();
1116 if (AXObjectCache::accessibilityEnabled()) {
1117 if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache()) {
1118 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadType::Reload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1119 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
1124 void FrameLoader::setupForReplace()
1126 m_client.revertToProvisionalState(m_documentLoader.get());
1127 setState(FrameStateProvisional);
1128 m_provisionalDocumentLoader = m_documentLoader;
1129 m_documentLoader = nullptr;
1133 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, Event* event, FormState* formState)
1135 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1136 auto protectFrame = makeRef(m_frame);
1138 URL url = request.resourceRequest().url();
1140 ASSERT(m_frame.document());
1141 if (!request.requester()->canDisplay(url)) {
1142 reportLocalLoadFailed(&m_frame, url.stringCenterEllipsizedToLength());
1146 String argsReferrer = request.resourceRequest().httpReferrer();
1147 if (argsReferrer.isEmpty())
1148 argsReferrer = outgoingReferrer();
1150 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), url, argsReferrer);
1151 if (request.shouldSendReferrer() == NeverSendReferrer)
1152 referrer = String();
1154 FrameLoadType loadType;
1155 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1156 loadType = FrameLoadType::Reload;
1157 else if (request.lockBackForwardList() == LockBackForwardList::Yes)
1158 loadType = FrameLoadType::RedirectWithLockedBackForwardList;
1160 loadType = FrameLoadType::Standard;
1162 if (request.resourceRequest().httpMethod() == "POST")
1163 loadPostRequest(request, referrer, loadType, event, formState);
1165 loadURL(request, referrer, loadType, event, formState);
1167 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1168 // load if frame names have changed.
1169 Frame* sourceFrame = formState ? formState->sourceDocument().frame() : &m_frame;
1171 sourceFrame = &m_frame;
1172 Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(request.frameName());
1173 if (targetFrame && targetFrame != sourceFrame) {
1174 if (Page* page = targetFrame->page())
1175 page->chrome().focus();
1179 static ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToApply(Frame& sourceFrame, ShouldOpenExternalURLsPolicy propagatedPolicy)
1181 if (!sourceFrame.isMainFrame())
1182 return ShouldOpenExternalURLsPolicy::ShouldNotAllow;
1183 if (ScriptController::processingUserGesture())
1184 return ShouldOpenExternalURLsPolicy::ShouldAllow;
1185 return propagatedPolicy;
1188 void FrameLoader::loadURL(const FrameLoadRequest& frameLoadRequest, const String& referrer, FrameLoadType newLoadType, Event* event, FormState* formState)
1190 if (m_inStopAllLoaders)
1193 Ref<Frame> protect(m_frame);
1195 String frameName = frameLoadRequest.frameName();
1196 AllowNavigationToInvalidURL allowNavigationToInvalidURL = frameLoadRequest.allowNavigationToInvalidURL();
1197 NewFrameOpenerPolicy openerPolicy = frameLoadRequest.newFrameOpenerPolicy();
1198 LockHistory lockHistory = frameLoadRequest.lockHistory();
1199 bool isFormSubmission = formState;
1201 const URL& newURL = frameLoadRequest.resourceRequest().url();
1202 ResourceRequest request(newURL);
1203 if (!referrer.isEmpty()) {
1204 request.setHTTPReferrer(referrer);
1205 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1206 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1208 if (&m_frame.tree().top() != &m_frame)
1209 request.setDomainForCachePartition(m_frame.tree().top().document()->securityOrigin().domainForCachePartition());
1211 addExtraFieldsToRequest(request, newLoadType, true);
1212 if (newLoadType == FrameLoadType::Reload || newLoadType == FrameLoadType::ReloadFromOrigin)
1213 request.setCachePolicy(ReloadIgnoringCacheData);
1215 ASSERT(newLoadType != FrameLoadType::Same);
1217 // The search for a target frame is done earlier in the case of form submission.
1218 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1219 if (targetFrame && targetFrame != &m_frame) {
1220 FrameLoadRequest newFrameLoadRequest(frameLoadRequest);
1221 newFrameLoadRequest.setFrameName("_self");
1222 targetFrame->loader().loadURL(newFrameLoadRequest, referrer, newLoadType, event, formState);
1226 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1229 NavigationAction action(request, newLoadType, isFormSubmission, event, frameLoadRequest.shouldOpenExternalURLsPolicy(), frameLoadRequest.downloadAttribute());
1231 if (!targetFrame && !frameName.isEmpty()) {
1232 action = action.copyWithShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(m_frame, frameLoadRequest.shouldOpenExternalURLsPolicy()));
1233 policyChecker().checkNewWindowPolicy(action, request, formState, frameName, [this, allowNavigationToInvalidURL, openerPolicy] (const ResourceRequest& request, FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
1234 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
1239 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1241 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1242 const String& httpMethod = request.httpMethod();
1244 // Make sure to do scroll to fragment processing even if the URL is
1245 // exactly the same so pages with '#' links and DHTML side effects
1247 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1248 oldDocumentLoader->setTriggeringAction(action);
1249 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1250 policyChecker().stopCheck();
1251 policyChecker().setLoadType(newLoadType);
1252 policyChecker().checkNavigationPolicy(request, false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this] (const ResourceRequest& request, FormState*, bool shouldContinue) {
1253 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
1258 // must grab this now, since this load may stop the previous load and clear this flag
1259 bool isRedirect = m_quickRedirectComing;
1260 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState, allowNavigationToInvalidURL);
1262 m_quickRedirectComing = false;
1263 if (m_provisionalDocumentLoader)
1264 m_provisionalDocumentLoader->setIsClientRedirect(true);
1265 } else if (sameURL && newLoadType != FrameLoadType::Reload && newLoadType != FrameLoadType::ReloadFromOrigin) {
1266 // Example of this case are sites that reload the same URL with a different cookie
1267 // driving the generated content, or a master frame with links that drive a target
1268 // frame, where the user has clicked on the same link repeatedly.
1269 m_loadType = FrameLoadType::Same;
1273 SubstituteData FrameLoader::defaultSubstituteDataForURL(const URL& url)
1275 if (!shouldTreatURLAsSrcdocDocument(url))
1276 return SubstituteData();
1277 String srcdoc = m_frame.ownerElement()->attributeWithoutSynchronization(srcdocAttr);
1278 ASSERT(!srcdoc.isNull());
1279 CString encodedSrcdoc = srcdoc.utf8();
1281 ResourceResponse response(URL(), ASCIILiteral("text/html"), encodedSrcdoc.length(), ASCIILiteral("UTF-8"));
1282 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), URL(), response, SubstituteData::SessionHistoryVisibility::Hidden);
1285 void FrameLoader::load(const FrameLoadRequest& passedRequest)
1287 FrameLoadRequest request(passedRequest);
1289 if (m_inStopAllLoaders)
1292 if (!request.frameName().isEmpty()) {
1293 Frame* frame = findFrameForNavigation(request.frameName());
1295 request.setShouldCheckNewWindowPolicy(false);
1296 if (&frame->loader() != this) {
1297 frame->loader().load(request);
1303 if (request.shouldCheckNewWindowPolicy()) {
1304 NavigationAction action(request.resourceRequest(), NavigationType::Other, passedRequest.shouldOpenExternalURLsPolicy());
1305 policyChecker().checkNewWindowPolicy(action, request.resourceRequest(), nullptr, request.frameName(), [this] (const ResourceRequest& request, FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
1306 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Suppress);
1312 if (!request.hasSubstituteData())
1313 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1315 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request.resourceRequest(), request.substituteData());
1316 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, request.shouldOpenExternalURLsPolicy());
1321 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, LockHistory lockHistory, FrameLoadType type, FormState* formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
1323 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1324 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, action.shouldOpenExternalURLsPolicy());
1326 if (lockHistory == LockHistory::Yes && m_documentLoader)
1327 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1329 loader->setTriggeringAction(action);
1330 if (m_documentLoader)
1331 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1333 loadWithDocumentLoader(loader.ptr(), type, formState, allowNavigationToInvalidURL);
1336 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1338 ResourceRequest& r = newDocumentLoader->request();
1339 addExtraFieldsToMainResourceRequest(r);
1342 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1343 r.setCachePolicy(ReloadIgnoringCacheData);
1344 type = FrameLoadType::Same;
1345 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadType::Reload)
1346 type = FrameLoadType::Reload;
1347 else if (m_loadType == FrameLoadType::RedirectWithLockedBackForwardList && !newDocumentLoader->unreachableURL().isEmpty() && newDocumentLoader->substituteData().isValid())
1348 type = FrameLoadType::RedirectWithLockedBackForwardList;
1350 type = FrameLoadType::Standard;
1352 if (m_documentLoader)
1353 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1355 // When we loading alternate content for an unreachable URL that we're
1356 // visiting in the history list, we treat it as a reload so the history list
1357 // is appropriately maintained.
1359 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadType::Reload" ...
1360 // shouldn't a more explicit type of reload be defined, that means roughly
1361 // "load without affecting history" ?
1362 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1363 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1364 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1365 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1366 history().saveDocumentAndScrollState();
1368 ASSERT(type == FrameLoadType::Standard);
1369 type = FrameLoadType::Reload;
1372 loadWithDocumentLoader(newDocumentLoader, type, 0, AllowNavigationToInvalidURL::Yes);
1375 static void logNavigation(MainFrame& frame, const URL& destinationURL, FrameLoadType type)
1380 String navigationDescription;
1382 case FrameLoadType::Standard:
1383 navigationDescription = ASCIILiteral("standard");
1385 case FrameLoadType::Back:
1386 navigationDescription = ASCIILiteral("back");
1388 case FrameLoadType::Forward:
1389 navigationDescription = ASCIILiteral("forward");
1391 case FrameLoadType::IndexedBackForward:
1392 navigationDescription = ASCIILiteral("indexedBackForward");
1394 case FrameLoadType::Reload:
1395 navigationDescription = ASCIILiteral("reload");
1397 case FrameLoadType::Same:
1398 navigationDescription = ASCIILiteral("same");
1400 case FrameLoadType::ReloadFromOrigin:
1401 navigationDescription = ASCIILiteral("reloadFromOrigin");
1403 case FrameLoadType::Replace:
1404 case FrameLoadType::RedirectWithLockedBackForwardList:
1405 // Not logging those for now.
1408 frame.page()->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::navigationKey(), navigationDescription, ShouldSample::No);
1409 #if ENABLE(PUBLIC_SUFFIX_LIST)
1410 String domain = topPrivatelyControlledDomain(destinationURL.host());
1411 if (!domain.isEmpty())
1412 frame.page()->diagnosticLoggingClient().logDiagnosticMessageWithEnhancedPrivacy(DiagnosticLoggingKeys::domainVisitedKey(), domain, ShouldSample::No);
1416 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, FormState* formState, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
1418 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1419 Ref<Frame> protect(m_frame);
1421 ASSERT(m_client.hasWebView());
1423 // Unfortunately the view must be non-nil, this is ultimately due
1424 // to parser requiring a FrameView. We should fix this dependency.
1426 ASSERT(m_frame.view());
1428 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1431 if (m_frame.document())
1432 m_previousURL = m_frame.document()->url();
1434 const URL& newURL = loader->request().url();
1436 // Log main frame navigation types.
1437 if (m_frame.isMainFrame()) {
1438 logNavigation(static_cast<MainFrame&>(m_frame), newURL, type);
1439 static_cast<MainFrame&>(m_frame).performanceLogging().didReachPointOfInterest(PerformanceLogging::MainFrameLoadStarted);
1442 policyChecker().setLoadType(type);
1443 bool isFormSubmission = formState;
1445 const String& httpMethod = loader->request().httpMethod();
1447 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker().loadType(), newURL)) {
1448 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1449 NavigationAction action(loader->request(), policyChecker().loadType(), isFormSubmission);
1451 oldDocumentLoader->setTriggeringAction(action);
1452 oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
1453 policyChecker().stopCheck();
1454 policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this] (const ResourceRequest& request, FormState*, bool shouldContinue) {
1455 continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
1460 if (Frame* parent = m_frame.tree().parent())
1461 loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
1463 policyChecker().stopCheck();
1464 setPolicyDocumentLoader(loader);
1465 if (loader->triggeringAction().isEmpty())
1466 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker().loadType(), isFormSubmission));
1468 if (Element* ownerElement = m_frame.ownerElement()) {
1469 // We skip dispatching the beforeload event if we've already
1470 // committed a real document load because the event would leak
1471 // subsequent activity by the frame which the parent frame isn't
1472 // supposed to learn. For example, if the child frame navigated to
1473 // a new URL, the parent frame shouldn't learn the URL.
1474 if (!m_stateMachine.committedFirstRealDocumentLoad()
1475 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1476 continueLoadAfterNavigationPolicy(loader->request(), formState, false, allowNavigationToInvalidURL);
1481 policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, loader, formState, [this, allowNavigationToInvalidURL] (const ResourceRequest& request, FormState* formState, bool shouldContinue) {
1482 continueLoadAfterNavigationPolicy(request, formState, shouldContinue, allowNavigationToInvalidURL);
1486 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1488 ASSERT(!url.isEmpty());
1492 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to load local resource: " + url);
1495 void FrameLoader::reportBlockedPortFailed(Frame* frame, const String& url)
1497 ASSERT(!url.isEmpty());
1501 frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to use restricted network port: " + url);
1504 const ResourceRequest& FrameLoader::initialRequest() const
1506 return activeDocumentLoader()->originalRequest();
1509 bool FrameLoader::willLoadMediaElementURL(URL& url)
1512 // MobileStore depends on the iOS 4.0 era client delegate method because webView:resource:willSendRequest:redirectResponse:fromDataSource
1513 // doesn't let them tell when a load request is coming from a media element. See <rdar://problem/8266916> for more details.
1514 if (IOSApplication::isMobileStore())
1515 return m_client.shouldLoadMediaElementURL(url);
1518 ResourceRequest request(url);
1520 unsigned long identifier;
1521 ResourceError error;
1522 requestFromDelegate(request, identifier, error);
1523 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String()), 0, -1, -1, error);
1525 url = request.url();
1527 return error.isNull();
1530 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1532 URL unreachableURL = docLoader->unreachableURL();
1534 if (unreachableURL.isEmpty())
1537 if (!isBackForwardLoadType(policyChecker().loadType()))
1540 // We only treat unreachableURLs specially during the delegate callbacks
1541 // for provisional load errors and navigation policy decisions. The former
1542 // case handles well-formed URLs that can't be loaded, and the latter
1543 // case handles malformed URLs and unknown schemes. Loading alternate content
1544 // at other times behaves like a standard load.
1545 if (policyChecker().delegateIsDecidingNavigationPolicy() || policyChecker().delegateIsHandlingUnimplementablePolicy())
1546 return m_policyDocumentLoader && unreachableURL == m_policyDocumentLoader->request().url();
1548 return unreachableURL == m_provisionalLoadErrorBeingHandledURL;
1551 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1553 if (!m_documentLoader)
1556 ResourceRequest request = m_documentLoader->request();
1557 URL unreachableURL = m_documentLoader->unreachableURL();
1558 if (!unreachableURL.isEmpty())
1559 request.setURL(unreachableURL);
1561 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1562 // We should ask the user for confirmation in this case.
1563 request.setCachePolicy(ReturnCacheDataElseLoad);
1565 Ref<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1566 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1568 setPolicyDocumentLoader(loader.ptr());
1570 loader->setOverrideEncoding(encoding);
1572 loadWithDocumentLoader(loader.ptr(), FrameLoadType::Reload, 0, AllowNavigationToInvalidURL::Yes);
1575 void FrameLoader::reload(bool endToEndReload, bool contentBlockersEnabled)
1577 if (!m_documentLoader)
1580 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1581 // Reloading in this case will lose the current contents (see 4151001).
1582 if (m_documentLoader->request().url().isEmpty())
1585 // Replace error-page URL with the URL we were trying to reach.
1586 ResourceRequest initialRequest = m_documentLoader->request();
1587 URL unreachableURL = m_documentLoader->unreachableURL();
1588 if (!unreachableURL.isEmpty())
1589 initialRequest.setURL(unreachableURL);
1591 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1592 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1593 Ref<DocumentLoader> loader = m_client.createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1594 applyShouldOpenExternalURLsPolicyToNewDocumentLoader(loader, m_documentLoader->shouldOpenExternalURLsPolicyToPropagate());
1596 loader->setUserContentExtensionsEnabled(contentBlockersEnabled);
1598 ResourceRequest& request = loader->request();
1600 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1601 request.setCachePolicy(ReloadIgnoringCacheData);
1603 // If we're about to re-post, set up action so the application can warn the user.
1604 if (request.httpMethod() == "POST")
1605 loader->setTriggeringAction(NavigationAction(request, NavigationType::FormResubmitted));
1607 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1609 loadWithDocumentLoader(loader.ptr(), endToEndReload ? FrameLoadType::ReloadFromOrigin : FrameLoadType::Reload, 0, AllowNavigationToInvalidURL::Yes);
1612 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1614 ASSERT(!m_frame.document() || m_frame.document()->pageCacheState() != Document::InPageCache);
1615 if (m_pageDismissalEventBeingDispatched != PageDismissalType::None)
1618 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1619 if (m_inStopAllLoaders)
1622 // Calling stopLoading() on the provisional document loader can blow away
1623 // the frame from underneath.
1624 Ref<Frame> protect(m_frame);
1626 m_inStopAllLoaders = true;
1628 policyChecker().stopCheck();
1630 // If no new load is in progress, we should clear the provisional item from history
1631 // before we call stopLoading.
1632 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1633 history().setProvisionalItem(nullptr);
1635 for (RefPtr<Frame> child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
1636 child->loader().stopAllLoaders(clearProvisionalItemPolicy);
1637 if (m_provisionalDocumentLoader)
1638 m_provisionalDocumentLoader->stopLoading();
1639 if (m_documentLoader)
1640 m_documentLoader->stopLoading();
1642 setProvisionalDocumentLoader(nullptr);
1644 m_checkTimer.stop();
1646 m_inStopAllLoaders = false;
1649 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1651 // Calling stopAllLoaders can cause the frame to be deallocated, including the frame loader.
1652 Ref<Frame> protectedFrame(m_frame);
1657 // Lay out immediately when stopping to immediately clear the old page if we just committed this one
1658 // but haven't laid out/painted yet.
1659 // FIXME: Is this behavior specific to iOS? Or should we expose a setting to toggle this behavior?
1660 if (m_frame.view() && !m_frame.view()->didFirstLayout())
1661 m_frame.view()->layout();
1664 if (deferCheckLoadComplete)
1665 scheduleCheckLoadComplete();
1666 else if (m_frame.page())
1667 checkLoadComplete();
1670 DocumentLoader* FrameLoader::activeDocumentLoader() const
1672 if (m_state == FrameStateProvisional)
1673 return m_provisionalDocumentLoader.get();
1674 return m_documentLoader.get();
1677 bool FrameLoader::isLoading() const
1679 DocumentLoader* docLoader = activeDocumentLoader();
1682 return docLoader->isLoading();
1685 bool FrameLoader::frameHasLoaded() const
1687 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1690 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1692 if (!loader && !m_documentLoader)
1695 ASSERT(loader != m_documentLoader);
1696 ASSERT(!loader || loader->frameLoader() == this);
1698 m_client.prepareForDataSourceReplacement();
1701 // detachChildren() can trigger this frame's unload event, and therefore
1702 // script can run and do just about anything. For example, an unload event that calls
1703 // document.write("") on its parent frame can lead to a recursive detachChildren()
1704 // invocation for this frame. In that case, we can end up at this point with a
1705 // loader that hasn't been deleted but has been detached from its frame. Such a
1706 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1707 // state if we try to use it.
1708 if (loader && !loader->frame())
1711 if (m_documentLoader)
1712 m_documentLoader->detachFromFrame();
1714 m_documentLoader = loader;
1717 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1719 if (m_policyDocumentLoader == loader)
1723 loader->attachToFrame(m_frame);
1724 if (m_policyDocumentLoader
1725 && m_policyDocumentLoader != m_provisionalDocumentLoader
1726 && m_policyDocumentLoader != m_documentLoader)
1727 m_policyDocumentLoader->detachFromFrame();
1729 m_policyDocumentLoader = loader;
1732 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1734 ASSERT(!loader || !m_provisionalDocumentLoader);
1735 ASSERT(!loader || loader->frameLoader() == this);
1737 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1738 m_provisionalDocumentLoader->detachFromFrame();
1740 m_provisionalDocumentLoader = loader;
1743 void FrameLoader::setState(FrameState newState)
1745 FrameState oldState = m_state;
1748 if (newState == FrameStateProvisional)
1749 provisionalLoadStarted();
1750 else if (newState == FrameStateComplete) {
1751 frameLoadCompleted();
1752 if (m_documentLoader)
1753 m_documentLoader->stopRecordingResponses();
1754 if (m_frame.isMainFrame() && oldState != newState)
1755 static_cast<MainFrame&>(m_frame).didCompleteLoad();
1759 void FrameLoader::clearProvisionalLoad()
1761 setProvisionalDocumentLoader(nullptr);
1762 m_progressTracker->progressCompleted();
1763 setState(FrameStateComplete);
1766 void FrameLoader::commitProvisionalLoad()
1768 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1769 Ref<Frame> protect(m_frame);
1771 std::unique_ptr<CachedPage> cachedPage;
1772 if (m_loadingFromCachedPage && history().provisionalItem())
1773 cachedPage = PageCache::singleton().take(*history().provisionalItem(), m_frame.page());
1775 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame.tree().uniqueName().string().utf8().data(),
1776 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
1777 pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>");
1779 willTransitionToCommitted();
1781 if (!m_frame.tree().parent() && history().currentItem()) {
1782 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1783 // We are doing this here because we know for sure that a new page is about to be loaded.
1784 PageCache::singleton().addIfCacheable(*history().currentItem(), m_frame.page());
1786 WebCore::jettisonExpensiveObjectsOnTopLevelNavigation();
1789 if (m_loadType != FrameLoadType::Replace)
1790 closeOldDataSources();
1792 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1793 m_client.makeRepresentation(pdl.get());
1795 transitionToCommitted(cachedPage.get());
1797 if (pdl && m_documentLoader) {
1798 // Check if the destination page is allowed to access the previous page's timing information.
1799 Ref<SecurityOrigin> securityOrigin(SecurityOrigin::create(pdl->request().url()));
1800 m_documentLoader->timing().setHasSameOriginAsPreviousDocument(securityOrigin.get().canRequest(m_previousURL));
1803 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1804 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1805 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1806 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1807 if (m_sentRedirectNotification)
1808 clientRedirectCancelledOrFinished(false);
1810 if (cachedPage && cachedPage->document()) {
1812 // FIXME: CachedPage::restore() would dispatch viewport change notification. However UIKit expects load
1813 // commit to happen before any changes to viewport arguments and dealing with this there is difficult.
1814 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(true);
1816 prepareForCachedPageRestore();
1818 // Start request for the main resource and dispatch didReceiveResponse before the load is committed for
1819 // consistency with all other loads. See https://bugs.webkit.org/show_bug.cgi?id=150927.
1820 ResourceError mainResouceError;
1821 unsigned long mainResourceIdentifier;
1822 ResourceRequest mainResourceRequest(cachedPage->documentLoader()->request());
1823 requestFromDelegate(mainResourceRequest, mainResourceIdentifier, mainResouceError);
1824 notifier().dispatchDidReceiveResponse(cachedPage->documentLoader(), mainResourceIdentifier, cachedPage->documentLoader()->response());
1826 std::optional<HasInsecureContent> hasInsecureContent = cachedPage->cachedMainFrame()->hasInsecureContent();
1828 // FIXME: This API should be turned around so that we ground CachedPage into the Page.
1829 cachedPage->restore(*m_frame.page());
1831 dispatchDidCommitLoad(hasInsecureContent);
1833 m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(false);
1834 m_frame.page()->chrome().dispatchViewportPropertiesDidChange(m_frame.page()->viewportArguments());
1837 auto& title = m_documentLoader->title();
1838 if (!title.string.isNull())
1839 m_client.dispatchDidReceiveTitle(title);
1841 // Send remaining notifications for the main resource.
1842 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), mainResourceIdentifier, mainResourceRequest, ResourceResponse(),
1843 nullptr, static_cast<int>(m_documentLoader->response().expectedContentLength()), 0, mainResouceError);
1849 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame.tree().uniqueName().string().utf8().data(),
1850 m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
1852 if (m_loadType == FrameLoadType::Standard && m_documentLoader->isClientRedirect())
1853 history().updateForClientRedirect();
1855 if (m_loadingFromCachedPage) {
1856 // Note, didReceiveDocType is expected to be called for cached pages. See <rdar://problem/5906758> for more details.
1857 if (auto* page = m_frame.page())
1858 page->chrome().didReceiveDocType(m_frame);
1859 m_frame.document()->resume(ActiveDOMObject::PageCache);
1861 // Force a layout to update view size and thereby update scrollbars.
1863 if (!m_client.forceLayoutOnRestoreFromPageCache())
1864 m_frame.view()->forceLayout();
1866 m_frame.view()->forceLayout();
1869 // Main resource delegates were already sent, so we skip the first response here.
1870 for (unsigned i = 1; i < m_documentLoader->responses().size(); ++i) {
1871 const auto& response = m_documentLoader->responses()[i];
1872 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1873 ResourceError error;
1874 unsigned long identifier;
1875 ResourceRequest request(response.url());
1876 requestFromDelegate(request, identifier, error);
1877 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1878 // However, with today's computers and networking speeds, this won't happen in practice.
1879 // Could be an issue with a giant local file.
1880 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1883 // FIXME: Why only this frame and not parent frames?
1884 checkLoadCompleteForThisFrame();
1888 void FrameLoader::transitionToCommitted(CachedPage* cachedPage)
1890 ASSERT(m_client.hasWebView());
1891 ASSERT(m_state == FrameStateProvisional);
1893 if (m_state != FrameStateProvisional)
1896 if (FrameView* view = m_frame.view()) {
1897 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
1898 scrollAnimator->cancelAnimations();
1901 m_client.setCopiesOnScroll();
1902 history().updateForCommit();
1904 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1905 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1906 // or the two will stomp each other.
1907 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1908 if (m_documentLoader)
1910 if (pdl != m_provisionalDocumentLoader)
1913 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1914 if (m_documentLoader)
1915 m_documentLoader->stopLoadingSubresources();
1916 if (m_documentLoader)
1917 m_documentLoader->stopLoadingPlugIns();
1919 setDocumentLoader(m_provisionalDocumentLoader.get());
1920 setProvisionalDocumentLoader(nullptr);
1922 if (pdl != m_documentLoader) {
1923 ASSERT(m_state == FrameStateComplete);
1927 setState(FrameStateCommittedPage);
1929 // Handle adding the URL to the back/forward list.
1930 DocumentLoader* dl = m_documentLoader.get();
1932 switch (m_loadType) {
1933 case FrameLoadType::Forward:
1934 case FrameLoadType::Back:
1935 case FrameLoadType::IndexedBackForward:
1936 if (m_frame.page()) {
1937 // If the first load within a frame is a navigation within a back/forward list that was attached
1938 // without any of the items being loaded then we need to update the history in a similar manner as
1939 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1940 if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame.isMainFrame())
1941 history().updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1943 history().updateForBackForwardNavigation();
1945 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1946 if (history().currentItem() && !cachedPage)
1947 m_pendingStateObject = history().currentItem()->stateObject();
1949 // Create a document view for this document, or used the cached view.
1951 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1952 ASSERT(cachedDocumentLoader);
1953 cachedDocumentLoader->attachToFrame(m_frame);
1954 m_client.transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1956 m_client.transitionToCommittedForNewPage();
1960 case FrameLoadType::Reload:
1961 case FrameLoadType::ReloadFromOrigin:
1962 case FrameLoadType::Same:
1963 case FrameLoadType::Replace:
1964 history().updateForReload();
1965 m_client.transitionToCommittedForNewPage();
1968 case FrameLoadType::Standard:
1969 history().updateForStandardLoad();
1971 m_frame.view()->setScrollbarsSuppressed(true);
1972 m_client.transitionToCommittedForNewPage();
1975 case FrameLoadType::RedirectWithLockedBackForwardList:
1976 history().updateForRedirectWithLockedBackForwardList();
1977 m_client.transitionToCommittedForNewPage();
1980 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1981 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1983 ASSERT_NOT_REACHED();
1986 m_documentLoader->writer().setMIMEType(dl->responseMIMEType());
1988 // Tell the client we've committed this URL.
1989 ASSERT(m_frame.view());
1991 if (m_stateMachine.creatingInitialEmptyDocument())
1994 if (!m_stateMachine.committedFirstRealDocumentLoad())
1995 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1998 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
2000 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
2001 // the redirect succeeded. We should either rename this API, or add a new method, like
2002 // -webView:didFinishClientRedirectForFrame:
2003 m_client.dispatchDidCancelClientRedirect();
2005 if (!cancelWithLoadInProgress)
2006 m_quickRedirectComing = false;
2008 m_sentRedirectNotification = false;
2011 void FrameLoader::clientRedirected(const URL& url, double seconds, double fireDate, LockBackForwardList lockBackForwardList)
2013 m_client.dispatchWillPerformClientRedirect(url, seconds, fireDate);
2015 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
2016 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
2017 m_sentRedirectNotification = true;
2019 // If a "quick" redirect comes in, we set a special mode so we treat the next
2020 // load as part of the original navigation. If we don't have a document loader, we have
2021 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
2022 // Loads triggered by JavaScript form submissions never count as quick redirects.
2023 m_quickRedirectComing = (lockBackForwardList == LockBackForwardList::Yes || history().currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
2026 bool FrameLoader::shouldReload(const URL& currentURL, const URL& destinationURL)
2028 // This function implements the rule: "Don't reload if navigating by fragment within
2029 // the same URL, but do reload if going to a new URL or to the same URL with no
2030 // fragment identifier at all."
2031 if (!destinationURL.hasFragmentIdentifier())
2033 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
2036 void FrameLoader::closeOldDataSources()
2038 // FIXME: Is it important for this traversal to be postorder instead of preorder?
2039 // If so, add helpers for postorder traversal, and use them. If not, then lets not
2040 // use a recursive algorithm here.
2041 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
2042 child->loader().closeOldDataSources();
2044 if (m_documentLoader)
2045 m_client.dispatchWillClose();
2047 m_client.setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2050 void FrameLoader::prepareForCachedPageRestore()
2052 ASSERT(!m_frame.tree().parent());
2053 ASSERT(m_frame.page());
2054 ASSERT(m_frame.isMainFrame());
2056 m_frame.navigationScheduler().cancel();
2058 // We still have to close the previous part page.
2061 // Delete old status bar messages (if it _was_ activated on last URL).
2062 if (m_frame.script().canExecuteScripts(NotAboutToExecuteScript)) {
2063 DOMWindow* window = m_frame.document()->domWindow();
2064 window->setStatus(String());
2065 window->setDefaultStatus(String());
2069 void FrameLoader::open(CachedFrameBase& cachedFrame)
2071 m_isComplete = false;
2073 // Don't re-emit the load event.
2074 m_didCallImplicitClose = true;
2076 URL url = cachedFrame.url();
2078 // FIXME: I suspect this block of code doesn't do anything.
2079 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2083 Document* document = cachedFrame.document();
2085 ASSERT(document->domWindow());
2087 clear(document, true, true, cachedFrame.isMainFrame());
2089 document->setPageCacheState(Document::NotInPageCache);
2091 m_needsClear = true;
2092 m_isComplete = false;
2093 m_didCallImplicitClose = false;
2094 m_outgoingReferrer = url.string();
2096 FrameView* view = cachedFrame.view();
2098 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2100 view->setWasScrolledByUser(false);
2102 std::optional<IntRect> previousViewFrameRect = m_frame.view() ? m_frame.view()->frameRect() : std::optional<IntRect>(std::nullopt);
2103 m_frame.setView(view);
2105 // Use the previous ScrollView's frame rect.
2106 if (previousViewFrameRect)
2107 view->setFrameRect(previousViewFrameRect.value());
2109 m_frame.setDocument(document);
2110 document->domWindow()->resumeFromDocumentSuspension();
2112 updateFirstPartyForCookies();
2114 cachedFrame.restore();
2117 bool FrameLoader::isHostedByObjectElement() const
2119 HTMLFrameOwnerElement* owner = m_frame.ownerElement();
2120 return owner && owner->hasTagName(objectTag);
2123 bool FrameLoader::isReplacing() const
2125 return m_loadType == FrameLoadType::Replace;
2128 void FrameLoader::setReplacing()
2130 m_loadType = FrameLoadType::Replace;
2133 bool FrameLoader::subframeIsLoading() const
2135 // It's most likely that the last added frame is the last to load so we walk backwards.
2136 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling()) {
2137 FrameLoader& childLoader = child->loader();
2138 DocumentLoader* documentLoader = childLoader.documentLoader();
2139 if (documentLoader && documentLoader->isLoadingInAPISense())
2141 documentLoader = childLoader.provisionalDocumentLoader();
2142 if (documentLoader && documentLoader->isLoadingInAPISense())
2144 documentLoader = childLoader.policyDocumentLoader();
2151 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2153 m_client.willChangeTitle(loader);
2156 FrameLoadType FrameLoader::loadType() const
2161 CachePolicy FrameLoader::subresourceCachePolicy() const
2163 if (Page* page = m_frame.page()) {
2164 if (page->isResourceCachingDisabled())
2165 return CachePolicyReload;
2169 return CachePolicyVerify;
2171 if (m_loadType == FrameLoadType::ReloadFromOrigin)
2172 return CachePolicyReload;
2174 if (Frame* parentFrame = m_frame.tree().parent()) {
2175 CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
2176 if (parentCachePolicy != CachePolicyVerify)
2177 return parentCachePolicy;
2180 switch (m_loadType) {
2181 case FrameLoadType::Reload:
2182 return CachePolicyRevalidate;
2183 case FrameLoadType::Back:
2184 case FrameLoadType::Forward:
2185 case FrameLoadType::IndexedBackForward:
2186 return CachePolicyHistoryBuffer;
2187 case FrameLoadType::ReloadFromOrigin:
2188 ASSERT_NOT_REACHED(); // Already handled above.
2189 return CachePolicyReload;
2190 case FrameLoadType::RedirectWithLockedBackForwardList:
2191 case FrameLoadType::Replace:
2192 case FrameLoadType::Same:
2193 case FrameLoadType::Standard:
2194 return CachePolicyVerify;
2197 RELEASE_ASSERT_NOT_REACHED();
2198 return CachePolicyVerify;
2201 void FrameLoader::checkLoadCompleteForThisFrame()
2203 ASSERT(m_client.hasWebView());
2206 case FrameStateProvisional: {
2207 // FIXME: Prohibiting any provisional load failures from being sent to clients
2208 // while handling provisional load failures is too heavy. For example, the current
2209 // load will fail to cancel another ongoing load. That might prevent clients' page
2210 // load state being handled properly.
2211 if (!m_provisionalLoadErrorBeingHandledURL.isEmpty())
2214 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2218 // If we've received any errors we may be stuck in the provisional state and actually complete.
2219 const ResourceError& error = pdl->mainDocumentError();
2223 // Check all children first.
2224 RefPtr<HistoryItem> item;
2225 if (Page* page = m_frame.page())
2226 if (isBackForwardLoadType(loadType()))
2227 // Reset the back forward list to the last committed history item at the top level.
2228 item = page->mainFrame().loader().history().currentItem();
2230 // Only reset if we aren't already going to a new provisional item.
2231 bool shouldReset = !history().provisionalItem();
2232 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2233 m_provisionalLoadErrorBeingHandledURL = m_provisionalDocumentLoader->url();
2234 m_client.dispatchDidFailProvisionalLoad(error);
2235 #if ENABLE(CONTENT_FILTERING)
2236 if (auto contentFilter = pdl->contentFilter())
2237 contentFilter->handleProvisionalLoadFailure(error);
2239 m_provisionalLoadErrorBeingHandledURL = { };
2241 ASSERT(!pdl->isLoading());
2243 // If we're in the middle of loading multipart data, we need to restore the document loader.
2244 if (isReplacing() && !m_documentLoader.get())
2245 setDocumentLoader(m_provisionalDocumentLoader.get());
2247 // Finish resetting the load state, but only if another load hasn't been started by the
2248 // delegate callback.
2249 if (pdl == m_provisionalDocumentLoader)
2250 clearProvisionalLoad();
2251 else if (activeDocumentLoader()) {
2252 URL unreachableURL = activeDocumentLoader()->unreachableURL();
2253 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2254 shouldReset = false;
2257 if (shouldReset && item)
2258 if (Page* page = m_frame.page()) {
2259 page->backForward().setCurrentItem(item.get());
2260 m_frame.loader().client().updateGlobalHistoryItemForPage();
2265 case FrameStateCommittedPage: {
2266 DocumentLoader* dl = m_documentLoader.get();
2267 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2270 setState(FrameStateComplete);
2272 // FIXME: Is this subsequent work important if we already navigated away?
2273 // Maybe there are bugs because of that, or extra work we can skip because
2274 // the new page is ready.
2276 m_client.forceLayoutForNonHTML();
2278 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2279 if (m_frame.page()) {
2280 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadType::Reload || m_loadType == FrameLoadType::ReloadFromOrigin)
2281 history().restoreScrollPositionAndViewState();
2284 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2287 m_progressTracker->progressCompleted();
2288 Page* page = m_frame.page();
2290 if (m_frame.isMainFrame())
2291 page->didFinishLoad();
2294 const ResourceError& error = dl->mainDocumentError();
2296 AXObjectCache::AXLoadingEvent loadingEvent;
2297 if (!error.isNull()) {
2298 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());
2299 m_client.dispatchDidFailLoad(error);
2300 loadingEvent = AXObjectCache::AXLoadingFailed;
2302 RELEASE_LOG_IF_ALLOWED("checkLoadCompleteForThisFrame: Finished frame load (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
2303 #if ENABLE(DATA_DETECTION)
2304 auto* document = m_frame.document();
2305 if (m_frame.settings().dataDetectorTypes() != DataDetectorTypeNone && document) {
2306 if (auto* documentElement = document->documentElement()) {
2307 RefPtr<Range> documentRange = makeRange(firstPositionInNode(documentElement), lastPositionInNode(documentElement));
2308 m_frame.setDataDetectionResults(DataDetection::detectContentInRange(documentRange, m_frame.settings().dataDetectorTypes(), m_client.dataDetectionContext()));
2309 if (m_frame.isMainFrame())
2310 m_client.dispatchDidFinishDataDetection(m_frame.dataDetectionResults());
2314 m_client.dispatchDidFinishLoad();
2315 loadingEvent = AXObjectCache::AXLoadingFinished;
2318 // Notify accessibility.
2319 if (auto* document = m_frame.document()) {
2320 if (AXObjectCache* cache = document->existingAXObjectCache())
2321 cache->frameLoadingEventNotification(&m_frame, loadingEvent);
2324 // The above calls to dispatchDidFinishLoad() might have detached the Frame
2325 // from its Page and also might have caused Page to be deleted.
2326 // Don't assume 'page' is still available to use.
2327 if (m_frame.isMainFrame() && m_frame.page()) {
2328 ASSERT(&m_frame.page()->mainFrame() == &m_frame);
2329 m_frame.page()->diagnosticLoggingClient().logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageLoadedKey(), emptyString(), error.isNull() ? DiagnosticLoggingResultPass : DiagnosticLoggingResultFail, ShouldSample::Yes);
2335 case FrameStateComplete:
2336 m_loadType = FrameLoadType::Standard;
2337 frameLoadCompleted();
2341 ASSERT_NOT_REACHED();
2344 void FrameLoader::continueLoadAfterWillSubmitForm()
2346 if (!m_provisionalDocumentLoader)
2349 prepareForLoadStart();
2351 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2352 // so we need to null check it again.
2353 if (!m_provisionalDocumentLoader) {
2354 RELEASE_LOG_IF_ALLOWED("continueLoadAfterWillSubmitForm: Frame load canceled (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
2358 DocumentLoader* activeDocLoader = activeDocumentLoader();
2359 if (activeDocLoader && activeDocLoader->isLoadingMainResource()) {
2360 RELEASE_LOG_IF_ALLOWED("continueLoadAfterWillSubmitForm: Main frame already being loaded (frame = %p, main = %d)", &m_frame, m_frame.isMainFrame());
2364 m_loadingFromCachedPage = false;
2365 m_provisionalDocumentLoader->startLoadingMainResource();
2368 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2370 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2371 // The originalURL is defined as the URL of the page where the download was initiated.
2373 if (m_frame.document()) {
2374 originalURL = m_frame.document()->firstPartyForCookies();
2375 // If there is no main document URL, it means that this document is newly opened and just for download purpose.
2376 // In this case, we need to set the originalURL to this document's opener's main document URL.
2377 if (originalURL.isEmpty() && opener() && opener()->document())
2378 originalURL = opener()->document()->firstPartyForCookies();
2380 // If the originalURL is the same as the requested URL, we are processing a download
2381 // initiated directly without a page and do not need to specify the originalURL.
2382 if (originalURL == request.url())
2383 request.setFirstPartyForCookies(URL());
2385 request.setFirstPartyForCookies(originalURL);
2388 void FrameLoader::didReachLayoutMilestone(LayoutMilestones milestones)
2390 ASSERT(m_frame.isMainFrame());
2392 m_client.dispatchDidReachLayoutMilestone(milestones);
2395 void FrameLoader::didFirstLayout()
2398 // Only send layout-related delegate callbacks synchronously for the main frame to
2399 // avoid reentering layout for the main frame while delivering a layout-related delegate
2400 // callback for a subframe.
2401 if (&m_frame != &m_frame.page()->mainFrame())
2404 if (m_frame.page() && isBackForwardLoadType(m_loadType))
2405 history().restoreScrollPositionAndViewState();
2407 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2408 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2411 void FrameLoader::frameLoadCompleted()
2413 // Note: Can be called multiple times.
2415 m_client.frameLoadCompleted();
2417 history().updateForFrameLoadCompleted();
2419 // After a canceled provisional load, firstLayoutDone is false.
2420 // Reset it to true if we're displaying a page.
2421 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2422 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2425 void FrameLoader::detachChildren()
2427 // detachChildren() will fire the unload event in each subframe and the
2428 // HTML specification states that the parent document's ignore-opens-during-unload counter while
2429 // this event is being fired in its subframes:
2430 // https://html.spec.whatwg.org/multipage/browsers.html#unload-a-document
2431 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2433 Vector<Ref<Frame>, 16> childrenToDetach;
2434 childrenToDetach.reserveInitialCapacity(m_frame.tree().childCount());
2435 for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling())
2436 childrenToDetach.uncheckedAppend(*child);
2437 for (auto& child : childrenToDetach)
2438 child->loader().detachFromParent();
2441 void FrameLoader::closeAndRemoveChild(Frame& child)
2443 child.tree().detachFromParent();
2445 child.setView(nullptr);
2446 if (child.ownerElement() && child.page())
2447 child.page()->decrementSubframeCount();
2448 child.willDetachPage();
2449 child.detachFromPage();
2451 m_frame.tree().removeChild(child);
2454 // Called every time a resource is completely loaded or an error is received.
2455 void FrameLoader::checkLoadComplete()
2457 ASSERT(m_client.hasWebView());
2459 m_shouldCallCheckLoadComplete = false;
2461 if (!m_frame.page())
2464 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2465 // is currently needed in order to null out the previous history item for all frames.
2466 Vector<Ref<Frame>, 16> frames;
2467 for (Frame* frame = &m_frame.mainFrame(); frame; frame = frame->tree().traverseNext())
2468 frames.append(*frame);
2470 // To process children before their parents, iterate the vector backwards.
2471 for (auto frame = frames.rbegin(); frame != frames.rend(); ++frame) {
2472 if ((*frame)->page())
2473 (*frame)->loader().checkLoadCompleteForThisFrame();
2477 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2480 return m_frame.document()->cachedResourceLoader().requestCount();
2483 for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
2484 count += frame->document()->cachedResourceLoader().requestCount();
2488 String FrameLoader::userAgent(const URL& url) const
2490 return m_client.userAgent(url);
2493 void FrameLoader::dispatchOnloadEvents()
2495 m_client.dispatchDidDispatchOnloadEvents();
2497 if (documentLoader())
2498 documentLoader()->dispatchOnloadEvents();
2501 void FrameLoader::frameDetached()
2503 // Calling stopAllLoaders() can cause the frame to be deallocated, including the frame loader.
2504 Ref<Frame> protectedFrame(m_frame);
2506 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2508 m_frame.document()->stopActiveDOMObjects();
2514 void FrameLoader::detachFromParent()
2516 // Calling stopAllLoaders() can cause the frame to be deallocated, including the frame loader.
2517 Ref<Frame> protect(m_frame);
2520 history().saveScrollPositionAndViewStateToItem(history().currentItem());
2522 if (m_frame.document()->pageCacheState() != Document::InPageCache) {
2523 // stopAllLoaders() needs to be called after detachChildren() if the document is not in the page cache,
2524 // because detachedChildren() will trigger the unload event handlers of any child frames, and those event
2525 // handlers might start a new subresource load in this frame.
2529 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2531 detachViewsAndDocumentLoader();
2533 m_progressTracker = nullptr;
2535 if (Frame* parent = m_frame.tree().parent()) {
2536 parent->loader().closeAndRemoveChild(m_frame);
2537 parent->loader().scheduleCheckCompleted();
2539 m_frame.setView(nullptr);
2540 m_frame.willDetachPage();
2541 m_frame.detachFromPage();
2545 void FrameLoader::detachViewsAndDocumentLoader()
2547 m_client.detachedFromParent2();
2548 setDocumentLoader(nullptr);
2549 m_client.detachedFromParent3();
2552 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2554 addExtraFieldsToRequest(request, m_loadType, false);
2557 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2559 // FIXME: Using m_loadType seems wrong for some callers.
2560 // If we are only preparing to load the main resource, that is previous load's load type!
2561 addExtraFieldsToRequest(request, m_loadType, true);
2563 // Upgrade-Insecure-Requests should only be added to main resource requests
2564 addHTTPUpgradeInsecureRequestsIfNeeded(request);
2567 ResourceRequestCachePolicy FrameLoader::defaultRequestCachingPolicy(const ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2569 if (m_overrideCachePolicyForTesting)
2570 return m_overrideCachePolicyForTesting.value();
2571 if (!isMainResource) {
2572 if (request.isConditional())
2573 return ReloadIgnoringCacheData;
2574 if (documentLoader()->isLoadingInAPISense()) {
2575 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2576 // original request cache policy for two reasons:
2577 // 1. For POST requests, we mutate the cache policy for the main resource,
2578 // but we do not want this to apply to subresources
2579 // 2. Delegates that modify the cache policy using willSendRequest: should
2580 // not affect any other resources. Such changes need to be done
2582 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2583 // 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.
2584 // This policy is set on initial request too, but should not be inherited.
2585 return (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2587 // FIXME: Other FrameLoader functions have duplicated code for setting cache policy of main request when reloading.
2588 // It seems better to manage it explicitly than to hide the logic inside addExtraFieldsToRequest().
2589 } else if (loadType == FrameLoadType::Reload || loadType == FrameLoadType::ReloadFromOrigin || request.isConditional())
2590 return ReloadIgnoringCacheData;
2592 return UseProtocolCachePolicy;
2595 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool isMainResource)
2597 // Don't set the cookie policy URL if it's already been set.
2598 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2599 if (request.firstPartyForCookies().isEmpty()) {
2600 if (isMainResource && m_frame.isMainFrame())
2601 request.setFirstPartyForCookies(request.url());
2602 else if (Document* document = m_frame.document())
2603 request.setFirstPartyForCookies(document->firstPartyForCookies());
2606 Page* page = frame().page();
2607 bool hasSpecificCachePolicy = request.cachePolicy() != UseProtocolCachePolicy;
2609 if (page && page->isResourceCachingDisabled()) {
2610 request.setCachePolicy(ReloadIgnoringCacheData);
2611 loadType = FrameLoadType::ReloadFromOrigin;
2612 } else if (!hasSpecificCachePolicy)
2613 request.setCachePolicy(defaultRequestCachingPolicy(request, loadType, isMainResource));
2615 // The remaining modifications are only necessary for HTTP and HTTPS.
2616 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2619 if (!hasSpecificCachePolicy && request.cachePolicy() == ReloadIgnoringCacheData) {
2620 if (loadType == FrameLoadType::Reload)
2621 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
2622 else if (loadType == FrameLoadType::ReloadFromOrigin) {
2623 request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
2624 request.setHTTPHeaderField(HTTPHeaderName::Pragma, "no-cache");
2628 if (m_overrideResourceLoadPriorityForTesting)
2629 request.setPriority(m_overrideResourceLoadPriorityForTesting.value());
2631 applyUserAgent(request);
2634 request.setHTTPAccept(defaultAcceptHeader);
2636 // Make sure we send the Origin header.
2637 addHTTPOriginIfNeeded(request, String());
2639 // Only set fallback array if it's still empty (later attempts may be incorrect, see bug 117818).
2640 if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
2641 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2642 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame.document()->encoding(), m_frame.settings().defaultTextEncodingName());
2646 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2648 if (!request.httpOrigin().isEmpty())
2649 return; // Request already has an Origin header.
2651 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2652 // For example, if an intranet page has a hyperlink to an external web
2653 // site, we don't want to include the Origin of the request because it
2654 // will leak the internal host name. Similar privacy concerns have lead
2655 // to the widespread suppression of the Referer header at the network
2657 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2660 // For non-GET and non-HEAD methods, always send an Origin header so the
2661 // server knows we support this feature.
2663 if (origin.isEmpty()) {
2664 // If we don't know what origin header to attach, we attach the value
2665 // for an empty origin.
2666 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2670 request.setHTTPOrigin(origin);
2673 void FrameLoader::addHTTPUpgradeInsecureRequestsIfNeeded(ResourceRequest& request)
2675 if (request.url().protocolIs("https")) {
2676 // FIXME: Identify HSTS cases and avoid adding the header. <https://bugs.webkit.org/show_bug.cgi?id=157885>
2680 request.setHTTPHeaderField(HTTPHeaderName::UpgradeInsecureRequests, ASCIILiteral("1"));
2683 void FrameLoader::loadPostRequest(const FrameLoadRequest& request, const String& referrer, FrameLoadType loadType, Event* event, FormState* formState)
2685 String frameName = request.frameName();
2686 LockHistory lockHistory = request.lockHistory();
2687 AllowNavigationToInvalidURL allowNavigationToInvalidURL = request.allowNavigationToInvalidURL();
2688 NewFrameOpenerPolicy openerPolicy = request.newFrameOpenerPolicy();
2690 const ResourceRequest& inRequest = request.resourceRequest();
2691 const URL& url = inRequest.url();
2692 const String& contentType = inRequest.httpContentType();
2693 String origin = inRequest.httpOrigin();
2695 ResourceRequest workingResourceRequest(url);
2697 if (!referrer.isEmpty())
2698 workingResourceRequest.setHTTPReferrer(referrer);
2699 workingResourceRequest.setHTTPOrigin(origin);
2700 workingResourceRequest.setHTTPMethod("POST");
2701 workingResourceRequest.setHTTPBody(inRequest.httpBody());
2702 workingResourceRequest.setHTTPContentType(contentType);
2703 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2705 if (Document* document = m_frame.document())
2706 document->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(workingResourceRequest, ContentSecurityPolicy::InsecureRequestType::Load);
2708 NavigationAction action(workingResourceRequest, loadType, true, event, request.shouldOpenExternalURLsPolicy(), request.downloadAttribute());
2710 if (!frameName.isEmpty()) {
2711 // The search for a target frame is done earlier in the case of form submission.
2712 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName)) {
2713 targetFrame->loader().loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL);
2717 policyChecker().checkNewWindowPolicy(action, workingResourceRequest, WTFMove(formState), frameName, [this, allowNavigationToInvalidURL, openerPolicy] (const ResourceRequest& request, FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
2718 continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
2723 // must grab this now, since this load may stop the previous load and clear this flag
2724 bool isRedirect = m_quickRedirectComing;
2725 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, WTFMove(formState), allowNavigationToInvalidURL);
2727 m_quickRedirectComing = false;
2728 if (m_provisionalDocumentLoader)
2729 m_provisionalDocumentLoader->setIsClientRedirect(true);
2733 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, RefPtr<SharedBuffer>& data)
2735 ASSERT(m_frame.document());
2736 String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), request.url(), outgoingReferrer());
2738 ResourceRequest initialRequest = request;
2739 initialRequest.setTimeoutInterval(10);
2741 if (!referrer.isEmpty())
2742 initialRequest.setHTTPReferrer(referrer);
2743 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2745 initialRequest.setFirstPartyForCookies(m_frame.mainFrame().loader().documentLoader()->request().url());
2747 addExtraFieldsToSubresourceRequest(initialRequest);
2749 unsigned long identifier = 0;
2750 ResourceRequest newRequest(initialRequest);
2751 requestFromDelegate(newRequest, identifier, error);
2753 #if ENABLE(CONTENT_EXTENSIONS)
2754 if (error.isNull()) {
2755 if (auto* page = m_frame.page()) {
2756 if (m_documentLoader) {
2757 auto blockedStatus = page->userContentProvider().processContentExtensionRulesForLoad(newRequest.url(), ResourceType::Raw, *m_documentLoader);
2758 applyBlockedStatusToRequest(blockedStatus, newRequest);
2759 if (blockedStatus.blockedLoad) {
2761 error = ResourceError(errorDomainWebKitInternal, 0, initialRequest.url(), emptyString());
2770 m_frame.document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(newRequest, ContentSecurityPolicy::InsecureRequestType::Load);
2772 if (error.isNull()) {
2773 ASSERT(!newRequest.isNull());
2775 if (!documentLoader()->applicationCacheHost().maybeLoadSynchronously(newRequest, error, response, data)) {
2776 Vector<char> buffer;
2777 platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, buffer);
2778 data = SharedBuffer::adoptVector(buffer);
2779 documentLoader()->applicationCacheHost().maybeLoadFallbackSynchronously(newRequest, error, response, data);
2780 ResourceLoadObserver::sharedObserver().logSubresourceLoading(&m_frame, newRequest, response);
2783 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data ? data->data() : nullptr, data ? data->size() : 0, -1, error);
2787 const ResourceRequest& FrameLoader::originalRequest() const
2789 return activeDocumentLoader()->originalRequestCopy();
2792 void FrameLoader::receivedMainResourceError(const ResourceError& error)
2794 // Retain because the stop may release the last reference to it.
2795 Ref<Frame> protect(m_frame);
2797 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2798 // FIXME: Don't want to do this if an entirely new load is going, so should check
2799 // that both data sources on the frame are either this or nil.
2801 if (m_client.shouldFallBack(error))
2802 handleFallbackContent();
2804 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2805 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2806 m_submittedFormURL = URL();
2808 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2809 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2810 // so that the existing view (that wenever got far enough to replace) can continue being used.
2811 history().invalidateCurrentItemCachedPage();
2813 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2814 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2815 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2816 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2818 if (m_sentRedirectNotification)
2819 clientRedirectCancelledOrFinished(false);
2824 checkLoadComplete();
2827 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2829 m_quickRedirectComing = false;
2831 if (!shouldContinue)
2834 // Calling stopLoading() on the provisional document loader can cause the underlying
2835 // frame to be deallocated.
2836 Ref<Frame> protectedFrame(m_frame);
2838 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2839 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2840 m_provisionalDocumentLoader->stopLoading();
2841 setProvisionalDocumentLoader(nullptr);
2844 bool isRedirect = m_quickRedirectComing || policyChecker().loadType() == FrameLoadType::RedirectWithLockedBackForwardList;
2845 loadInSameDocument(request.url(), 0, !isRedirect);
2848 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const URL& url)
2850 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2851 // currently displaying a frameset, or if the URL does not have a fragment.
2852 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2854 // FIXME: What about load types other than Standard and Reload?
2856 return (!isFormSubmission || equalLettersIgnoringASCIICase(httpMethod, "get"))
2857 && loadType != FrameLoadType::Reload
2858 && loadType != FrameLoadType::ReloadFromOrigin
2859 && loadType != FrameLoadType::Same
2860 && !shouldReload(m_frame.document()->url(), url)
2861 // We don't want to just scroll if a link from within a
2862 // frameset is trying to reload the frameset into _top.
2863 && !m_frame.document()->isFrameSet();
2866 void FrameLoader::scrollToFragmentWithParentBoundary(const URL& url)
2868 FrameView* view = m_frame.view();
2872 // Leaking scroll position to a cross-origin ancestor would permit the so-called "framesniffing" attack.
2873 RefPtr<Frame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame.document()->findUnsafeParentScrollPropagationBoundary() : 0);
2876 boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
2878 view->scrollToFragment(url);
2881 boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
2884 bool FrameLoader::shouldClose()
2886 Page* page = m_frame.page();
2889 if (!page->chrome().canRunBeforeUnloadConfirmPanel())
2892 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2893 Vector<Ref<Frame>, 16> targetFrames;
2894 targetFrames.append(m_frame);
2895 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().traverseNext(&m_frame))
2896 targetFrames.append(*child);
2898 bool shouldClose = false;
2900 NavigationDisablerForBeforeUnload navigationDisabler;
2903 for (i = 0; i < targetFrames.size(); i++) {
2904 if (!targetFrames[i]->tree().isDescendantOf(&m_frame))
2906 if (!targetFrames[i]->loader().dispatchBeforeUnloadEvent(page->chrome(), this))
2910 if (i == targetFrames.size())
2915 m_submittedFormURL = URL();
2917 m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
2921 void FrameLoader::dispatchUnloadEvents(UnloadEventPolicy unloadEventPolicy)
2923 if (!m_frame.document())
2926 // We store the frame's page in a local variable because the frame might get detached inside dispatchEvent.
2927 ForbidPromptsScope forbidPrompts(m_frame.page());
2928 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2930 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
2931 auto* currentFocusedElement = m_frame.document()->focusedElement();
2932 if (is<HTMLInputElement>(currentFocusedElement))
2933 downcast<HTMLInputElement>(*currentFocusedElement).endEditing();
2934 if (m_pageDismissalEventBeingDispatched == PageDismissalType::None) {
2935 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
2936 m_pageDismissalEventBeingDispatched = PageDismissalType::PageHide;
2937 m_frame.document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame.document()->pageCacheState() == Document::AboutToEnterPageCache), m_frame.document());
2940 // FIXME: update Page Visibility state here.
2941 // https://bugs.webkit.org/show_bug.cgi?id=116770
2943 if (m_frame.document()->pageCacheState() == Document::NotInPageCache) {
2944 Ref<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
2945 // The DocumentLoader (and thus its LoadTiming) might get destroyed
2946 // while dispatching the event, so protect it to prevent writing the end
2947 // time into freed memory.
2948 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
2949 m_pageDismissalEventBeingDispatched = PageDismissalType::Unload;
2950 if (documentLoader && documentLoader->timing().startTime() && !documentLoader->timing().unloadEventStart() && !documentLoader->timing().unloadEventEnd()) {
2951 auto& timing = documentLoader->timing();
2952 timing.markUnloadEventStart();
2953 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
2954 timing.markUnloadEventEnd();
2956 m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
2959 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
2960 m_wasUnloadEventEmitted = true;
2963 // Dispatching the unload event could have made m_frame.document() null.
2964 if (!m_frame.document())
2967 if (m_frame.document()->pageCacheState() != Document::NotInPageCache)
2970 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
2971 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
2972 && m_frame.document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
2974 if (!keepEventListeners)
2975 m_frame.document()->removeAllEventListeners();
2978 bool FrameLoader::dispatchBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
2980 DOMWindow* domWindow = m_frame.document()->domWindow();
2984 RefPtr<Document> document = m_frame.document();
2985 if (!document->bodyOrFrameset())
2988 Ref<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2989 m_pageDismissalEventBeingDispatched = PageDismissalType::BeforeUnload;
2992 ForbidPromptsScope forbidPrompts(m_frame.page());
2993 IgnoreOpensDuringUnloadCountIncrementer ignoreOpensDuringUnloadCountIncrementer(m_frame.document());
2994 domWindow->dispatchEvent(beforeUnloadEvent, domWindow->document());
2997 m_pageDismissalEventBeingDispatched = PageDismissalType::None;
2999 if (!beforeUnloadEvent->defaultPrevented())
3000 document->defaultEventHandler(beforeUnloadEvent.get());
3001 if (beforeUnloadEvent->returnValue().isNull())
3004 // If the navigating FrameLoader has already shown a beforeunload confirmation panel for the current navigation attempt,
3005 // this frame is not allowed to cause another one to be shown.
3006 if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
3007 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation."));
3011 // We should only display the beforeunload dialog for an iframe if its SecurityOrigin matches all
3012 // ancestor frame SecurityOrigins up through the navigating FrameLoader.
3013 if (frameLoaderBeingNavigated != this) {
3014 Frame* parentFrame = m_frame.tree().parent();
3015 while (parentFrame) {
3016 Document* parentDocument = parentFrame->document();
3017 if (!parentDocument)
3019 if (!m_frame.document() || !m_frame.document()->securityOrigin().canAccess(parentDocument->securityOrigin())) {
3020 document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show beforeunload confirmation dialog on behalf of a frame with different security origin. Protocols, domains, and ports must match."));
3024 if (&parentFrame->loader() == frameLoaderBeingNavigated)
3027 parentFrame = parentFrame->tree().parent();
3030 // The navigatingFrameLoader should always be in our ancestory.
3031 ASSERT(parentFrame);
3032 ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
3035 frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
3037 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
3038 return chrome.runBeforeUnloadConfirmPanel(text, m_frame);
3041 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest& request, FormState* formState, bool shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL)
3043 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
3044 // nil policyDataSource because loading the alternate page will have passed
3045 // through this method already, nested; otherwise, policyDataSource should still be set.
3046 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
3048 bool isTargetItem = history().provisionalItem() ? history().provisionalItem()->isTargetItem() : false;
3050 bool urlIsDisallowed = allowNavigationToInvalidURL == AllowNavigationToInvalidURL::No && !request.url().isValid();
3052 // Three reasons we can't continue:
3053 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
3054 // is the user responding Cancel to the form repost nag sheet.
3055 // 2) User responded Cancel to an alert popped up by the before unload event handler.
3056 // 3) The request's URL is invalid and navigation to invalid URLs is disallowed.
3057 bool canContinue = shouldContinue && shouldClose() && !urlIsDisallowed;
3060 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
3061 // need to report that the client redirect was cancelled.
3062 // FIXME: The client should be told about ignored non-quick redirects, too.
3063 if (m_quickRedirectComing)
3064 clientRedirectCancelledOrFinished(false);
3066 setPolicyDocumentLoader(nullptr);
3068 // If the navigation request came from the back/forward menu, and we punt on it, we have the
3069 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
3070 // we only do this when punting a navigation for the target frame or top-level frame.
3071 if ((isTargetItem || m_frame.isMainFrame()) && isBackForwardLoadType(policyChecker().loadType())) {
3072 if (Page* page = m_frame.page()) {
3073 if (HistoryItem* resetItem = m_frame.mainFrame().loader().history().currentItem()) {
3074 page->backForward().setCurrentItem(resetItem);
3075 m_frame.loader().client().updateGlobalHistoryItemForPage();
3082 FrameLoadType type = policyChecker().loadType();
3083 // A new navigation is in progress, so don't clear the history's provisional item.
3084 stopAllLoaders(ShouldNotClearProvisionalItem);
3086 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
3087 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
3088 if (!m_frame.page())
3091 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
3093 setState(FrameStateProvisional);
3095 setPolicyDocumentLoader(nullptr);
3097 if (isBackForwardLoadType(type)) {
3098 auto& diagnosticLoggingClient = m_frame.page()->diagnosticLoggingClient();
3099 if (history().provisionalItem()->isInPageCache()) {
3100 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultPass, ShouldSample::Yes);
3101 loadProvisionalItemFromCachedPage();
3104 diagnosticLoggingClient.logDiagnosticMessageWithResult(DiagnosticLoggingKeys::pageCacheKey(), DiagnosticLoggingKeys::retrievalKey(), DiagnosticLoggingResultFail, ShouldSample::Yes);
3108 continueLoadAfterWillSubmitForm();
3112 m_client.dispatchWillSubmitForm(*formState, [this] (PolicyAction action) {
3113 policyChecker().continueLoadAfterWillSubmitForm(action);
3117 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
3118 FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue, AllowNavigationToInvalidURL allowNavigationToInvalidURL, NewFrameOpenerPolicy openerPolicy)
3120 if (!shouldContinue)
3123 Ref<Frame> frame(m_frame);
3124 RefPtr<Frame> mainFrame = m_client.dispatchCreatePage(action);
3128 mainFrame->loader().forceSandboxFlags(frame->loader().effectiveSandboxFlags());
3130 if (frameName != "_blank")
3131 mainFrame->tree().setName(frameName);
3133 mainFrame->page()->setOpenedByDOM();
3134 mainFrame->loader().m_client.dispatchShow();
3135 if (openerPolicy == NewFrameOpenerPolicy::Allow) {
3136 mainFrame->loader().setOpener(frame.ptr());
3137 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
3140 NavigationAction newAction(request, action.shouldOpenExternalURLsPolicy());
3141 mainFrame->loader().loadWithNavigationAction(request, newAction, LockHistory::No, FrameLoadType::Standard, formState, allowNavigationToInvalidURL);
3144 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
3146 ASSERT(!request.isNull());
3149 if (Page* page = m_frame.page()) {
3150 identifier = page->progress().createUniqueIdentifier();
3151 notifier().assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
3154 ResourceRequest newRequest(request);
3155 notifier().dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
3157 if (newRequest.isNull())
3158 error = cancelledError(request);
3160 error = ResourceError();
3162 request = newRequest;
3165 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
3167 Page* page = m_frame.page();
3171 if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
3174 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
3175 if (resource->type() == CachedResource::MainResource)
3178 if (!page->areMemoryCacheClientCallsEnabled()) {
3179 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), resource);
3180 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
3181 m_documentLoader->didTellClientAboutLoad(resource->url());
3185 if (m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
3186 InspectorInstrumentation::didLoadResourceFromMemoryCache(*page, m_documentLoader.get(), resource);
3187 m_documentLoader->didTellClientAboutLoad(resource->url());
3191 unsigned long identifier;
3192 ResourceError error;
3193 requestFromDelegate(newRequest, identifier, error);
3194 InspectorInstrumentation::markResourceAsCached(*page, identifier);
3195 notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
3198 void FrameLoader::applyUserAgent(ResourceRequest& request)
3200 String userAgent = this->userAgent(request.url());
3201 ASSERT(!userAgent.isNull());
3202 request.setHTTPUserAgent(userAgent);
3205 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const URL& url, unsigned long requestIdentifier)
3207 Frame& topFrame = m_frame.tree().top();
3208 if (&m_frame == &topFrame)
3211 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
3213 switch (disposition) {
3214 case XFrameOptionsSameOrigin: {
3215 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
3216 if (!origin->isSameSchemeHostPort(topFrame.document()->securityOrigin()))
3218 for (Frame* frame = m_frame.tree().parent(); frame; frame = frame->tree().parent()) {
3219 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin()))
3224 case XFrameOptionsDeny:
3226 case XFrameOptionsAllowAll:
3228 case XFrameOptionsConflict:
3229 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);
3231 case XFrameOptionsInvalid:
3232 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);
3234 case XFrameOptionsNone:
3237 ASSERT_NOT_REACHED();
3241 void FrameLoader::loadProvisionalItemFromCachedPage()
3243 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
3244 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().stringCenterEllipsizedToLength().utf8().data());
3246 prepareForLoadStart();
3248 m_loadingFromCachedPage = true;
3250 // Should have timing data from previous time(s) the page was shown.
3251 ASSERT(provisionalLoader->timing().startTime());
3252 provisionalLoader->resetTiming();
3253 provisionalLoader->timing().markStartTime();
3255 provisionalLoader->setCommitted(true);
3256 commitProvisionalLoad();
3259 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const URL& url) const
3261 if (!history().currentItem())
3263 return url == history().currentItem()->url() || url == history().currentItem()->originalURL();
3266 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const URL& url) const
3268 if (!equalLettersIgnoringASCIICase(url.string(), "about:srcdoc"))
3270 HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement();
3273 if (!ownerElement->hasTagName(iframeTag))
3275 return ownerElement->hasAttributeWithoutSynchronization(srcdocAttr);
3278 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
3280 Frame* frame = m_frame.tree().find(name);
3282 // FIXME: Eventually all callers should supply the actual activeDocument so we can call canNavigate with the right document.
3283 if (!activeDocument)
3284 activeDocument = m_frame.document();
3286 if (!activeDocument->canNavigate(frame))
3292 void FrameLoader::loadSameDocumentItem(HistoryItem& item)
3294 ASSERT(item.documentSequenceNumber() == history().currentItem()->documentSequenceNumber());
3296 Ref<Frame> protect(m_frame);
3298 // Save user view state to the current history item here since we don't do a normal load.
3299 // FIXME: Does form state need to be saved here too?
3300 history().saveScrollPositionAndViewStateToItem(history().currentItem());
3301 if (FrameView* view = m_frame.view())
3302 view->setWasScrolledByUser(false);
3304 history().setCurrentItem(&item);
3306 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3307 loadInSameDocument(item.url(), item.stateObject(), false);
3309 // Restore user view state from the current history item here since we don't do a normal load.
3310 history().restoreScrollPositionAndViewState();
3313 // FIXME: This function should really be split into a couple pieces, some of
3314 // which should be methods of HistoryController and some of which should be
3315 // methods of FrameLoader.
3316 void FrameLoader::loadDifferentDocumentItem(HistoryItem& item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
3318 // Remember this item so we can traverse any child items as child frames load
3319 history().setProvisionalItem(&item);
3321 if (CachedPage* cachedPage = PageCache::singleton().get(item, m_frame.page())) {
3322 auto documentLoader = cachedPage->documentLoader();
3323 m_client.updateCachedDocumentLoader(*documentLoader);
3324 documentLoader->setTriggeringAction(NavigationAction(documentLoader->request(), loadType, false));
3325 documentLoader->setLastCheckedRequest(ResourceRequest());
3326 loadWithDocumentLoader(documentLoader, loadType, 0, AllowNavigationToInvalidURL::Yes);
3330 URL itemURL = item.url();
3331 URL itemOriginalURL = item.originalURL();
3333 if (documentLoader())
3334 currentURL = documentLoader()->url();
3335 RefPtr<FormData> formData = item.formData();
3337 ResourceRequest request(itemURL);
3339 if (!item.referrer().isNull())
3340 request.setHTTPReferrer(item.referrer());
3342 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = shouldOpenExternalURLsPolicyToApply(m_frame, item.shouldOpenExternalURLsPolicy());
3343 bool isFormSubmission = false;
3344 Event* event = nullptr;
3346 // If this was a repost that failed the page cache, we might try to repost the form.
3347 NavigationAction action;
3349 formData->generateFiles(m_frame.document());
3351 request.setHTTPMethod("POST");
3352 request.setHTTPBody(WTFMove(formData));
3353 request.setHTTPContentType(item.formContentType());
3354 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item.referrer());
3355 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3356 addHTTPUpgradeInsecureRequestsIfNeeded(request);
3358 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3359 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3360 addExtraFieldsToRequest(request, loadType, true);
3362 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3363 // We want to know this before talking to the policy delegate, since it affects whether
3364 // we show the DoYouReallyWantToRepost nag.
3366 // This trick has a small bug (3123893) where we might find a cache hit, but then
3367 // have the item vanish when we try to use it in the ensuing nav. This should be
3368 // extremely rare, but in that case the user will get an error on the navigation.
3370 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3371 request.setCachePolicy(ReturnCacheDataDontLoad);
3372 action = NavigationAction(request, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy);
3374 request.setCachePolicy(ReturnCacheDataElseLoad);
3375 action = NavigationAction(request, NavigationType::FormResubmitted, event, shouldOpenExternalURLsPolicy);
3379 case FrameLoadType::Reload:
3380 case FrameLoadType::ReloadFromOrigin:
3381 request.setCachePolicy(ReloadIgnoringCacheData);
3383 case FrameLoadType::Back:
3384 case FrameLoadType::Forward:
3385 case FrameLoadType::IndexedBackForward: {
3387 bool allowStaleData = true;
3389 bool allowStaleData = !item.wasRestoredFromSession();
3392 request.setCachePolicy(ReturnCacheDataElseLoad);
3393 item.setWasRestoredFromSession(false);
3396 case FrameLoadType::Standard:
3397 case FrameLoadType::RedirectWithLockedBackForwardList:
3399 case FrameLoadType::Same:
3401 ASSERT_NOT_REACHED();
3404 addExtraFieldsToRequest(request, loadType, true);
3406 ResourceRequest requestForOriginalURL(request);
3407 requestForOriginalURL.setURL(itemOriginalURL);
3408 action = NavigationAction(requestForOriginalURL, loadType, isFormSubmission, event, shouldOpenExternalURLsPolicy);
3411 loadWithNavigationAction(request, action, LockHistory::No, loadType, 0, AllowNavigationToInvalidURL::Yes);
3414 // Loads content into this frame, as specified by history item
3415 void FrameLoader::loadItem(HistoryItem& item, FrameLoadType loadType)
3417 m_requestedHistoryItem = &item;
3418 HistoryItem* currentItem = history().currentItem();
3419 bool sameDocumentNavigation = currentItem && item.shouldDoSameDocumentNavigationTo(*currentItem);
3421 if (sameDocumentNavigation)
3422 loadSameDocumentItem(item);
3424 loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
3427 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3429 ASSERT(m_state == FrameStateProvisional);
3430 ASSERT(!m_loadingFromCachedPage);
3431 ASSERT(history().provisionalItem());
3432 ASSERT(history().provisionalItem()->formData());
3433 ASSERT(history().provisionalItem() == m_requestedHistoryItem.get());
3435 FrameLoadType loadType = m_loadType;
3436 HistoryItem& item = *history().provisionalItem();
3438 stopAllLoaders(ShouldNotClearProvisionalItem);
3439 loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
3442 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3444 ResourceError error = m_client.cancelledError(request);
3445 error.setType(ResourceError::Type::Cancellation);
3449 ResourceError FrameLoader::blockedByContentBlockerError(const ResourceRequest& request) const
3451 return m_client.blockedByContentBlockerError(request);
3454 ResourceError FrameLoader::blockedError(const ResourceRequest& request) const
3456 ResourceError error = m_client.blockedError(request);
3457 error.setType(ResourceError::Type::Cancellation);
3461 #if ENABLE(CONTENT_FILTERING)
3462 ResourceError FrameLoader::blockedByContentFilterError(const ResourceRequest& request) const
3464 ResourceError error = m_client.blockedByContentFilterError(request);
3465 error.setType(ResourceError::Type::General);
3471 RetainPtr<CFDictionaryRef> FrameLoader::connectionProperties(ResourceLoader* loader)
3473 return m_client.connectionProperties(loader->documentLoader(), loader->identifier());
3477 String FrameLoader::referrer() const
3479 return m_documentLoader ? m_documentLoader->request().httpReferrer() : emptyString();
3482 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3484 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript))
3487 Vector<Ref<DOMWrapperWorld>> worlds;
3488 ScriptController::getAllWorlds(worlds);
3489 for (auto& world : worlds)
3490 dispatchDidClearWindowObjectInWorld(world);
3493 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
3495 if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame.script().existingWindowShell(world))
3498 m_client.dispatchDidClearWindowObjectInWorld(world);
3500 if (Page* page = m_frame.page())
3501 page->inspectorController().didClearWindowObjectInWorld(m_frame, world);
3503 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3506 void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
3508 Vector<Ref<DOMWrapperWorld>> worlds;
3509 ScriptController::getAllWorlds(worlds);
3510 for (auto& world : worlds)
3511 m_client.dispatchGlobalObjectAvailable(world);
3514 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3516 SandboxFlags flags = m_forcedSandboxFlags;
3517 if (Frame* parentFrame = m_frame.tree().parent())
3518 flags |= parentFrame->document()->sandboxFlags();
3519 if (HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement())
3520 flags |= ownerElement->sandboxFlags();
3524 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3526 m_client.didChangeTitle(loader);
3528 if (loader == m_documentLoader) {
3529 // Must update the entries in the back-forward list too.
3530 history().setCurrentItemTitle(loader->title());
3531 // This must go through the WebFrame because it has the right notion of the current b/f item.
3532 m_client.setTitle(loader->title(), loader->urlForHistory());
3533 m_client.setMainFrameDocumentReady(true); // update observers with new DOMDocument
3534 m_client.dispatchDidReceiveTitle(loader->title());
3537 #if ENABLE(REMOTE_INSPECTOR)
3538 if (m_frame.isMainFrame())
3539 m_frame.page()->remoteInspectorInformationDidChange();
3543 void FrameLoader::dispatchDidCommitLoad(std::optional<HasInsecureContent> initialHasInsecureContent)
3545 if (m_stateMachine.creatingInitialEmptyDocument())
3548 m_client.dispatchDidCommitLoad(initialHasInsecureContent);
3550 if (m_frame.isMainFrame()) {
3551 m_frame.page()->resetSeenPlugins();
3552 m_frame.page()->resetSeenMediaEngines();
3555 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3557 #if ENABLE(REMOTE_INSPECTOR)
3558 if (m_frame.isMainFrame())
3559 m_frame.page()->remoteInspectorInformationDidChange();
3563 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3565 ASSERT(m_frame.page());
3566 ASSERT(m_frame.page()->areMemoryCacheClientCallsEnabled());
3568 if (!m_documentLoader)
3571 Vector<ResourceRequest> pastLoads;
3572 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3574 for (auto& pastLoad : pastLoads) {
3575 CachedResource* resource = MemoryCache::singleton().resourceForRequest(pastLoad, m_frame.page()->sessionID());
3577 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3578 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3579 // Consider if there's some efficient way of remembering enough to deliver this client call.
3580 // We have the URL, but not the rest of the response or the length.
3584 ResourceRequest request(resource->url());
3585 m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3589 NetworkingContext* FrameLoader::networkingContext() const
3591 return m_networkingContext.get();
3594 void FrameLoader::loadProgressingStatusChanged()
3596 if (auto* view = m_frame.mainFrame().view())
3597 view->loadProgressingStatusChanged();
3600 void FrameLoader::forcePageTransitionIfNeeded()
3602 m_client.forcePageTransitionIfNeeded();
3605 void FrameLoader::clearTestingOverrides()
3607 m_overrideCachePolicyForTesting = std::nullopt;
3608 m_overrideResourceLoadPriorityForTesting = std::nullopt;
3609 m_isStrictRawResourceValidationPolicyDisabledForTesting = false;
3612 void FrameLoader::applyShouldOpenExternalURLsPolicyToNewDocumentLoader(DocumentLoader& documentLoader, ShouldOpenExternalURLsPolicy propagatedPolicy)
3614 documentLoader.setShouldOpenExternalURLsPolicy(shouldOpenExternalURLsPolicyToApply(m_frame, propagatedPolicy));
3617 bool FrameLoader::isAlwaysOnLoggingAllowed() const
3619 return frame().isAlwaysOnLoggingAllowed();
3622 bool FrameLoaderClient::hasHTMLView() const
3627 RefPtr<Frame> createWindow(Frame& openerFrame, Frame& lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3629 ASSERT(!features.dialog || request.frameName().isEmpty());
3633 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3634 if (RefPtr<Frame> frame = lookupFrame.loader().findFrameForNavigation(request.frameName(), openerFrame.document())) {
3635 if (request.frameName() != "_self") {
3636 if (Page* page = frame->page())
3637 page->chrome().focus();
3643 // Sandboxed frames cannot open new auxiliary browsing contexts.
3644 if (isDocumentSandboxed(openerFrame, SandboxPopups)) {
3645 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
3646 openerFrame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked opening '" + request.resourceRequest().url().stringCenterEllipsizedToLength() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
3650 // FIXME: Setting the referrer should be the caller's responsibility.
3651 FrameLoadRequest requestWithReferrer = request;
3652 String referrer = SecurityPolicy::generateReferrerHeader(openerFrame.document()->referrerPolicy(), request.resourceRequest().url(), openerFrame.loader().outgoingReferrer());
3653 if (!referrer.isEmpty())
3654 requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
3655 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame.loader().outgoingOrigin());
3656 FrameLoader::addHTTPUpgradeInsecureRequestsIfNeeded(requestWithReferrer.resourceRequest());
3658 Page* oldPage = openerFrame.page();
3662 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = shouldOpenExternalURLsPolicyToApply(openerFrame, request.shouldOpenExternalURLsPolicy());
3663 Page* page = oldPage->chrome().createWindow(openerFrame, requestWithReferrer, features, NavigationAction(requestWithReferrer.resourceRequest(), shouldOpenExternalURLsPolicy));
3667 RefPtr<Frame> frame = &page->mainFrame();
3669 frame->loader().forceSandboxFlags(openerFrame.document()->sandboxFlags());
3671 if (request.frameName() != "_blank")
3672 frame->tree().setName(request.frameName());
3674 page->chrome().setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3678 page->chrome().setStatusbarVisible(features.statusBarVisible);
3682 page->chrome().setScrollbarsVisible(features.scrollbarsVisible);
3686 page->chrome().setMenubarVisible(features.menuBarVisible);
3690 page->chrome().setResizable(features.resizable);
3692 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3693 // specify the size of the viewport. We can only resize the window, so adjust
3694 // for the difference between the window size and the viewport size.
3696 // FIXME: We should reconcile the initialization of viewport arguments between iOS and non-IOS.
3698 FloatSize viewportSize = page->chrome().pageRect().size();
3699 FloatRect windowRect = page->chrome().windowRect();
3701 windowRect.setX(*features.x);
3703 windowRect.setY(*features.y);
3704 // Zero width and height mean using default size, not minumum one.
3705 if (features.width && *features.width)
3706 windowRect.setWidth(*features.width + (windowRect.width() - viewportSize.width()));
3707 if (features.height && *features.height)
3708 windowRect.setHeight(*features.height + (windowRect.height() - viewportSize.height()));
3710 // Ensure non-NaN values, minimum size as well as being within valid screen area.
3711 FloatRect newWindowRect = DOMWindow::adjustWindowRect(*page, windowRect);
3715 page->chrome().setWindowRect(newWindowRect);
3717 // On iOS, width and height refer to the viewport dimensions.
3718 ViewportArguments arguments;
3719 // Zero width and height mean using default size, not minimum one.
3720 if (features.width && *features.width)
3721 arguments.width = *features.width;
3722 if (features.height && *features.height)
3723 arguments.height = *features.height;
3724 frame->setViewportArguments(arguments);
3729 page->chrome().show();
3735 bool FrameLoader::shouldSuppressKeyboardInput() const
3737 return m_frame.settings().shouldSuppressKeyboardInputDuringProvisionalNavigation() && m_state == FrameStateProvisional;
3740 } // namespace WebCore