2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
6 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
7 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
8 * Copyright (C) 2011 Google Inc. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
20 * its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
27 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "FrameLoader.h"
38 #include "AXObjectCache.h"
39 #include "ApplicationCacheHost.h"
40 #include "BackForwardController.h"
41 #include "BeforeUnloadEvent.h"
42 #include "CachedPage.h"
43 #include "CachedResourceLoader.h"
45 #include "ChromeClient.h"
47 #include "ContentSecurityPolicy.h"
48 #include "DOMImplementation.h"
49 #include "DOMWindow.h"
50 #include "DatabaseManager.h"
52 #include "DocumentLoadTiming.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"
64 #include "FrameLoadRequest.h"
65 #include "FrameLoaderClient.h"
66 #include "FrameNetworkingContext.h"
67 #include "FrameTree.h"
68 #include "FrameView.h"
69 #include "HTMLAnchorElement.h"
70 #include "HTMLFormElement.h"
71 #include "HTMLInputElement.h"
72 #include "HTMLNames.h"
73 #include "HTMLObjectElement.h"
74 #include "HTMLParserIdioms.h"
75 #include "HTTPParsers.h"
76 #include "HistoryController.h"
77 #include "HistoryItem.h"
78 #include "IconController.h"
79 #include "InspectorController.h"
80 #include "InspectorInstrumentation.h"
81 #include "LoaderStrategy.h"
83 #include "MIMETypeRegistry.h"
84 #include "MemoryCache.h"
86 #include "PageCache.h"
87 #include "PageTransitionEvent.h"
88 #include "PlatformStrategies.h"
89 #include "PluginData.h"
90 #include "PluginDatabase.h"
91 #include "PluginDocument.h"
92 #include "PolicyChecker.h"
93 #include "ProgressTracker.h"
94 #include "ResourceHandle.h"
95 #include "ResourceRequest.h"
96 #include "SchemeRegistry.h"
97 #include "ScriptCallStack.h"
98 #include "ScriptController.h"
99 #include "ScriptSourceCode.h"
100 #include "ScrollAnimator.h"
101 #include "SecurityOrigin.h"
102 #include "SecurityPolicy.h"
103 #include "SegmentedString.h"
104 #include "SerializedScriptValue.h"
105 #include "Settings.h"
106 #include "TextResourceDecoder.h"
107 #include "WindowFeatures.h"
108 #include "XMLDocumentParser.h"
109 #include <wtf/CurrentTime.h>
110 #include <wtf/StdLibExtras.h>
111 #include <wtf/text/CString.h>
112 #include <wtf/text/WTFString.h>
114 #if ENABLE(SHARED_WORKERS)
115 #include "SharedWorkerRepository.h"
119 #include "SVGDocument.h"
120 #include "SVGLocatable.h"
121 #include "SVGNames.h"
122 #include "SVGPreserveAspectRatio.h"
123 #include "SVGSVGElement.h"
124 #include "SVGViewElement.h"
125 #include "SVGViewSpec.h"
128 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
135 using namespace HTMLNames;
138 using namespace SVGNames;
141 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
142 static double storedTimeOfLastCompletedLoad;
144 bool isBackForwardLoadType(FrameLoadType type)
147 case FrameLoadTypeStandard:
148 case FrameLoadTypeReload:
149 case FrameLoadTypeReloadFromOrigin:
150 case FrameLoadTypeSame:
151 case FrameLoadTypeRedirectWithLockedBackForwardList:
152 case FrameLoadTypeReplace:
154 case FrameLoadTypeBack:
155 case FrameLoadTypeForward:
156 case FrameLoadTypeIndexedBackForward:
159 ASSERT_NOT_REACHED();
163 // This is not in the FrameLoader class to emphasize that it does not depend on
164 // private FrameLoader data, and to avoid increasing the number of public functions
165 // with access to private data. Since only this .cpp file needs it, making it
166 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
169 static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
171 return frame->document() && frame->document()->isSandboxed(mask);
174 class FrameLoader::FrameProgressTracker {
176 static PassOwnPtr<FrameProgressTracker> create(Frame* frame) { return adoptPtr(new FrameProgressTracker(frame)); }
177 ~FrameProgressTracker()
179 ASSERT(!m_inProgress || m_frame->page());
181 m_frame->page()->progress()->progressCompleted(m_frame);
184 void progressStarted()
186 ASSERT(m_frame->page());
188 m_frame->page()->progress()->progressStarted(m_frame);
192 void progressCompleted()
194 ASSERT(m_inProgress);
195 ASSERT(m_frame->page());
196 m_inProgress = false;
197 m_frame->page()->progress()->progressCompleted(m_frame);
201 FrameProgressTracker(Frame* frame)
203 , m_inProgress(false)
211 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
214 , m_policyChecker(adoptPtr(new PolicyChecker(frame)))
215 , m_history(adoptPtr(new HistoryController(frame)))
217 , m_subframeLoader(frame)
218 , m_icon(adoptPtr(new IconController(frame)))
219 , m_mixedContentChecker(frame)
220 , m_state(FrameStateProvisional)
221 , m_loadType(FrameLoadTypeStandard)
222 , m_delegateIsHandlingProvisionalLoadError(false)
223 , m_quickRedirectComing(false)
224 , m_sentRedirectNotification(false)
225 , m_inStopAllLoaders(false)
226 , m_isExecutingJavaScriptFormAction(false)
227 , m_didCallImplicitClose(true)
228 , m_wasUnloadEventEmitted(false)
229 , m_pageDismissalEventBeingDispatched(NoDismissal)
230 , m_isComplete(false)
231 , m_needsClear(false)
232 , m_checkTimer(this, &FrameLoader::checkTimerFired)
233 , m_shouldCallCheckCompleted(false)
234 , m_shouldCallCheckLoadComplete(false)
236 , m_didPerformFirstNavigation(false)
237 , m_loadingFromCachedPage(false)
238 , m_suppressOpenerInNewFrame(false)
239 , m_forcedSandboxFlags(SandboxNone)
243 FrameLoader::~FrameLoader()
247 HashSet<Frame*>::iterator end = m_openedFrames.end();
248 for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
249 (*it)->loader()->m_opener = 0;
251 m_client->frameLoaderDestroyed();
253 if (m_networkingContext)
254 m_networkingContext->invalidate();
257 void FrameLoader::init()
259 // This somewhat odd set of steps gives the frame an initial empty document.
260 setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData()).get());
261 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
262 m_provisionalDocumentLoader->startLoadingMainResource();
263 m_frame->document()->cancelParsing();
264 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
266 m_networkingContext = m_client->createNetworkingContext();
267 m_progressTracker = FrameProgressTracker::create(m_frame);
270 void FrameLoader::setDefersLoading(bool defers)
272 if (m_documentLoader)
273 m_documentLoader->setDefersLoading(defers);
274 if (m_provisionalDocumentLoader)
275 m_provisionalDocumentLoader->setDefersLoading(defers);
276 if (m_policyDocumentLoader)
277 m_policyDocumentLoader->setDefersLoading(defers);
278 history()->setDefersLoading(defers);
281 m_frame->navigationScheduler()->startTimer();
282 startCheckCompleteTimer();
286 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
288 urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
289 0, lockHistory, lockBackForwardList, MaybeSendReferrer, ReplaceDocumentIfJavaScriptURL);
292 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer)
294 urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
295 triggeringEvent, lockHistory, lockBackForwardList, shouldSendReferrer, DoNotReplaceDocumentIfJavaScriptURL);
298 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
299 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
300 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
302 ASSERT(!m_suppressOpenerInNewFrame);
304 RefPtr<Frame> protect(m_frame);
305 FrameLoadRequest frameRequest(passedRequest);
307 if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
310 if (frameRequest.frameName().isEmpty())
311 frameRequest.setFrameName(m_frame->document()->baseTarget());
313 if (shouldSendReferrer == NeverSendReferrer)
314 m_suppressOpenerInNewFrame = true;
315 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
317 loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, shouldSendReferrer);
319 m_suppressOpenerInNewFrame = false;
322 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
324 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
326 // FIXME: Find a good spot for these.
327 ASSERT(submission->data());
328 ASSERT(submission->state());
329 ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == m_frame);
331 if (!m_frame->page())
334 if (submission->action().isEmpty())
337 if (isDocumentSandboxed(m_frame, SandboxForms)) {
338 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
339 m_frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
343 if (protocolIsJavaScript(submission->action())) {
344 if (!m_frame->document()->contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
346 m_isExecutingJavaScriptFormAction = true;
347 m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
348 m_isExecutingJavaScriptFormAction = false;
352 Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
354 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
357 targetFrame = m_frame;
359 submission->clearTarget();
361 if (!targetFrame->page())
364 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
366 // We do not want to submit more than one form from the same page, nor do we want to submit a single
367 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
368 // The flag is reset in each time we start handle a new mouse or key down event, and
369 // also in setView since this part may get reused for a page from the back/forward cache.
370 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
372 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
373 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
374 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
376 if (m_frame->tree()->isDescendantOf(targetFrame)) {
377 if (m_submittedFormURL == submission->requestURL())
379 m_submittedFormURL = submission->requestURL();
382 submission->data()->generateFiles(m_frame->document());
383 submission->setReferrer(outgoingReferrer());
384 submission->setOrigin(outgoingOrigin());
386 targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
389 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
391 if (m_frame->document() && m_frame->document()->parser())
392 m_frame->document()->parser()->stopParsing();
394 if (unloadEventPolicy != UnloadEventPolicyNone) {
395 if (m_frame->document()) {
396 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
397 Node* currentFocusedNode = m_frame->document()->focusedNode();
398 if (currentFocusedNode && currentFocusedNode->toInputElement())
399 currentFocusedNode->toInputElement()->endEditing();
400 if (m_pageDismissalEventBeingDispatched == NoDismissal) {
401 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
402 m_pageDismissalEventBeingDispatched = PageHideDismissal;
403 m_frame->document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
405 if (!m_frame->document()->inPageCache()) {
406 RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
407 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
408 // while dispatching the event, so protect it to prevent writing the end
409 // time into freed memory.
410 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
411 m_pageDismissalEventBeingDispatched = UnloadDismissal;
412 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
413 DocumentLoadTiming* timing = documentLoader->timing();
414 ASSERT(timing->navigationStart());
415 timing->markUnloadEventStart();
416 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
417 timing->markUnloadEventEnd();
419 m_frame->document()->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
422 m_pageDismissalEventBeingDispatched = NoDismissal;
423 if (m_frame->document())
424 m_frame->document()->updateStyleIfNeeded();
425 m_wasUnloadEventEmitted = true;
429 // Dispatching the unload event could have made m_frame->document() null.
430 if (m_frame->document() && !m_frame->document()->inPageCache()) {
431 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
432 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
433 && m_frame->document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
435 if (!keepEventListeners)
436 m_frame->document()->removeAllEventListeners();
440 m_isComplete = true; // to avoid calling completed() in finishedParsing()
441 m_didCallImplicitClose = true; // don't want that one either
443 if (m_frame->document() && m_frame->document()->parsing()) {
445 m_frame->document()->setParsing(false);
448 if (Document* doc = m_frame->document()) {
449 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
450 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
451 doc->setReadyState(Document::Complete);
453 #if ENABLE(SQL_DATABASE)
454 // FIXME: Should the DatabaseManager watch for something like ActiveDOMObject::stop() rather than being special-cased here?
455 DatabaseManager::manager().stopDatabases(doc, 0);
459 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
460 m_frame->navigationScheduler()->cancel();
463 void FrameLoader::stop()
465 // http://bugs.webkit.org/show_bug.cgi?id=10854
466 // The frame's last ref may be removed and it will be deleted by checkCompleted().
467 RefPtr<Frame> protector(m_frame);
469 if (DocumentParser* parser = m_frame->document()->parser()) {
470 parser->stopParsing();
474 icon()->stopLoader();
477 bool FrameLoader::closeURL()
479 history()->saveDocumentState();
481 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
482 Document* currentDocument = m_frame->document();
483 stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
485 m_frame->editor()->clearUndoRedoOperations();
489 bool FrameLoader::didOpenURL()
491 if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
492 // A redirect was scheduled before the document was created.
493 // This can happen when one frame changes another frame's location.
497 m_frame->navigationScheduler()->cancel();
498 m_frame->editor()->clearLastEditCommand();
500 m_isComplete = false;
501 m_didCallImplicitClose = false;
503 // If we are still in the process of initializing an empty document then
504 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
505 // since it may cause clients to attempt to render the frame.
506 if (!m_stateMachine.creatingInitialEmptyDocument()) {
507 DOMWindow* window = m_frame->document()->domWindow();
508 window->setStatus(String());
509 window->setDefaultStatus(String());
517 void FrameLoader::didExplicitOpen()
519 m_isComplete = false;
520 m_didCallImplicitClose = false;
522 // Calling document.open counts as committing the first real document load.
523 if (!m_stateMachine.committedFirstRealDocumentLoad())
524 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
526 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
527 // from a subsequent window.document.open / window.document.write call.
528 // Canceling redirection here works for all cases because document.open
529 // implicitly precedes document.write.
530 m_frame->navigationScheduler()->cancel();
534 void FrameLoader::cancelAndClear()
536 m_frame->navigationScheduler()->cancel();
541 clear(m_frame->document(), false);
542 m_frame->script()->updatePlatformScriptObjects();
545 void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
547 m_frame->editor()->clear();
551 m_needsClear = false;
553 if (!m_frame->document()->inPageCache()) {
554 m_frame->document()->cancelParsing();
555 m_frame->document()->stopActiveDOMObjects();
556 if (m_frame->document()->attached()) {
557 m_frame->document()->prepareForDestruction();
558 m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
562 // Do this after detaching the document so that the unload event works.
563 if (clearWindowProperties) {
564 InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->document()->domWindow());
565 m_frame->document()->domWindow()->resetUnlessSuspendedForPageCache();
566 m_frame->script()->clearWindowShell(newDocument->domWindow(), m_frame->document()->inPageCache());
569 m_frame->selection()->prepareForDestruction();
570 m_frame->eventHandler()->clear();
571 if (clearFrameView && m_frame->view())
572 m_frame->view()->clear();
574 // Do not drop the document before the ScriptController and view are cleared
575 // as some destructors might still try to access the document.
576 m_frame->setDocument(0);
578 m_subframeLoader.clear();
580 if (clearScriptObjects)
581 m_frame->script()->clearScriptObjects();
583 m_frame->script()->enableEval();
585 m_frame->navigationScheduler()->clear();
588 m_shouldCallCheckCompleted = false;
589 m_shouldCallCheckLoadComplete = false;
591 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
592 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
595 void FrameLoader::receivedFirstData()
597 dispatchDidCommitLoad();
598 dispatchDidClearWindowObjectsInAllWorlds();
599 dispatchGlobalObjectAvailableInAllWorlds();
601 if (m_documentLoader) {
602 StringWithDirection ptitle = m_documentLoader->title();
603 // If we have a title let the WebView know about it.
604 if (!ptitle.isNull())
605 m_client->dispatchDidReceiveTitle(ptitle);
608 if (!m_documentLoader)
610 if (m_frame->document()->isViewSource())
615 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
618 url = m_frame->document()->url().string();
620 url = m_frame->document()->completeURL(url).string();
622 m_frame->navigationScheduler()->scheduleRedirect(delay, url);
625 void FrameLoader::setOutgoingReferrer(const KURL& url)
627 m_outgoingReferrer = url.strippedForUseAsReferrer();
630 void FrameLoader::didBeginDocument(bool dispatch)
633 m_isComplete = false;
634 m_didCallImplicitClose = false;
635 m_frame->document()->setReadyState(Document::Loading);
637 if (m_pendingStateObject) {
638 m_frame->document()->statePopped(m_pendingStateObject.get());
639 m_pendingStateObject.clear();
643 dispatchDidClearWindowObjectsInAllWorlds();
645 updateFirstPartyForCookies();
646 m_frame->document()->initContentSecurityPolicy();
648 Settings* settings = m_frame->document()->settings();
650 m_frame->document()->cachedResourceLoader()->setImagesEnabled(settings->areImagesEnabled());
651 m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings->loadsImagesAutomatically());
654 if (m_documentLoader) {
655 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
656 if (!dnsPrefetchControl.isEmpty())
657 m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
659 String policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy");
660 if (!policyValue.isEmpty())
661 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Enforce);
663 policyValue = m_documentLoader->response().httpHeaderField("Content-Security-Policy-Report-Only");
664 if (!policyValue.isEmpty())
665 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Report);
667 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
668 if (!policyValue.isEmpty())
669 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedEnforce);
671 policyValue = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
672 if (!policyValue.isEmpty())
673 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedReport);
675 String headerContentLanguage = m_documentLoader->response().httpHeaderField("Content-Language");
676 if (!headerContentLanguage.isEmpty()) {
677 size_t commaIndex = headerContentLanguage.find(',');
678 headerContentLanguage.truncate(commaIndex); // notFound == -1 == don't truncate
679 headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
680 if (!headerContentLanguage.isEmpty())
681 m_frame->document()->setContentLanguage(headerContentLanguage);
685 history()->restoreDocumentState();
688 void FrameLoader::finishedParsing()
690 m_frame->injectUserScripts(InjectAtDocumentEnd);
692 if (m_stateMachine.creatingInitialEmptyDocument())
695 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
696 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
697 // Null-checking the FrameView indicates whether or not we're in the destructor.
698 RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
700 m_client->dispatchDidFinishDocumentLoad();
704 if (!m_frame->view())
705 return; // We are being destroyed by something checkCompleted called.
707 // Check if the scrollbars are really needed for the content.
708 // If not, remove them, relayout, and repaint.
709 m_frame->view()->restoreScrollbar();
710 scrollToFragmentWithParentBoundary(m_frame->document()->url());
713 void FrameLoader::loadDone()
718 bool FrameLoader::allChildrenAreComplete() const
720 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
721 if (!child->loader()->m_isComplete)
727 bool FrameLoader::allAncestorsAreComplete() const
729 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
730 if (!ancestor->loader()->m_isComplete)
736 void FrameLoader::checkCompleted()
738 RefPtr<Frame> protect(m_frame);
739 m_shouldCallCheckCompleted = false;
742 m_frame->view()->handleLoadCompleted();
744 // Have we completed before?
748 // Are we still parsing?
749 if (m_frame->document()->parsing())
752 // Still waiting for images/scripts?
753 if (m_frame->document()->cachedResourceLoader()->requestCount())
756 // Still waiting for elements that don't go through a FrameLoader?
757 if (m_frame->document()->isDelayingLoadEvent())
760 // Any frame that hasn't completed yet?
761 if (!allChildrenAreComplete())
766 m_requestedHistoryItem = 0;
767 m_frame->document()->setReadyState(Document::Complete);
769 checkCallImplicitClose(); // if we didn't do it before
771 m_frame->navigationScheduler()->startTimer();
778 m_frame->view()->handleLoadCompleted();
781 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
783 RefPtr<Frame> protect(m_frame);
785 if (Page* page = m_frame->page()) {
786 if (page->defersLoading())
789 if (m_shouldCallCheckCompleted)
791 if (m_shouldCallCheckLoadComplete)
795 void FrameLoader::startCheckCompleteTimer()
797 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
799 if (m_checkTimer.isActive())
801 m_checkTimer.startOneShot(0);
804 void FrameLoader::scheduleCheckCompleted()
806 m_shouldCallCheckCompleted = true;
807 startCheckCompleteTimer();
810 void FrameLoader::scheduleCheckLoadComplete()
812 m_shouldCallCheckLoadComplete = true;
813 startCheckCompleteTimer();
816 void FrameLoader::checkCallImplicitClose()
818 if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
821 if (!allChildrenAreComplete())
822 return; // still got a frame running -> too early
824 m_didCallImplicitClose = true;
825 m_wasUnloadEventEmitted = false;
826 m_frame->document()->implicitClose();
829 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
833 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
834 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);
835 if (subframeArchive) {
836 childFrame->loader()->loadArchive(subframeArchive.release());
839 #endif // ENABLE(WEB_ARCHIVE)
841 HistoryItem* parentItem = history()->currentItem();
842 // If we're moving in the back/forward list, we might want to replace the content
843 // of this child frame with whatever was there at that point.
844 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
845 && !m_frame->document()->loadEventFinished()) {
846 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
848 childFrame->loader()->loadDifferentDocumentItem(childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
853 childFrame->loader()->loadURL(url, referer, "_self", false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
856 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
857 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
859 ArchiveResource* mainResource = archive->mainResource();
860 ASSERT(mainResource);
864 SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
866 ResourceRequest request(mainResource->url());
868 request.applyWebArchiveHackForMail();
871 RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
872 documentLoader->setArchive(archive.get());
873 load(documentLoader.get());
875 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
877 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
879 String mimeType = mimeTypeIn;
881 if (mimeType.isEmpty())
882 mimeType = mimeTypeFromURL(url);
884 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
885 if (mimeType.isEmpty()) {
886 String decodedPath = decodeURLEscapeSequences(url.path());
887 mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(decodedPath.substring(decodedPath.reverseFind('.') + 1));
891 if (mimeType.isEmpty())
892 return ObjectContentFrame; // Go ahead and hope that we can display the content.
894 #if !PLATFORM(MAC) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
895 bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
897 bool plugInSupportsMIMEType = false;
900 if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
901 return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
903 if (plugInSupportsMIMEType)
904 return WebCore::ObjectContentNetscapePlugin;
906 if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
907 return WebCore::ObjectContentFrame;
909 return WebCore::ObjectContentNone;
912 String FrameLoader::outgoingReferrer() const
914 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
915 // for why we walk the parent chain for srcdoc documents.
916 Frame* frame = m_frame;
917 while (frame->document()->isSrcdocDocument()) {
918 frame = frame->tree()->parent();
919 // Srcdoc documents cannot be top-level documents, by definition,
920 // because they need to be contained in iframes with the srcdoc.
923 return frame->loader()->m_outgoingReferrer;
926 String FrameLoader::outgoingOrigin() const
928 return m_frame->document()->securityOrigin()->toString();
931 bool FrameLoader::checkIfFormActionAllowedByCSP(const KURL& url) const
933 if (m_submittedFormURL.isEmpty())
936 return m_frame->document()->contentSecurityPolicy()->allowFormAction(url);
939 Frame* FrameLoader::opener()
944 void FrameLoader::setOpener(Frame* opener)
946 if (m_opener && !opener)
947 m_client->didDisownOpener();
950 m_opener->loader()->m_openedFrames.remove(m_frame);
952 opener->loader()->m_openedFrames.add(m_frame);
955 if (m_frame->document())
956 m_frame->document()->initSecurityContext();
959 // FIXME: This does not belong in FrameLoader!
960 void FrameLoader::handleFallbackContent()
962 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
963 if (!owner || !owner->hasTagName(objectTag))
965 static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
968 void FrameLoader::provisionalLoadStarted()
970 if (m_stateMachine.firstLayoutDone())
971 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
972 m_frame->navigationScheduler()->cancel(true);
973 m_client->provisionalLoadStarted();
976 void FrameLoader::resetMultipleFormSubmissionProtection()
978 m_submittedFormURL = KURL();
981 void FrameLoader::updateFirstPartyForCookies()
983 if (m_frame->tree()->parent())
984 setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
986 setFirstPartyForCookies(m_frame->document()->url());
989 void FrameLoader::setFirstPartyForCookies(const KURL& url)
991 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
992 frame->document()->setFirstPartyForCookies(url);
995 // This does the same kind of work that didOpenURL does, except it relies on the fact
996 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
997 void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
999 // If we have a state object, we cannot also be a new navigation.
1000 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1002 // Update the data source's request with the new URL to fake the URL change
1003 KURL oldURL = m_frame->document()->url();
1004 m_frame->document()->setURL(url);
1005 setOutgoingReferrer(url);
1006 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1007 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1008 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1009 // based on the current request. Must also happen before we openURL and displace the
1010 // scroll position, since adding the BF item will save away scroll state.
1012 // NB2: If we were loading a long, slow doc, and the user fragment navigated before
1013 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1014 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1015 // though its load is not yet done. I think this all works out OK, for one because
1016 // we have already saved away the scroll and doc state for the long slow load,
1017 // but it's not an obvious case.
1019 history()->updateBackForwardListForFragmentScroll();
1022 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1024 history()->updateForSameDocumentNavigation();
1026 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1028 m_frame->eventHandler()->stopAutoscrollTimer();
1030 // It's important to model this as a load that starts and immediately finishes.
1031 // Otherwise, the parent frame may think we never finished loading.
1034 // We need to scroll to the fragment whether or not a hash change occurred, since
1035 // the user might have scrolled since the previous navigation.
1036 scrollToFragmentWithParentBoundary(url);
1038 m_isComplete = false;
1041 if (isNewNavigation) {
1042 // This will clear previousItem from the rest of the frame tree that didn't
1043 // doing any loading. We need to make a pass on this now, since for fragment
1044 // navigation we'll not go through a real load and reach Completed state.
1045 checkLoadComplete();
1048 m_client->dispatchDidNavigateWithinPage();
1050 m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1051 m_client->dispatchDidPopStateWithinPage();
1054 m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1055 m_client->dispatchDidChangeLocationWithinPage();
1058 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1059 m_client->didFinishLoad();
1062 bool FrameLoader::isComplete() const
1064 return m_isComplete;
1067 void FrameLoader::completed()
1069 RefPtr<Frame> protect(m_frame);
1071 for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1072 descendant->navigationScheduler()->startTimer();
1074 if (Frame* parent = m_frame->tree()->parent())
1075 parent->loader()->checkCompleted();
1077 if (m_frame->view())
1078 m_frame->view()->maintainScrollPositionAtAnchor(0);
1081 void FrameLoader::started()
1083 for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1084 frame->loader()->m_isComplete = false;
1087 void FrameLoader::prepareForHistoryNavigation()
1089 // If there is no currentItem, but we still want to engage in
1090 // history navigation we need to manufacture one, and update
1091 // the state machine of this frame to impersonate having
1093 RefPtr<HistoryItem> currentItem = history()->currentItem();
1095 currentItem = HistoryItem::create();
1096 currentItem->setLastVisitWasFailure(true);
1097 history()->setCurrentItem(currentItem.get());
1098 frame()->page()->backForward()->setCurrentItem(currentItem.get());
1100 ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1101 stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1102 stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1106 void FrameLoader::prepareForLoadStart()
1108 m_progressTracker->progressStarted();
1109 m_client->dispatchDidStartProvisionalLoad();
1111 // Notify accessibility.
1112 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
1113 AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadTypeReload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
1114 cache->frameLoadingEventNotification(m_frame, loadingEvent);
1118 void FrameLoader::setupForReplace()
1120 m_client->revertToProvisionalState(m_documentLoader.get());
1121 setState(FrameStateProvisional);
1122 m_provisionalDocumentLoader = m_documentLoader;
1123 m_documentLoader = 0;
1127 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1128 PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
1130 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1131 RefPtr<Frame> protect(m_frame);
1133 KURL url = request.resourceRequest().url();
1135 ASSERT(m_frame->document());
1136 if (!request.requester()->canDisplay(url)) {
1137 reportLocalLoadFailed(m_frame, url.elidedString());
1141 String argsReferrer = request.resourceRequest().httpReferrer();
1142 if (argsReferrer.isEmpty())
1143 argsReferrer = outgoingReferrer();
1145 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), url, argsReferrer);
1146 if (shouldSendReferrer == NeverSendReferrer)
1147 referrer = String();
1149 FrameLoadType loadType;
1150 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1151 loadType = FrameLoadTypeReload;
1152 else if (lockBackForwardList)
1153 loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1155 loadType = FrameLoadTypeStandard;
1157 if (request.resourceRequest().httpMethod() == "POST")
1158 loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1160 loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1162 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1163 // load if frame names have changed.
1164 Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : m_frame;
1166 sourceFrame = m_frame;
1167 Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName());
1168 if (targetFrame && targetFrame != sourceFrame) {
1169 if (Page* page = targetFrame->page())
1170 page->chrome()->focus();
1174 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1175 PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1177 if (m_inStopAllLoaders)
1180 RefPtr<FormState> formState = prpFormState;
1181 bool isFormSubmission = formState;
1183 ResourceRequest request(newURL);
1184 if (!referrer.isEmpty()) {
1185 request.setHTTPReferrer(referrer);
1186 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1187 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1189 #if ENABLE(CACHE_PARTITIONING)
1190 if (m_frame->tree()->top() != m_frame)
1191 request.setCachePartition(m_frame->tree()->top()->document()->securityOrigin()->cachePartition());
1193 addExtraFieldsToRequest(request, newLoadType, true);
1194 if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1195 request.setCachePolicy(ReloadIgnoringCacheData);
1197 ASSERT(newLoadType != FrameLoadTypeSame);
1199 // The search for a target frame is done earlier in the case of form submission.
1200 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1201 if (targetFrame && targetFrame != m_frame) {
1202 targetFrame->loader()->loadURL(newURL, referrer, "_self", lockHistory, newLoadType, event, formState.release());
1206 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1209 NavigationAction action(request, newLoadType, isFormSubmission, event);
1211 if (!targetFrame && !frameName.isEmpty()) {
1212 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1213 request, formState.release(), frameName, this);
1217 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1219 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1220 const String& httpMethod = request.httpMethod();
1222 // Make sure to do scroll to fragment processing even if the URL is
1223 // exactly the same so pages with '#' links and DHTML side effects
1225 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
1226 oldDocumentLoader->setTriggeringAction(action);
1227 policyChecker()->stopCheck();
1228 policyChecker()->setLoadType(newLoadType);
1229 policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1230 callContinueFragmentScrollAfterNavigationPolicy, this);
1232 // must grab this now, since this load may stop the previous load and clear this flag
1233 bool isRedirect = m_quickRedirectComing;
1234 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1236 m_quickRedirectComing = false;
1237 if (m_provisionalDocumentLoader)
1238 m_provisionalDocumentLoader->setIsClientRedirect(true);
1239 } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1240 // Example of this case are sites that reload the same URL with a different cookie
1241 // driving the generated content, or a master frame with links that drive a target
1242 // frame, where the user has clicked on the same link repeatedly.
1243 m_loadType = FrameLoadTypeSame;
1247 SubstituteData FrameLoader::defaultSubstituteDataForURL(const KURL& url)
1249 if (!shouldTreatURLAsSrcdocDocument(url))
1250 return SubstituteData();
1251 String srcdoc = m_frame->ownerElement()->fastGetAttribute(srcdocAttr);
1252 ASSERT(!srcdoc.isNull());
1253 CString encodedSrcdoc = srcdoc.utf8();
1254 return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL());
1257 void FrameLoader::load(const FrameLoadRequest& passedRequest)
1259 FrameLoadRequest request(passedRequest);
1261 if (m_inStopAllLoaders)
1264 if (!request.frameName().isEmpty()) {
1265 Frame* frame = findFrameForNavigation(request.frameName());
1267 request.setShouldCheckNewWindowPolicy(false);
1268 if (frame->loader() != this) {
1269 frame->loader()->load(request);
1275 if (request.shouldCheckNewWindowPolicy()) {
1276 policyChecker()->checkNewWindowPolicy(NavigationAction(request.resourceRequest(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request.resourceRequest(), 0, request.frameName(), this);
1280 if (!request.hasSubstituteData())
1281 request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
1283 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request.resourceRequest(), request.substituteData());
1284 if (request.lockHistory() && m_documentLoader)
1285 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1289 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1291 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1292 if (lockHistory && m_documentLoader)
1293 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1295 loader->setTriggeringAction(action);
1296 if (m_documentLoader)
1297 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1299 loadWithDocumentLoader(loader.get(), type, formState);
1302 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1304 ResourceRequest& r = newDocumentLoader->request();
1305 addExtraFieldsToMainResourceRequest(r);
1308 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1309 r.setCachePolicy(ReloadIgnoringCacheData);
1310 type = FrameLoadTypeSame;
1311 } else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadTypeReload)
1312 type = FrameLoadTypeReload;
1314 type = FrameLoadTypeStandard;
1316 if (m_documentLoader)
1317 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1319 // When we loading alternate content for an unreachable URL that we're
1320 // visiting in the history list, we treat it as a reload so the history list
1321 // is appropriately maintained.
1323 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1324 // shouldn't a more explicit type of reload be defined, that means roughly
1325 // "load without affecting history" ?
1326 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1327 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1328 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1329 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1330 history()->saveDocumentAndScrollState();
1332 ASSERT(type == FrameLoadTypeStandard);
1333 type = FrameLoadTypeReload;
1336 loadWithDocumentLoader(newDocumentLoader, type, 0);
1339 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1341 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1342 RefPtr<Frame> protect(m_frame);
1344 ASSERT(m_client->hasWebView());
1346 // Unfortunately the view must be non-nil, this is ultimately due
1347 // to parser requiring a FrameView. We should fix this dependency.
1349 ASSERT(m_frame->view());
1351 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1354 if (m_frame->document())
1355 m_previousURL = m_frame->document()->url();
1357 policyChecker()->setLoadType(type);
1358 RefPtr<FormState> formState = prpFormState;
1359 bool isFormSubmission = formState;
1361 const KURL& newURL = loader->request().url();
1362 const String& httpMethod = loader->request().httpMethod();
1364 if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker()->loadType(), newURL)) {
1365 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1366 NavigationAction action(loader->request(), policyChecker()->loadType(), isFormSubmission);
1368 oldDocumentLoader->setTriggeringAction(action);
1369 policyChecker()->stopCheck();
1370 policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1371 callContinueFragmentScrollAfterNavigationPolicy, this);
1373 if (Frame* parent = m_frame->tree()->parent())
1374 loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
1376 policyChecker()->stopCheck();
1377 setPolicyDocumentLoader(loader);
1378 if (loader->triggeringAction().isEmpty())
1379 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker()->loadType(), isFormSubmission));
1381 if (Element* ownerElement = m_frame->ownerElement()) {
1382 // We skip dispatching the beforeload event if we've already
1383 // committed a real document load because the event would leak
1384 // subsequent activity by the frame which the parent frame isn't
1385 // supposed to learn. For example, if the child frame navigated to
1386 // a new URL, the parent frame shouldn't learn the URL.
1387 if (!m_stateMachine.committedFirstRealDocumentLoad()
1388 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1389 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1394 policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1395 callContinueLoadAfterNavigationPolicy, this);
1399 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1401 ASSERT(!url.isEmpty());
1405 frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
1408 const ResourceRequest& FrameLoader::initialRequest() const
1410 return activeDocumentLoader()->originalRequest();
1413 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1415 ResourceRequest request(url);
1417 unsigned long identifier;
1418 ResourceError error;
1419 requestFromDelegate(request, identifier, error);
1420 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1422 url = request.url();
1424 return error.isNull();
1427 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1429 KURL unreachableURL = docLoader->unreachableURL();
1431 if (unreachableURL.isEmpty())
1434 if (!isBackForwardLoadType(policyChecker()->loadType()))
1437 // We only treat unreachableURLs specially during the delegate callbacks
1438 // for provisional load errors and navigation policy decisions. The former
1439 // case handles well-formed URLs that can't be loaded, and the latter
1440 // case handles malformed URLs and unknown schemes. Loading alternate content
1441 // at other times behaves like a standard load.
1442 DocumentLoader* compareDocumentLoader = 0;
1443 if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1444 compareDocumentLoader = m_policyDocumentLoader.get();
1445 else if (m_delegateIsHandlingProvisionalLoadError)
1446 compareDocumentLoader = m_provisionalDocumentLoader.get();
1448 return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1451 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1453 if (!m_documentLoader)
1456 ResourceRequest request = m_documentLoader->request();
1457 KURL unreachableURL = m_documentLoader->unreachableURL();
1458 if (!unreachableURL.isEmpty())
1459 request.setURL(unreachableURL);
1461 // FIXME: If the resource is a result of form submission and is not cached, the form will be silently resubmitted.
1462 // We should ask the user for confirmation in this case.
1463 request.setCachePolicy(ReturnCacheDataElseLoad);
1465 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
1466 setPolicyDocumentLoader(loader.get());
1468 loader->setOverrideEncoding(encoding);
1470 loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1473 void FrameLoader::reloadWithOverrideURL(const KURL& overrideUrl, bool endToEndReload)
1475 if (!m_documentLoader)
1478 if (overrideUrl.isEmpty())
1481 ResourceRequest request = m_documentLoader->request();
1482 request.setURL(overrideUrl);
1483 reloadWithRequest(request, endToEndReload);
1486 void FrameLoader::reload(bool endToEndReload)
1488 if (!m_documentLoader)
1491 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1492 // Reloading in this case will lose the current contents (see 4151001).
1493 if (m_documentLoader->request().url().isEmpty())
1496 // Replace error-page URL with the URL we were trying to reach.
1497 ResourceRequest initialRequest = m_documentLoader->request();
1498 KURL unreachableURL = m_documentLoader->unreachableURL();
1499 if (!unreachableURL.isEmpty())
1500 initialRequest.setURL(unreachableURL);
1502 reloadWithRequest(initialRequest, endToEndReload);
1505 void FrameLoader::reloadWithRequest(const ResourceRequest& initialRequest, bool endToEndReload)
1507 ASSERT(m_documentLoader);
1509 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1510 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1511 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
1513 ResourceRequest& request = loader->request();
1515 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1516 request.setCachePolicy(ReloadIgnoringCacheData);
1518 // If we're about to re-post, set up action so the application can warn the user.
1519 if (request.httpMethod() == "POST")
1520 loader->setTriggeringAction(NavigationAction(request, NavigationTypeFormResubmitted));
1522 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1524 loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1527 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1529 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1530 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1533 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1534 if (m_inStopAllLoaders)
1537 // Calling stopLoading() on the provisional document loader can blow away
1538 // the frame from underneath.
1539 RefPtr<Frame> protect(m_frame);
1541 m_inStopAllLoaders = true;
1543 policyChecker()->stopCheck();
1545 // If no new load is in progress, we should clear the provisional item from history
1546 // before we call stopLoading.
1547 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1548 history()->setProvisionalItem(0);
1550 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1551 child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
1552 if (m_provisionalDocumentLoader)
1553 m_provisionalDocumentLoader->stopLoading();
1554 if (m_documentLoader)
1555 m_documentLoader->stopLoading();
1557 setProvisionalDocumentLoader(0);
1559 m_checkTimer.stop();
1561 m_inStopAllLoaders = false;
1564 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1568 if (deferCheckLoadComplete)
1569 scheduleCheckLoadComplete();
1570 else if (m_frame->page())
1571 checkLoadComplete();
1574 DocumentLoader* FrameLoader::activeDocumentLoader() const
1576 if (m_state == FrameStateProvisional)
1577 return m_provisionalDocumentLoader.get();
1578 return m_documentLoader.get();
1581 bool FrameLoader::isLoading() const
1583 DocumentLoader* docLoader = activeDocumentLoader();
1586 return docLoader->isLoading();
1589 bool FrameLoader::frameHasLoaded() const
1591 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1594 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1596 if (!loader && !m_documentLoader)
1599 ASSERT(loader != m_documentLoader);
1600 ASSERT(!loader || loader->frameLoader() == this);
1602 m_client->prepareForDataSourceReplacement();
1605 // detachChildren() can trigger this frame's unload event, and therefore
1606 // script can run and do just about anything. For example, an unload event that calls
1607 // document.write("") on its parent frame can lead to a recursive detachChildren()
1608 // invocation for this frame. In that case, we can end up at this point with a
1609 // loader that hasn't been deleted but has been detached from its frame. Such a
1610 // DocumentLoader has been sufficiently detached that we'll end up in an inconsistent
1611 // state if we try to use it.
1612 if (loader && !loader->frame())
1615 if (m_documentLoader)
1616 m_documentLoader->detachFromFrame();
1618 m_documentLoader = loader;
1621 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1623 if (m_policyDocumentLoader == loader)
1628 loader->setFrame(m_frame);
1629 if (m_policyDocumentLoader
1630 && m_policyDocumentLoader != m_provisionalDocumentLoader
1631 && m_policyDocumentLoader != m_documentLoader)
1632 m_policyDocumentLoader->detachFromFrame();
1634 m_policyDocumentLoader = loader;
1637 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1639 ASSERT(!loader || !m_provisionalDocumentLoader);
1640 ASSERT(!loader || loader->frameLoader() == this);
1642 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1643 m_provisionalDocumentLoader->detachFromFrame();
1645 m_provisionalDocumentLoader = loader;
1648 double FrameLoader::timeOfLastCompletedLoad()
1650 return storedTimeOfLastCompletedLoad;
1653 void FrameLoader::setState(FrameState newState)
1657 if (newState == FrameStateProvisional)
1658 provisionalLoadStarted();
1659 else if (newState == FrameStateComplete) {
1660 frameLoadCompleted();
1661 storedTimeOfLastCompletedLoad = currentTime();
1662 if (m_documentLoader)
1663 m_documentLoader->stopRecordingResponses();
1667 void FrameLoader::clearProvisionalLoad()
1669 setProvisionalDocumentLoader(0);
1670 m_progressTracker->progressCompleted();
1671 setState(FrameStateComplete);
1674 void FrameLoader::commitProvisionalLoad()
1676 RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1677 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1678 RefPtr<Frame> protect(m_frame);
1680 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1681 m_frame->document() ? m_frame->document()->url().elidedString().utf8().data() : "",
1682 pdl ? pdl->url().elidedString().utf8().data() : "<no provisional DocumentLoader>");
1684 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1685 // We are doing this here because we know for sure that a new page is about to be loaded.
1686 HistoryItem* item = history()->currentItem();
1687 if (!m_frame->tree()->parent() && pageCache()->canCache(m_frame->page()) && !item->isInPageCache())
1688 pageCache()->add(item, m_frame->page());
1690 if (m_loadType != FrameLoadTypeReplace)
1691 closeOldDataSources();
1693 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1694 m_client->makeRepresentation(pdl.get());
1696 transitionToCommitted(cachedPage);
1698 if (pdl && m_documentLoader) {
1699 // Check if the destination page is allowed to access the previous page's timing information.
1700 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1701 m_documentLoader->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_previousURL));
1704 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1705 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1706 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1707 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1708 if (m_sentRedirectNotification)
1709 clientRedirectCancelledOrFinished(false);
1711 if (cachedPage && cachedPage->document()) {
1712 prepareForCachedPageRestore();
1713 cachedPage->restore(m_frame->page());
1715 // The page should be removed from the cache immediately after a restoration in order for the PageCache to be consistent.
1716 pageCache()->remove(history()->currentItem());
1718 dispatchDidCommitLoad();
1720 // If we have a title let the WebView know about it.
1721 StringWithDirection title = m_documentLoader->title();
1722 if (!title.isNull())
1723 m_client->dispatchDidReceiveTitle(title);
1728 pageCache()->remove(history()->currentItem());
1732 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1733 m_frame->document() ? m_frame->document()->url().elidedString().utf8().data() : "");
1735 if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1736 history()->updateForClientRedirect();
1738 if (m_loadingFromCachedPage) {
1739 m_frame->document()->documentDidResumeFromPageCache();
1741 // Force a layout to update view size and thereby update scrollbars.
1742 m_frame->view()->forceLayout();
1744 const ResponseVector& responses = m_documentLoader->responses();
1745 size_t count = responses.size();
1746 for (size_t i = 0; i < count; i++) {
1747 const ResourceResponse& response = responses[i];
1748 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1749 ResourceError error;
1750 unsigned long identifier;
1751 ResourceRequest request(response.url());
1752 requestFromDelegate(request, identifier, error);
1753 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1754 // However, with today's computers and networking speeds, this won't happen in practice.
1755 // Could be an issue with a giant local file.
1756 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1759 // FIXME: Why only this frame and not parent frames?
1760 checkLoadCompleteForThisFrame();
1764 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1766 ASSERT(m_client->hasWebView());
1767 ASSERT(m_state == FrameStateProvisional);
1769 if (m_state != FrameStateProvisional)
1772 if (FrameView* view = m_frame->view()) {
1773 if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
1774 scrollAnimator->cancelAnimations();
1777 m_client->setCopiesOnScroll();
1778 history()->updateForCommit();
1780 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1781 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1782 // or the two will stomp each other.
1783 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1784 if (m_documentLoader)
1786 if (pdl != m_provisionalDocumentLoader)
1789 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1790 if (m_documentLoader)
1791 m_documentLoader->stopLoadingSubresources();
1792 if (m_documentLoader)
1793 m_documentLoader->stopLoadingPlugIns();
1795 setDocumentLoader(m_provisionalDocumentLoader.get());
1796 setProvisionalDocumentLoader(0);
1798 if (pdl != m_documentLoader) {
1799 ASSERT(m_state == FrameStateComplete);
1803 setState(FrameStateCommittedPage);
1805 #if ENABLE(TOUCH_EVENTS)
1806 if (isLoadingMainFrame())
1807 m_frame->page()->chrome()->client()->needTouchEvents(false);
1810 // Handle adding the URL to the back/forward list.
1811 DocumentLoader* dl = m_documentLoader.get();
1813 switch (m_loadType) {
1814 case FrameLoadTypeForward:
1815 case FrameLoadTypeBack:
1816 case FrameLoadTypeIndexedBackForward:
1817 if (m_frame->page()) {
1818 // If the first load within a frame is a navigation within a back/forward list that was attached
1819 // without any of the items being loaded then we need to update the history in a similar manner as
1820 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1821 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1822 history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1824 history()->updateForBackForwardNavigation();
1826 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1827 if (history()->currentItem() && !cachedPage)
1828 m_pendingStateObject = history()->currentItem()->stateObject();
1830 // Create a document view for this document, or used the cached view.
1832 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1833 ASSERT(cachedDocumentLoader);
1834 cachedDocumentLoader->setFrame(m_frame);
1835 m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1838 m_client->transitionToCommittedForNewPage();
1842 case FrameLoadTypeReload:
1843 case FrameLoadTypeReloadFromOrigin:
1844 case FrameLoadTypeSame:
1845 case FrameLoadTypeReplace:
1846 history()->updateForReload();
1847 m_client->transitionToCommittedForNewPage();
1850 case FrameLoadTypeStandard:
1851 history()->updateForStandardLoad();
1852 if (m_frame->view())
1853 m_frame->view()->setScrollbarsSuppressed(true);
1854 m_client->transitionToCommittedForNewPage();
1857 case FrameLoadTypeRedirectWithLockedBackForwardList:
1858 history()->updateForRedirectWithLockedBackForwardList();
1859 m_client->transitionToCommittedForNewPage();
1862 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1863 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1865 ASSERT_NOT_REACHED();
1868 m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
1870 // Tell the client we've committed this URL.
1871 ASSERT(m_frame->view());
1873 if (m_stateMachine.creatingInitialEmptyDocument())
1876 if (!m_stateMachine.committedFirstRealDocumentLoad())
1877 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1880 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1882 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1883 // the redirect succeeded. We should either rename this API, or add a new method, like
1884 // -webView:didFinishClientRedirectForFrame:
1885 m_client->dispatchDidCancelClientRedirect();
1887 if (!cancelWithLoadInProgress)
1888 m_quickRedirectComing = false;
1890 m_sentRedirectNotification = false;
1893 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
1895 m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
1897 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
1898 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
1899 m_sentRedirectNotification = true;
1901 // If a "quick" redirect comes in, we set a special mode so we treat the next
1902 // load as part of the original navigation. If we don't have a document loader, we have
1903 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
1904 // Loads triggered by JavaScript form submissions never count as quick redirects.
1905 m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
1908 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
1910 // This function implements the rule: "Don't reload if navigating by fragment within
1911 // the same URL, but do reload if going to a new URL or to the same URL with no
1912 // fragment identifier at all."
1913 if (!destinationURL.hasFragmentIdentifier())
1915 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
1918 void FrameLoader::closeOldDataSources()
1920 // FIXME: Is it important for this traversal to be postorder instead of preorder?
1921 // If so, add helpers for postorder traversal, and use them. If not, then lets not
1922 // use a recursive algorithm here.
1923 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1924 child->loader()->closeOldDataSources();
1926 if (m_documentLoader)
1927 m_client->dispatchWillClose();
1929 m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
1932 void FrameLoader::prepareForCachedPageRestore()
1934 ASSERT(!m_frame->tree()->parent());
1935 ASSERT(m_frame->page());
1936 ASSERT(m_frame->page()->mainFrame() == m_frame);
1938 m_frame->navigationScheduler()->cancel();
1940 // We still have to close the previous part page.
1943 // Delete old status bar messages (if it _was_ activated on last URL).
1944 if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
1945 DOMWindow* window = m_frame->document()->domWindow();
1946 window->setStatus(String());
1947 window->setDefaultStatus(String());
1951 void FrameLoader::open(CachedFrameBase& cachedFrame)
1953 m_isComplete = false;
1955 // Don't re-emit the load event.
1956 m_didCallImplicitClose = true;
1958 KURL url = cachedFrame.url();
1960 // FIXME: I suspect this block of code doesn't do anything.
1961 if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
1965 Document* document = cachedFrame.document();
1967 ASSERT(document->domWindow());
1969 clear(document, true, true, cachedFrame.isMainFrame());
1971 document->setInPageCache(false);
1973 m_needsClear = true;
1974 m_isComplete = false;
1975 m_didCallImplicitClose = false;
1976 m_outgoingReferrer = url.string();
1978 FrameView* view = cachedFrame.view();
1980 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
1982 view->setWasScrolledByUser(false);
1984 // Use the current ScrollView's frame rect.
1985 if (m_frame->view())
1986 view->setFrameRect(m_frame->view()->frameRect());
1987 m_frame->setView(view);
1989 m_frame->setDocument(document);
1990 document->domWindow()->resumeFromPageCache();
1992 updateFirstPartyForCookies();
1994 cachedFrame.restore();
1997 bool FrameLoader::isHostedByObjectElement() const
1999 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2000 return owner && owner->hasTagName(objectTag);
2003 bool FrameLoader::isLoadingMainFrame() const
2005 Page* page = m_frame->page();
2006 return page && m_frame == page->mainFrame();
2009 bool FrameLoader::isReplacing() const
2011 return m_loadType == FrameLoadTypeReplace;
2014 void FrameLoader::setReplacing()
2016 m_loadType = FrameLoadTypeReplace;
2019 bool FrameLoader::subframeIsLoading() const
2021 // It's most likely that the last added frame is the last to load so we walk backwards.
2022 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2023 FrameLoader* childLoader = child->loader();
2024 DocumentLoader* documentLoader = childLoader->documentLoader();
2025 if (documentLoader && documentLoader->isLoadingInAPISense())
2027 documentLoader = childLoader->provisionalDocumentLoader();
2028 if (documentLoader && documentLoader->isLoadingInAPISense())
2030 documentLoader = childLoader->policyDocumentLoader();
2037 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2039 m_client->willChangeTitle(loader);
2042 FrameLoadType FrameLoader::loadType() const
2047 CachePolicy FrameLoader::subresourceCachePolicy() const
2050 return CachePolicyVerify;
2052 if (m_loadType == FrameLoadTypeReloadFromOrigin)
2053 return CachePolicyReload;
2055 if (Frame* parentFrame = m_frame->tree()->parent()) {
2056 CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
2057 if (parentCachePolicy != CachePolicyVerify)
2058 return parentCachePolicy;
2061 if (m_loadType == FrameLoadTypeReload)
2062 return CachePolicyRevalidate;
2064 const ResourceRequest& request(documentLoader()->request());
2066 if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2067 return CachePolicyRevalidate;
2070 if (request.cachePolicy() == ReturnCacheDataElseLoad)
2071 return CachePolicyHistoryBuffer;
2073 return CachePolicyVerify;
2076 void FrameLoader::checkLoadCompleteForThisFrame()
2078 ASSERT(m_client->hasWebView());
2080 Settings* settings = m_frame->settings();
2083 case FrameStateProvisional: {
2084 if (m_delegateIsHandlingProvisionalLoadError)
2087 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2091 // If we've received any errors we may be stuck in the provisional state and actually complete.
2092 const ResourceError& error = pdl->mainDocumentError();
2096 // Check all children first.
2097 RefPtr<HistoryItem> item;
2098 if (Page* page = m_frame->page())
2099 if (isBackForwardLoadType(loadType()))
2100 // Reset the back forward list to the last committed history item at the top level.
2101 item = page->mainFrame()->loader()->history()->currentItem();
2103 // Only reset if we aren't already going to a new provisional item.
2104 bool shouldReset = !history()->provisionalItem();
2105 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2106 m_delegateIsHandlingProvisionalLoadError = true;
2107 m_client->dispatchDidFailProvisionalLoad(error);
2108 m_delegateIsHandlingProvisionalLoadError = false;
2110 ASSERT(!pdl->isLoading());
2112 // If we're in the middle of loading multipart data, we need to restore the document loader.
2113 if (isReplacing() && !m_documentLoader.get())
2114 setDocumentLoader(m_provisionalDocumentLoader.get());
2116 // Finish resetting the load state, but only if another load hasn't been started by the
2117 // delegate callback.
2118 if (pdl == m_provisionalDocumentLoader)
2119 clearProvisionalLoad();
2120 else if (activeDocumentLoader()) {
2121 KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2122 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2123 shouldReset = false;
2126 if (shouldReset && item)
2127 if (Page* page = m_frame->page()) {
2128 page->backForward()->setCurrentItem(item.get());
2129 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2134 case FrameStateCommittedPage: {
2135 DocumentLoader* dl = m_documentLoader.get();
2136 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2139 setState(FrameStateComplete);
2141 // FIXME: Is this subsequent work important if we already navigated away?
2142 // Maybe there are bugs because of that, or extra work we can skip because
2143 // the new page is ready.
2145 m_client->forceLayoutForNonHTML();
2147 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2148 if (m_frame->page()) {
2149 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2150 history()->restoreScrollPositionAndViewState();
2153 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2156 if (!settings->needsDidFinishLoadOrderQuirk()) {
2157 m_progressTracker->progressCompleted();
2158 if (Page* page = m_frame->page()) {
2159 if (m_frame == page->mainFrame())
2160 page->resetRelevantPaintedObjectCounter();
2164 const ResourceError& error = dl->mainDocumentError();
2166 AXObjectCache::AXLoadingEvent loadingEvent;
2167 if (!error.isNull()) {
2168 m_client->dispatchDidFailLoad(error);
2169 loadingEvent = AXObjectCache::AXLoadingFailed;
2171 m_client->dispatchDidFinishLoad();
2172 loadingEvent = AXObjectCache::AXLoadingFinished;
2175 if (settings->needsDidFinishLoadOrderQuirk()) {
2176 m_progressTracker->progressCompleted();
2177 if (Page* page = m_frame->page()) {
2178 if (m_frame == page->mainFrame())
2179 page->resetRelevantPaintedObjectCounter();
2183 // Notify accessibility.
2184 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
2185 cache->frameLoadingEventNotification(m_frame, loadingEvent);
2190 case FrameStateComplete:
2191 m_loadType = FrameLoadTypeStandard;
2192 frameLoadCompleted();
2196 ASSERT_NOT_REACHED();
2199 void FrameLoader::continueLoadAfterWillSubmitForm()
2201 if (!m_provisionalDocumentLoader)
2204 prepareForLoadStart();
2206 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2207 // so we need to null check it again.
2208 if (!m_provisionalDocumentLoader)
2211 DocumentLoader* activeDocLoader = activeDocumentLoader();
2212 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2215 m_loadingFromCachedPage = false;
2216 m_provisionalDocumentLoader->startLoadingMainResource();
2219 static KURL originatingURLFromBackForwardList(Page* page)
2221 // FIXME: Can this logic be replaced with m_frame->document()->firstPartyForCookies()?
2222 // It has the same meaning of "page a user thinks is the current one".
2225 int backCount = page->backForward()->backCount();
2226 for (int backIndex = 0; backIndex <= backCount; backIndex++) {
2227 // FIXME: At one point we had code here to check a "was user gesture" flag.
2228 // Do we need to restore that logic?
2229 HistoryItem* historyItem = page->backForward()->itemAtIndex(-backIndex);
2233 originalURL = historyItem->originalURL();
2234 if (!originalURL.isNull())
2241 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2245 // If there is no referrer, assume that the download was initiated directly, so current document is
2246 // completely unrelated to it. See <rdar://problem/5294691>.
2247 // FIXME: Referrer is not sent in many other cases, so we will often miss this important information.
2248 // Find a better way to decide whether the download was unrelated to current document.
2249 if (!request.httpReferrer().isNull()) {
2250 // find the first item in the history that was originated by the user
2251 originalURL = originatingURLFromBackForwardList(m_frame->page());
2254 if (originalURL.isNull())
2255 originalURL = request.url();
2257 if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
2258 unsigned port = originalURL.port();
2260 // Original URL is needed to show the user where a file was downloaded from. We should make a URL that won't result in downloading the file again.
2261 // FIXME: Using host-only URL is a very heavy-handed approach. We should attempt to provide the actual page where the download was initiated from, as a reminder to the user.
2262 String hostOnlyURLString;
2264 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ":", String::number(port));
2266 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
2268 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2269 request.setFirstPartyForCookies(KURL(KURL(), hostOnlyURLString));
2273 void FrameLoader::didLayout(LayoutMilestones milestones)
2275 m_client->dispatchDidLayout(milestones);
2278 void FrameLoader::didFirstLayout()
2280 if (m_frame->page() && isBackForwardLoadType(m_loadType))
2281 history()->restoreScrollPositionAndViewState();
2283 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2284 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2287 void FrameLoader::frameLoadCompleted()
2289 // Note: Can be called multiple times.
2291 m_client->frameLoadCompleted();
2293 history()->updateForFrameLoadCompleted();
2295 // After a canceled provisional load, firstLayoutDone is false.
2296 // Reset it to true if we're displaying a page.
2297 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2298 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2301 void FrameLoader::detachChildren()
2303 typedef Vector<RefPtr<Frame> > FrameVector;
2304 FrameVector childrenToDetach;
2305 childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2306 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2307 childrenToDetach.append(child);
2308 FrameVector::iterator end = childrenToDetach.end();
2309 for (FrameVector::iterator it = childrenToDetach.begin(); it != end; ++it)
2310 (*it)->loader()->detachFromParent();
2313 void FrameLoader::closeAndRemoveChild(Frame* child)
2315 child->tree()->detachFromParent();
2318 if (child->ownerElement() && child->page())
2319 child->page()->decrementSubframeCount();
2320 child->willDetachPage();
2321 child->detachFromPage();
2323 m_frame->tree()->removeChild(child);
2326 // Called every time a resource is completely loaded or an error is received.
2327 void FrameLoader::checkLoadComplete()
2329 ASSERT(m_client->hasWebView());
2331 m_shouldCallCheckLoadComplete = false;
2333 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2334 // is currently needed in order to null out the previous history item for all frames.
2335 if (Page* page = m_frame->page()) {
2336 Vector<RefPtr<Frame>, 10> frames;
2337 for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2338 frames.append(frame);
2339 // To process children before their parents, iterate the vector backwards.
2340 for (size_t i = frames.size(); i; --i)
2341 frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
2345 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2348 return m_frame->document()->cachedResourceLoader()->requestCount();
2351 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2352 count += frame->document()->cachedResourceLoader()->requestCount();
2356 String FrameLoader::userAgent(const KURL& url) const
2358 String userAgent = m_client->userAgent(url);
2359 InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2363 void FrameLoader::handledOnloadEvents()
2365 m_client->dispatchDidHandleOnloadEvents();
2367 if (documentLoader())
2368 documentLoader()->handledOnloadEvents();
2371 void FrameLoader::frameDetached()
2374 m_frame->document()->stopActiveDOMObjects();
2378 void FrameLoader::detachFromParent()
2380 RefPtr<Frame> protect(m_frame);
2383 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2385 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2386 // will trigger the unload event handlers of any child frames, and those event
2387 // handlers might start a new subresource load in this frame.
2390 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2392 detachViewsAndDocumentLoader();
2394 m_progressTracker.clear();
2396 if (Frame* parent = m_frame->tree()->parent()) {
2397 parent->loader()->closeAndRemoveChild(m_frame);
2398 parent->loader()->scheduleCheckCompleted();
2400 m_frame->setView(0);
2401 m_frame->willDetachPage();
2402 m_frame->detachFromPage();
2406 void FrameLoader::detachViewsAndDocumentLoader()
2408 m_client->detachedFromParent2();
2409 setDocumentLoader(0);
2410 m_client->detachedFromParent3();
2413 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2415 addExtraFieldsToRequest(request, m_loadType, false);
2418 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2420 // FIXME: Using m_loadType seems wrong for some callers.
2421 // If we are only preparing to load the main resource, that is previous load's load type!
2422 addExtraFieldsToRequest(request, m_loadType, true);
2425 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2427 // Don't set the cookie policy URL if it's already been set.
2428 // But make sure to set it on all requests regardless of protocol, as it has significance beyond the cookie policy (<rdar://problem/6616664>).
2429 if (request.firstPartyForCookies().isEmpty()) {
2430 if (mainResource && isLoadingMainFrame())
2431 request.setFirstPartyForCookies(request.url());
2432 else if (Document* document = m_frame->document())
2433 request.setFirstPartyForCookies(document->firstPartyForCookies());
2436 // The remaining modifications are only necessary for HTTP and HTTPS.
2437 if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
2440 applyUserAgent(request);
2442 if (!mainResource) {
2443 if (request.isConditional())
2444 request.setCachePolicy(ReloadIgnoringCacheData);
2445 else if (documentLoader()->isLoadingInAPISense()) {
2446 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2447 // original request cache policy for two reasons:
2448 // 1. For POST requests, we mutate the cache policy for the main resource,
2449 // but we do not want this to apply to subresources
2450 // 2. Delegates that modify the cache policy using willSendRequest: should
2451 // not affect any other resources. Such changes need to be done
2453 ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
2454 // 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.
2455 // This policy is set on initial request too, but should not be inherited.
2456 ResourceRequestCachePolicy subresourceCachePolicy = (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
2457 request.setCachePolicy(subresourceCachePolicy);
2459 request.setCachePolicy(UseProtocolCachePolicy);
2461 // FIXME: Other FrameLoader functions have duplicated code for setting cache policy of main request when reloading.
2462 // It seems better to manage it explicitly than to hide the logic inside addExtraFieldsToRequest().
2463 } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2464 request.setCachePolicy(ReloadIgnoringCacheData);
2466 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2467 if (loadType == FrameLoadTypeReload)
2468 request.setHTTPHeaderField("Cache-Control", "max-age=0");
2469 else if (loadType == FrameLoadTypeReloadFromOrigin) {
2470 request.setHTTPHeaderField("Cache-Control", "no-cache");
2471 request.setHTTPHeaderField("Pragma", "no-cache");
2476 request.setHTTPAccept(defaultAcceptHeader);
2478 // Make sure we send the Origin header.
2479 addHTTPOriginIfNeeded(request, String());
2481 // Always try UTF-8. If that fails, try frame encoding (if any) and then the default.
2482 Settings* settings = m_frame->settings();
2483 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame->document()->encoding(), settings ? settings->defaultTextEncodingName() : String());
2486 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2488 if (!request.httpOrigin().isEmpty())
2489 return; // Request already has an Origin header.
2491 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2492 // For example, if an intranet page has a hyperlink to an external web
2493 // site, we don't want to include the Origin of the request because it
2494 // will leak the internal host name. Similar privacy concerns have lead
2495 // to the widespread suppression of the Referer header at the network
2497 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2500 // For non-GET and non-HEAD methods, always send an Origin header so the
2501 // server knows we support this feature.
2503 if (origin.isEmpty()) {
2504 // If we don't know what origin header to attach, we attach the value
2505 // for an empty origin.
2506 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2510 request.setHTTPOrigin(origin);
2513 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2515 RefPtr<FormState> formState = prpFormState;
2517 // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a
2518 // bunch of parameters that would come in here and then be built back up to a ResourceRequest. In case
2519 // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2520 // from scratch as it did all along.
2521 const KURL& url = inRequest.url();
2522 RefPtr<FormData> formData = inRequest.httpBody();
2523 const String& contentType = inRequest.httpContentType();
2524 String origin = inRequest.httpOrigin();
2526 ResourceRequest workingResourceRequest(url);
2528 if (!referrer.isEmpty())
2529 workingResourceRequest.setHTTPReferrer(referrer);
2530 workingResourceRequest.setHTTPOrigin(origin);
2531 workingResourceRequest.setHTTPMethod("POST");
2532 workingResourceRequest.setHTTPBody(formData);
2533 workingResourceRequest.setHTTPContentType(contentType);
2534 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2536 NavigationAction action(workingResourceRequest, loadType, true, event);
2538 if (!frameName.isEmpty()) {
2539 // The search for a target frame is done earlier in the case of form submission.
2540 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2541 targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2543 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2545 // must grab this now, since this load may stop the previous load and clear this flag
2546 bool isRedirect = m_quickRedirectComing;
2547 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2549 m_quickRedirectComing = false;
2550 if (m_provisionalDocumentLoader)
2551 m_provisionalDocumentLoader->setIsClientRedirect(true);
2556 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2558 ASSERT(m_frame->document());
2559 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), outgoingReferrer());
2561 ResourceRequest initialRequest = request;
2562 initialRequest.setTimeoutInterval(10);
2564 if (!referrer.isEmpty())
2565 initialRequest.setHTTPReferrer(referrer);
2566 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2568 if (Page* page = m_frame->page())
2569 initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url());
2571 addExtraFieldsToSubresourceRequest(initialRequest);
2573 unsigned long identifier = 0;
2574 ResourceRequest newRequest(initialRequest);
2575 requestFromDelegate(newRequest, identifier, error);
2577 if (error.isNull()) {
2578 ASSERT(!newRequest.isNull());
2580 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2581 #if USE(PLATFORM_STRATEGIES)
2582 platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, data);
2584 ResourceHandle::loadResourceSynchronously(networkingContext(), newRequest, storedCredentials, error, response, data);
2586 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2589 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data.data(), data.size(), -1, error);
2593 const ResourceRequest& FrameLoader::originalRequest() const
2595 return activeDocumentLoader()->originalRequestCopy();
2598 void FrameLoader::receivedMainResourceError(const ResourceError& error)
2600 // Retain because the stop may release the last reference to it.
2601 RefPtr<Frame> protect(m_frame);
2603 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2604 // FIXME: Don't want to do this if an entirely new load is going, so should check
2605 // that both data sources on the frame are either this or nil.
2607 if (m_client->shouldFallBack(error))
2608 handleFallbackContent();
2610 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2611 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2612 m_submittedFormURL = KURL();
2614 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2615 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2616 // so that the existing view (that wenever got far enough to replace) can continue being used.
2617 history()->invalidateCurrentItemCachedPage();
2619 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2620 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2621 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2622 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2624 if (m_sentRedirectNotification)
2625 clientRedirectCancelledOrFinished(false);
2629 if (m_frame->page())
2630 checkLoadComplete();
2633 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2634 const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2636 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2637 loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2640 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2642 m_quickRedirectComing = false;
2644 if (!shouldContinue)
2647 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2648 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2649 m_provisionalDocumentLoader->stopLoading();
2650 setProvisionalDocumentLoader(0);
2653 bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;
2654 loadInSameDocument(request.url(), 0, !isRedirect);
2657 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2659 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2660 // currently displaying a frameset, or if the URL does not have a fragment.
2661 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2663 // FIXME: What about load types other than Standard and Reload?
2665 return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2666 && loadType != FrameLoadTypeReload
2667 && loadType != FrameLoadTypeReloadFromOrigin
2668 && loadType != FrameLoadTypeSame
2669 && !shouldReload(m_frame->document()->url(), url)
2670 // We don't want to just scroll if a link from within a
2671 // frameset is trying to reload the frameset into _top.
2672 && !m_frame->document()->isFrameSet();
2675 void FrameLoader::scrollToFragmentWithParentBoundary(const KURL& url)
2677 FrameView* view = m_frame->view();
2681 // Leaking scroll position to a cross-origin ancestor would permit the so-called "framesniffing" attack.
2682 RefPtr<Frame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame->document()->findUnsafeParentScrollPropagationBoundary() : 0);
2685 boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
2687 view->scrollToFragment(url);
2690 boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
2693 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2694 const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2696 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2697 loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2700 bool FrameLoader::shouldClose()
2702 Page* page = m_frame->page();
2703 Chrome* chrome = page ? page->chrome() : 0;
2704 if (!chrome || !chrome->canRunBeforeUnloadConfirmPanel())
2707 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2708 Vector<RefPtr<Frame> > targetFrames;
2709 targetFrames.append(m_frame);
2710 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2711 targetFrames.append(child);
2713 bool shouldClose = false;
2715 NavigationDisablerForBeforeUnload navigationDisabler;
2718 for (i = 0; i < targetFrames.size(); i++) {
2719 if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2721 if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(chrome))
2725 if (i == targetFrames.size())
2730 m_submittedFormURL = KURL();
2735 bool FrameLoader::fireBeforeUnloadEvent(Chrome* chrome)
2737 DOMWindow* domWindow = m_frame->document()->domWindow();
2741 RefPtr<Document> document = m_frame->document();
2742 if (!document->body())
2745 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2746 m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2747 domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2748 m_pageDismissalEventBeingDispatched = NoDismissal;
2750 if (!beforeUnloadEvent->defaultPrevented())
2751 document->defaultEventHandler(beforeUnloadEvent.get());
2752 if (beforeUnloadEvent->result().isNull())
2755 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2756 return chrome->runBeforeUnloadConfirmPanel(text, m_frame);
2759 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2761 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2762 // nil policyDataSource because loading the alternate page will have passed
2763 // through this method already, nested; otherwise, policyDataSource should still be set.
2764 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2766 bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2768 // Two reasons we can't continue:
2769 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
2770 // is the user responding Cancel to the form repost nag sheet.
2771 // 2) User responded Cancel to an alert popped up by the before unload event handler.
2772 bool canContinue = shouldContinue && shouldClose();
2775 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
2776 // need to report that the client redirect was cancelled.
2777 if (m_quickRedirectComing)
2778 clientRedirectCancelledOrFinished(false);
2780 setPolicyDocumentLoader(0);
2782 // If the navigation request came from the back/forward menu, and we punt on it, we have the
2783 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
2784 // we only do this when punting a navigation for the target frame or top-level frame.
2785 if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2786 if (Page* page = m_frame->page()) {
2787 Frame* mainFrame = page->mainFrame();
2788 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem()) {
2789 page->backForward()->setCurrentItem(resetItem);
2790 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2797 FrameLoadType type = policyChecker()->loadType();
2798 // A new navigation is in progress, so don't clear the history's provisional item.
2799 stopAllLoaders(ShouldNotClearProvisionalItem);
2801 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2802 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
2803 if (!m_frame->page())
2806 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2807 if (Page* page = m_frame->page()) {
2808 if (page->mainFrame() == m_frame)
2809 m_frame->page()->inspectorController()->resume();
2813 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2815 setState(FrameStateProvisional);
2817 setPolicyDocumentLoader(0);
2819 if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
2820 loadProvisionalItemFromCachedPage();
2825 m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
2827 continueLoadAfterWillSubmitForm();
2830 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
2831 const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2833 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2834 loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
2837 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
2838 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2840 if (!shouldContinue)
2843 RefPtr<Frame> frame = m_frame;
2844 RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
2848 if (frameName != "_blank")
2849 mainFrame->tree()->setName(frameName);
2851 mainFrame->page()->setOpenedByDOM();
2852 mainFrame->loader()->m_client->dispatchShow();
2853 if (!m_suppressOpenerInNewFrame) {
2854 mainFrame->loader()->setOpener(frame.get());
2855 mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
2857 mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(request), false, FrameLoadTypeStandard, formState);
2860 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
2862 ASSERT(!request.isNull());
2865 if (Page* page = m_frame->page()) {
2866 identifier = page->progress()->createUniqueIdentifier();
2867 notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
2870 ResourceRequest newRequest(request);
2871 notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
2873 if (newRequest.isNull())
2874 error = cancelledError(request);
2876 error = ResourceError();
2878 request = newRequest;
2881 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
2883 newRequest = ResourceRequest(resource->url());
2885 Page* page = m_frame->page();
2889 if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
2892 // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
2893 if (resource->type() == CachedResource::MainResource)
2896 if (!page->areMemoryCacheClientCallsEnabled()) {
2897 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2898 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
2899 m_documentLoader->didTellClientAboutLoad(resource->url());
2903 if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
2904 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2905 m_documentLoader->didTellClientAboutLoad(resource->url());
2909 unsigned long identifier;
2910 ResourceError error;
2911 requestFromDelegate(newRequest, identifier, error);
2912 InspectorInstrumentation::markResourceAsCached(page, identifier);
2913 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
2916 void FrameLoader::applyUserAgent(ResourceRequest& request)
2918 String userAgent = this->userAgent(request.url());
2919 ASSERT(!userAgent.isNull());
2920 request.setHTTPUserAgent(userAgent);
2923 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
2925 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptions);
2927 Frame* topFrame = m_frame->tree()->top();
2928 if (m_frame == topFrame)
2931 XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
2933 switch (disposition) {
2934 case XFrameOptionsSameOrigin: {
2935 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOrigin);
2936 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
2937 if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
2939 for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
2940 if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
2941 FeatureObserver::observe(m_frame->document(), FeatureObserver::XFrameOptionsSameOriginWithBadAncestorChain);
2947 case XFrameOptionsDeny:
2949 case XFrameOptionsAllowAll:
2951 case XFrameOptionsConflict:
2952 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.elidedString() + "'. Falling back to 'DENY'.", requestIdentifier);
2954 case XFrameOptionsInvalid:
2955 m_frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.elidedString() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
2958 ASSERT_NOT_REACHED();
2963 void FrameLoader::loadProvisionalItemFromCachedPage()
2965 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
2966 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().elidedString().utf8().data());
2968 prepareForLoadStart();
2970 m_loadingFromCachedPage = true;
2972 // Should have timing data from previous time(s) the page was shown.
2973 ASSERT(provisionalLoader->timing()->navigationStart());
2974 provisionalLoader->resetTiming();
2975 provisionalLoader->timing()->markNavigationStart();
2977 provisionalLoader->setCommitted(true);
2978 commitProvisionalLoad();
2981 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
2983 if (!history()->currentItem())
2985 return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
2988 bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
2990 if (!equalIgnoringCase(url.string(), "about:srcdoc"))
2992 HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
2995 if (!ownerElement->hasTagName(iframeTag))
2997 return ownerElement->fastHasAttribute(srcdocAttr);
3000 void FrameLoader::checkDidPerformFirstNavigation()
3002 Page* page = m_frame->page();
3006 if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3007 m_didPerformFirstNavigation = true;
3008 m_client->didPerformFirstNavigation();
3012 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
3014 Frame* frame = m_frame->tree()->find(name);
3016 // From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
3018 // If the source browsing context is the same as the browsing context
3019 // being navigated, and this browsing context has its seamless browsing
3020 // context flag set, and the browsing context being navigated was not
3021 // chosen using an explicit self-navigation override, then find the
3022 // nearest ancestor browsing context that does not have its seamless
3023 // browsing context flag set, and continue these steps as if that
3024 // browsing context was the one that was going to be navigated instead.
3025 if (frame == m_frame && name != "_self" && m_frame->document()->shouldDisplaySeamlesslyWithParent()) {
3026 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
3027 if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
3032 ASSERT(frame != m_frame);
3035 if (activeDocument) {
3036 if (!activeDocument->canNavigate(frame))
3039 // FIXME: Eventually all callers should supply the actual activeDocument
3040 // so we can call canNavigate with the right document.
3041 if (!m_frame->document()->canNavigate(frame))
3048 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3050 ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3052 // Save user view state to the current history item here since we don't do a normal load.
3053 // FIXME: Does form state need to be saved here too?
3054 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3055 if (FrameView* view = m_frame->view())
3056 view->setWasScrolledByUser(false);
3058 history()->setCurrentItem(item);
3060 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3061 loadInSameDocument(item->url(), item->stateObject(), false);
3063 // Restore user view state from the current history item here since we don't do a normal load.
3064 history()->restoreScrollPositionAndViewState();
3067 // FIXME: This function should really be split into a couple pieces, some of
3068 // which should be methods of HistoryController and some of which should be
3069 // methods of FrameLoader.
3070 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
3072 // Remember this item so we can traverse any child items as child frames load
3073 history()->setProvisionalItem(item);
3075 if (CachedPage* cachedPage = pageCache()->get(item)) {
3076 loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
3080 KURL itemURL = item->url();
3081 KURL itemOriginalURL = item->originalURL();
3083 if (documentLoader())
3084 currentURL = documentLoader()->url();
3085 RefPtr<FormData> formData = item->formData();
3087 ResourceRequest request(itemURL);
3089 if (!item->referrer().isNull())
3090 request.setHTTPReferrer(item->referrer());
3092 // If this was a repost that failed the page cache, we might try to repost the form.
3093 NavigationAction action;
3095 formData->generateFiles(m_frame->document());
3097 request.setHTTPMethod("POST");
3098 request.setHTTPBody(formData);
3099 request.setHTTPContentType(item->formContentType());
3100 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3101 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3103 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3104 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3105 addExtraFieldsToRequest(request, loadType, true);
3107 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3108 // We want to know this before talking to the policy delegate, since it affects whether
3109 // we show the DoYouReallyWantToRepost nag.
3111 // This trick has a small bug (3123893) where we might find a cache hit, but then
3112 // have the item vanish when we try to use it in the ensuing nav. This should be
3113 // extremely rare, but in that case the user will get an error on the navigation.
3115 if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
3116 request.setCachePolicy(ReturnCacheDataDontLoad);
3117 action = NavigationAction(request, loadType, false);
3119 request.setCachePolicy(ReturnCacheDataElseLoad);
3120 action = NavigationAction(request, NavigationTypeFormResubmitted);
3124 case FrameLoadTypeReload:
3125 case FrameLoadTypeReloadFromOrigin:
3126 request.setCachePolicy(ReloadIgnoringCacheData);
3128 case FrameLoadTypeBack:
3129 case FrameLoadTypeForward:
3130 case FrameLoadTypeIndexedBackForward:
3131 // If the first load within a frame is a navigation within a back/forward list that was attached
3132 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3133 if (m_stateMachine.committedFirstRealDocumentLoad())
3134 request.setCachePolicy(ReturnCacheDataElseLoad);
3136 case FrameLoadTypeStandard:
3137 case FrameLoadTypeRedirectWithLockedBackForwardList:
3139 case FrameLoadTypeSame:
3141 ASSERT_NOT_REACHED();
3144 addExtraFieldsToRequest(request, loadType, true);
3146 ResourceRequest requestForOriginalURL(request);
3147 requestForOriginalURL.setURL(itemOriginalURL);
3148 action = NavigationAction(requestForOriginalURL, loadType, false);
3151 loadWithNavigationAction(request, action, false, loadType, 0);
3154 // Loads content into this frame, as specified by history item
3155 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3157 m_requestedHistoryItem = item;
3158 HistoryItem* currentItem = history()->currentItem();
3159 bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3161 if (sameDocumentNavigation)
3162 loadSameDocumentItem(item);
3164 loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
3167 void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
3169 ASSERT(m_state == FrameStateProvisional);
3170 ASSERT(!m_loadingFromCachedPage);
3171 // We only use cache-only loads to avoid resubmitting forms.
3172 ASSERT(isBackForwardLoadType(m_loadType));
3173 ASSERT(m_history->provisionalItem()->formData());
3174 ASSERT(m_history->provisionalItem() == m_requestedHistoryItem.get());
3176 FrameLoadType loadType = m_loadType;
3177 HistoryItem* item = m_history->provisionalItem();
3179 stopAllLoaders(ShouldNotClearProvisionalItem);
3180 loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
3183 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3185 ResourceError error = m_client->cancelledError(request);
3186 error.setIsCancellation(true);
3190 void FrameLoader::setTitle(const StringWithDirection& title)
3192 documentLoader()->setTitle(title);
3195 String FrameLoader::referrer() const
3197 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3200 void FrameLoader::dispatchDocumentElementAvailable()
3202 m_frame->injectUserScripts(InjectAtDocumentStart);
3203 m_client->documentElementAvailable();
3206 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3208 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3211 Vector<RefPtr<DOMWrapperWorld> > worlds;
3212 ScriptController::getAllWorlds(worlds);
3213 for (size_t i = 0; i < worlds.size(); ++i)
3214 dispatchDidClearWindowObjectInWorld(worlds[i].get());
3217 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3219 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3222 m_client->dispatchDidClearWindowObjectInWorld(world);
3224 #if ENABLE(INSPECTOR)
3225 if (Page* page = m_frame->page())
3226 page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3229 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3232 void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
3234 Vector<RefPtr<DOMWrapperWorld> > worlds;
3235 ScriptController::getAllWorlds(worlds);
3236 for (size_t i = 0; i < worlds.size(); ++i)
3237 m_client->dispatchGlobalObjectAvailable(worlds[i].get());
3240 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3242 SandboxFlags flags = m_forcedSandboxFlags;
3243 if (Frame* parentFrame = m_frame->tree()->parent())
3244 flags |= parentFrame->document()->sandboxFlags();
3245 if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3246 flags |= ownerElement->sandboxFlags();
3250 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3252 m_client->didChangeTitle(loader);
3254 if (loader == m_documentLoader) {
3255 // Must update the entries in the back-forward list too.
3256 history()->setCurrentItemTitle(loader->title());
3257 // This must go through the WebFrame because it has the right notion of the current b/f item.
3258 m_client->setTitle(loader->title(), loader->urlForHistory());
3259 m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3260 m_client->dispatchDidReceiveTitle(loader->title());
3264 void FrameLoader::didChangeIcons(IconType type)
3266 m_client->dispatchDidChangeIcons(type);
3269 void FrameLoader::dispatchDidCommitLoad()
3271 if (m_stateMachine.creatingInitialEmptyDocument())
3274 m_client->dispatchDidCommitLoad();
3276 if (isLoadingMainFrame()) {
3277 m_frame->page()->resetSeenPlugins();
3278 m_frame->page()->resetSeenMediaEngines();
3281 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3283 if (m_frame->page()->mainFrame() == m_frame)
3284 m_frame->page()->featureObserver()->didCommitLoad();
3288 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3290 ASSERT(m_frame->page());
3291 ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3293 if (!m_documentLoader)
3296 Vector<ResourceRequest> pastLoads;
3297 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3299 size_t size = pastLoads.size();
3300 for (size_t i = 0; i < size; ++i) {
3301 CachedResource* resource = memoryCache()->resourceForRequest(pastLoads[i]);
3303 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3304 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3305 // Consider if there's some efficient way of remembering enough to deliver this client call.
3306 // We have the URL, but not the rest of the response or the length.
3310 ResourceRequest request(resource->url());
3311 m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3315 NetworkingContext* FrameLoader::networkingContext() const
3317 return m_networkingContext.get();
3320 void FrameLoader::loadProgressingStatusChanged()
3322 FrameView* view = m_frame->page()->mainFrame()->view();
3323 view->updateLayerFlushThrottlingInAllFrames();
3324 view->adjustTiledBackingCoverage();
3327 bool FrameLoaderClient::hasHTMLView() const
3332 Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3334 ASSERT(!features.dialog || request.frameName().isEmpty());
3336 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3337 if (Frame* frame = lookupFrame->loader()->findFrameForNavigation(request.frameName(), openerFrame->document())) {
3338 if (Page* page = frame->page())
3339 page->chrome()->focus();
3345 // Sandboxed frames cannot open new auxiliary browsing contexts.
3346 if (isDocumentSandboxed(openerFrame, SandboxPopups)) {
3347 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
3348 openerFrame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().elidedString() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
3352 // FIXME: Setting the referrer should be the caller's responsibility.
3353 FrameLoadRequest requestWithReferrer = request;
3354 String referrer = SecurityPolicy::generateReferrerHeader(openerFrame->document()->referrerPolicy(), request.resourceRequest().url(), openerFrame->loader()->outgoingReferrer());
3355 if (!referrer.isEmpty())
3356 requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
3357 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
3359 if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
3364 Page* oldPage = openerFrame->page();
3368 NavigationAction action(requestWithReferrer.resourceRequest());
3369 Page* page = oldPage->chrome()->createWindow(openerFrame, requestWithReferrer, features, action);
3373 Frame* frame = page->mainFrame();
3375 frame->loader()->forceSandboxFlags(openerFrame->document()->sandboxFlags());
3377 if (request.frameName() != "_blank")
3378 frame->tree()->setName(request.frameName());
3380 page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3381 page->chrome()->setStatusbarVisible(features.statusBarVisible);
3382 page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
3383 page->chrome()->setMenubarVisible(features.menuBarVisible);
3384 page->chrome()->setResizable(features.resizable);
3386 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3387 // specify the size of the viewport. We can only resize the window, so adjust
3388 // for the difference between the window size and the viewport size.
3390 FloatRect windowRect = page->chrome()->windowRect();
3391 FloatSize viewportSize = page->chrome()->pageRect().size();
3394 windowRect.setX(features.x);
3396 windowRect.setY(features.y);
3397 if (features.widthSet)
3398 windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
3399 if (features.heightSet)
3400 windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));
3402 // Ensure non-NaN values, minimum size as well as being within valid screen area.
3403 FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
3405 page->chrome()->setWindowRect(newWindowRect);
3406 page->chrome()->show();
3412 } // namespace WebCore