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>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
19 * its contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
23 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
26 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include "FrameLoader.h"
37 #include "ApplicationCacheHost.h"
38 #include "BackForwardController.h"
39 #include "BeforeUnloadEvent.h"
40 #include "MemoryCache.h"
41 #include "CachedPage.h"
42 #include "CachedResourceLoader.h"
44 #include "ChromeClient.h"
46 #include "ContentSecurityPolicy.h"
47 #include "DOMImplementation.h"
48 #include "DOMWindow.h"
50 #include "DocumentLoadTiming.h"
51 #include "DocumentLoader.h"
53 #include "EditorClient.h"
56 #include "EventNames.h"
57 #include "FloatRect.h"
58 #include "FormState.h"
59 #include "FormSubmission.h"
61 #include "FrameLoadRequest.h"
62 #include "FrameLoaderClient.h"
63 #include "FrameNetworkingContext.h"
64 #include "FrameTree.h"
65 #include "FrameView.h"
66 #include "HTMLAnchorElement.h"
67 #include "HTMLFormElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLObjectElement.h"
70 #include "HTTPParsers.h"
71 #include "HistoryItem.h"
72 #include "InspectorController.h"
73 #include "InspectorInstrumentation.h"
75 #include "MIMETypeRegistry.h"
76 #include "MainResourceLoader.h"
78 #include "PageCache.h"
79 #include "PageGroup.h"
80 #include "PageTransitionEvent.h"
81 #include "PluginData.h"
82 #include "PluginDatabase.h"
83 #include "PluginDocument.h"
84 #include "ProgressTracker.h"
85 #include "ResourceHandle.h"
86 #include "ResourceRequest.h"
87 #include "SchemeRegistry.h"
88 #include "ScrollAnimator.h"
89 #include "ScriptController.h"
90 #include "ScriptSourceCode.h"
91 #include "SecurityOrigin.h"
92 #include "SegmentedString.h"
93 #include "SerializedScriptValue.h"
95 #include "TextResourceDecoder.h"
96 #include "WindowFeatures.h"
97 #include "XMLDocumentParser.h"
98 #include <wtf/CurrentTime.h>
99 #include <wtf/StdLibExtras.h>
100 #include <wtf/text/CString.h>
101 #include <wtf/text/WTFString.h>
103 #if ENABLE(INPUT_COLOR)
104 #include "ColorChooser.h"
105 #include "ColorInputType.h"
108 #if ENABLE(SHARED_WORKERS)
109 #include "SharedWorkerRepository.h"
113 #include "SVGDocument.h"
114 #include "SVGLocatable.h"
115 #include "SVGNames.h"
116 #include "SVGPreserveAspectRatio.h"
117 #include "SVGSVGElement.h"
118 #include "SVGViewElement.h"
119 #include "SVGViewSpec.h"
122 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
124 #include "ArchiveFactory.h"
129 using namespace HTMLNames;
132 using namespace SVGNames;
136 static const char defaultAcceptHeader[] = "application/vnd.wap.xhtml+xml,application/xhtml+xml;profile='http://www.wapforum.org/xhtml',text/html,application/xml;q=0.9,*/*;q=0.8";
138 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
141 static double storedTimeOfLastCompletedLoad;
143 bool isBackForwardLoadType(FrameLoadType type)
146 case FrameLoadTypeStandard:
147 case FrameLoadTypeReload:
148 case FrameLoadTypeReloadFromOrigin:
149 case FrameLoadTypeSame:
150 case FrameLoadTypeRedirectWithLockedBackForwardList:
151 case FrameLoadTypeReplace:
153 case FrameLoadTypeBack:
154 case FrameLoadTypeForward:
155 case FrameLoadTypeIndexedBackForward:
158 ASSERT_NOT_REACHED();
162 // This is not in the FrameLoader class to emphasize that it does not depend on
163 // private FrameLoader data, and to avoid increasing the number of public functions
164 // with access to private data. Since only this .cpp file needs it, making it
165 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
168 // FIXME: isDocumentSandboxed should eventually replace isSandboxed.
169 static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
171 return frame->document() && frame->document()->securityOrigin()->isSandboxed(mask);
174 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
177 , m_policyChecker(frame)
180 , m_subframeLoader(frame)
182 , m_state(FrameStateCommittedPage)
183 , m_loadType(FrameLoadTypeStandard)
184 , m_delegateIsHandlingProvisionalLoadError(false)
185 , m_quickRedirectComing(false)
186 , m_sentRedirectNotification(false)
187 , m_inStopAllLoaders(false)
188 , m_isExecutingJavaScriptFormAction(false)
189 , m_didCallImplicitClose(false)
190 , m_wasUnloadEventEmitted(false)
191 , m_pageDismissalEventBeingDispatched(NoDismissal)
192 , m_isComplete(false)
193 , m_isLoadingMainResource(false)
194 , m_hasReceivedFirstData(false)
195 , m_needsClear(false)
196 , m_checkTimer(this, &FrameLoader::checkTimerFired)
197 , m_shouldCallCheckCompleted(false)
198 , m_shouldCallCheckLoadComplete(false)
200 , m_didPerformFirstNavigation(false)
201 , m_loadingFromCachedPage(false)
202 , m_suppressOpenerInNewFrame(false)
203 , m_sandboxFlags(SandboxAll)
204 , m_forcedSandboxFlags(SandboxNone)
208 FrameLoader::~FrameLoader()
212 HashSet<Frame*>::iterator end = m_openedFrames.end();
213 for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
214 (*it)->loader()->m_opener = 0;
216 m_client->frameLoaderDestroyed();
218 if (m_networkingContext)
219 m_networkingContext->invalidate();
222 void FrameLoader::init()
224 // Propagate sandbox attributes to this Frameloader and its descendants.
225 // This needs to be done early, so that an initial document gets correct sandbox flags in its SecurityOrigin.
226 updateSandboxFlags();
228 // This somewhat odd set of steps gives the frame an initial empty document.
229 // It would be better if this could be done with even fewer steps.
230 m_stateMachine.advanceTo(FrameLoaderStateMachine::CreatingInitialEmptyDocument);
231 setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, "")), SubstituteData()).get());
232 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
233 setState(FrameStateProvisional);
234 m_provisionalDocumentLoader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String()));
235 m_provisionalDocumentLoader->finishedLoading();
236 ASSERT(!m_frame->document());
237 m_documentLoader->writer()->begin(KURL(), false);
238 m_documentLoader->writer()->end();
239 m_frame->document()->cancelParsing();
240 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
241 m_didCallImplicitClose = true;
243 m_networkingContext = m_client->createNetworkingContext();
246 void FrameLoader::setDefersLoading(bool defers)
248 if (m_documentLoader)
249 m_documentLoader->setDefersLoading(defers);
250 if (m_provisionalDocumentLoader)
251 m_provisionalDocumentLoader->setDefersLoading(defers);
252 if (m_policyDocumentLoader)
253 m_policyDocumentLoader->setDefersLoading(defers);
254 history()->setDefersLoading(defers);
257 m_frame->navigationScheduler()->startTimer();
258 startCheckCompleteTimer();
262 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
264 RefPtr<Frame> protect(m_frame);
265 urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
266 0, lockHistory, lockBackForwardList, SendReferrer, ReplaceDocumentIfJavaScriptURL);
269 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ReferrerPolicy referrerPolicy)
271 urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
272 triggeringEvent, lockHistory, lockBackForwardList, referrerPolicy, DoNotReplaceDocumentIfJavaScriptURL);
275 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
276 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
277 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ReferrerPolicy referrerPolicy, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
279 ASSERT(!m_suppressOpenerInNewFrame);
281 FrameLoadRequest frameRequest(passedRequest);
283 if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
286 if (frameRequest.frameName().isEmpty())
287 frameRequest.setFrameName(m_frame->document()->baseTarget());
289 if (referrerPolicy == NoReferrer)
290 m_suppressOpenerInNewFrame = true;
291 if (frameRequest.resourceRequest().httpReferrer().isEmpty())
292 frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
293 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
295 loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, referrerPolicy);
297 m_suppressOpenerInNewFrame = false;
300 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
302 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
304 // FIXME: Find a good spot for these.
305 ASSERT(submission->data());
306 ASSERT(submission->state());
307 ASSERT(submission->state()->sourceFrame() == m_frame);
309 if (!m_frame->page())
312 if (submission->action().isEmpty())
315 if (isDocumentSandboxed(m_frame, SandboxForms))
318 if (protocolIsJavaScript(submission->action())) {
319 m_isExecutingJavaScriptFormAction = true;
320 m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
321 m_isExecutingJavaScriptFormAction = false;
325 Frame* targetFrame = m_frame->tree()->find(submission->target());
326 if (!shouldAllowNavigation(targetFrame))
329 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
332 targetFrame = m_frame;
334 submission->clearTarget();
336 if (!targetFrame->page())
339 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
341 // We do not want to submit more than one form from the same page, nor do we want to submit a single
342 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
343 // The flag is reset in each time we start handle a new mouse or key down event, and
344 // also in setView since this part may get reused for a page from the back/forward cache.
345 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
347 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
348 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
349 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
351 if (m_frame->tree()->isDescendantOf(targetFrame)) {
352 if (m_submittedFormURL == submission->action())
354 m_submittedFormURL = submission->action();
357 submission->data()->generateFiles(m_frame->document());
358 submission->setReferrer(m_outgoingReferrer);
359 submission->setOrigin(outgoingOrigin());
361 targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
364 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
366 if (m_frame->document() && m_frame->document()->parser())
367 m_frame->document()->parser()->stopParsing();
369 if (unloadEventPolicy != UnloadEventPolicyNone) {
370 if (m_frame->document()) {
371 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
372 Node* currentFocusedNode = m_frame->document()->focusedNode();
373 if (currentFocusedNode)
374 currentFocusedNode->aboutToUnload();
375 if (m_frame->domWindow() && m_pageDismissalEventBeingDispatched == NoDismissal) {
376 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
377 m_pageDismissalEventBeingDispatched = PageHideDismissal;
378 m_frame->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
380 if (!m_frame->document()->inPageCache()) {
381 RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
382 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
383 // while dispatching the event, so protect it to prevent writing the end
384 // time into freed memory.
385 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
386 m_pageDismissalEventBeingDispatched = UnloadDismissal;
387 if (documentLoader && !documentLoader->timing()->unloadEventStart && !documentLoader->timing()->unloadEventEnd) {
388 DocumentLoadTiming* timing = documentLoader->timing();
389 ASSERT(timing->navigationStart);
390 m_frame->domWindow()->dispatchTimedEvent(unloadEvent, m_frame->domWindow()->document(), &timing->unloadEventStart, &timing->unloadEventEnd);
392 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->domWindow()->document());
395 m_pageDismissalEventBeingDispatched = NoDismissal;
396 if (m_frame->document())
397 m_frame->document()->updateStyleIfNeeded();
398 m_wasUnloadEventEmitted = true;
402 // Dispatching the unload event could have made m_frame->document() null.
403 if (m_frame->document() && !m_frame->document()->inPageCache()) {
404 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
405 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
406 && m_frame->document()->securityOrigin()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
408 if (!keepEventListeners)
409 m_frame->document()->removeAllEventListeners();
413 m_isComplete = true; // to avoid calling completed() in finishedParsing()
414 m_isLoadingMainResource = false;
415 m_didCallImplicitClose = true; // don't want that one either
417 if (m_frame->document() && m_frame->document()->parsing()) {
419 m_frame->document()->setParsing(false);
422 m_hasReceivedFirstData = true;
424 if (Document* doc = m_frame->document()) {
425 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
426 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
427 doc->setReadyState(Document::Complete);
430 doc->stopDatabases(0);
434 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
435 m_frame->navigationScheduler()->cancel();
438 void FrameLoader::stop()
440 // http://bugs.webkit.org/show_bug.cgi?id=10854
441 // The frame's last ref may be removed and it will be deleted by checkCompleted().
442 RefPtr<Frame> protector(m_frame);
444 if (DocumentParser* parser = m_frame->document()->parser()) {
445 parser->stopParsing();
449 icon()->stopLoader();
452 bool FrameLoader::closeURL()
454 history()->saveDocumentState();
456 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
457 Document* currentDocument = m_frame->document();
458 stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
460 m_frame->editor()->clearUndoRedoOperations();
464 bool FrameLoader::didOpenURL()
466 if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
467 // A redirect was scheduled before the document was created.
468 // This can happen when one frame changes another frame's location.
472 m_frame->navigationScheduler()->cancel();
473 m_frame->editor()->clearLastEditCommand();
475 m_isComplete = false;
476 m_isLoadingMainResource = true;
477 m_didCallImplicitClose = false;
479 // If we are still in the process of initializing an empty document then
480 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
481 // since it may cause clients to attempt to render the frame.
482 if (!m_stateMachine.creatingInitialEmptyDocument()) {
483 if (DOMWindow* window = m_frame->existingDOMWindow()) {
484 window->setStatus(String());
485 window->setDefaultStatus(String());
488 m_hasReceivedFirstData = false;
495 void FrameLoader::didExplicitOpen()
497 m_isComplete = false;
498 m_didCallImplicitClose = false;
500 // Calling document.open counts as committing the first real document load.
501 if (!m_stateMachine.committedFirstRealDocumentLoad())
502 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
504 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
505 // from a subsequent window.document.open / window.document.write call.
506 // Canceling redirection here works for all cases because document.open
507 // implicitly precedes document.write.
508 m_frame->navigationScheduler()->cancel();
512 void FrameLoader::cancelAndClear()
514 m_frame->navigationScheduler()->cancel();
520 m_frame->script()->updatePlatformScriptObjects();
523 void FrameLoader::clear(bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
525 m_frame->editor()->clear();
529 m_needsClear = false;
531 if (!m_frame->document()->inPageCache()) {
532 m_frame->document()->cancelParsing();
533 m_frame->document()->stopActiveDOMObjects();
534 if (m_frame->document()->attached()) {
535 m_frame->document()->willRemove();
536 m_frame->document()->detach();
538 m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
542 // Do this after detaching the document so that the unload event works.
543 if (clearWindowProperties) {
544 m_frame->clearDOMWindow();
545 m_frame->script()->clearWindowShell(m_frame->document()->inPageCache());
548 m_frame->selection()->clear();
549 m_frame->eventHandler()->clear();
550 if (clearFrameView && m_frame->view())
551 m_frame->view()->clear();
553 // Do not drop the document before the ScriptController and view are cleared
554 // as some destructors might still try to access the document.
555 m_frame->setDocument(0);
557 m_subframeLoader.clear();
559 if (clearScriptObjects)
560 m_frame->script()->clearScriptObjects();
562 m_frame->navigationScheduler()->clear();
565 m_shouldCallCheckCompleted = false;
566 m_shouldCallCheckLoadComplete = false;
568 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
569 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
572 void FrameLoader::receivedFirstData()
574 KURL workingURL = activeDocumentLoader()->documentURL();
575 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
576 // FIXME: The document loader, not the frame loader, should be in charge of loading web archives.
577 // Once this is done, we can just make DocumentLoader::documentURL() return the right URL
578 // based on whether it has a non-null archive or not.
579 if (m_archive && activeDocumentLoader()->parsedArchiveData())
580 workingURL = m_archive->mainResource()->url();
583 activeDocumentLoader()->writer()->begin(workingURL, false);
584 activeDocumentLoader()->writer()->setDocumentWasLoadedAsPartOfNavigation();
586 dispatchDidCommitLoad();
587 dispatchDidClearWindowObjectsInAllWorlds();
589 if (m_documentLoader) {
590 StringWithDirection ptitle = m_documentLoader->title();
591 // If we have a title let the WebView know about it.
592 if (!ptitle.isNull())
593 m_client->dispatchDidReceiveTitle(ptitle);
596 m_hasReceivedFirstData = true;
598 if (!m_documentLoader)
600 if (m_frame->document()->isViewSource())
605 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
608 url = m_frame->document()->url().string();
610 url = m_frame->document()->completeURL(url).string();
612 m_frame->navigationScheduler()->scheduleRedirect(delay, url);
615 void FrameLoader::setOutgoingReferrer(const KURL& url)
617 m_outgoingReferrer = url.strippedForUseAsReferrer();
620 void FrameLoader::didBeginDocument(bool dispatch)
623 m_isComplete = false;
624 m_didCallImplicitClose = false;
625 m_isLoadingMainResource = true;
626 m_frame->document()->setReadyState(Document::Loading);
628 if (m_pendingStateObject) {
629 m_frame->document()->statePopped(m_pendingStateObject.get());
630 m_pendingStateObject.clear();
634 dispatchDidClearWindowObjectsInAllWorlds();
636 updateFirstPartyForCookies();
638 Settings* settings = m_frame->document()->settings();
639 m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically());
641 if (m_documentLoader) {
642 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
643 if (!dnsPrefetchControl.isEmpty())
644 m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
646 String contentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
647 if (!contentSecurityPolicy.isEmpty())
648 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(contentSecurityPolicy, ContentSecurityPolicy::EnforcePolicy);
650 String reportOnlyContentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
651 if (!contentSecurityPolicy.isEmpty())
652 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(reportOnlyContentSecurityPolicy, ContentSecurityPolicy::ReportOnly);
655 history()->restoreDocumentState();
658 void FrameLoader::didEndDocument()
660 m_isLoadingMainResource = false;
663 void FrameLoader::finishedParsing()
665 m_frame->injectUserScripts(InjectAtDocumentEnd);
667 if (m_stateMachine.creatingInitialEmptyDocument())
670 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
671 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
672 // Null-checking the FrameView indicates whether or not we're in the destructor.
673 RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
675 m_client->dispatchDidFinishDocumentLoad();
679 if (!m_frame->view())
680 return; // We are being destroyed by something checkCompleted called.
682 // Check if the scrollbars are really needed for the content.
683 // If not, remove them, relayout, and repaint.
684 m_frame->view()->restoreScrollbar();
685 m_frame->view()->scrollToFragment(m_frame->document()->url());
688 void FrameLoader::loadDone()
693 bool FrameLoader::allChildrenAreComplete() const
695 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
696 if (!child->loader()->m_isComplete)
702 bool FrameLoader::allAncestorsAreComplete() const
704 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
705 if (!ancestor->loader()->m_isComplete)
711 void FrameLoader::checkCompleted()
713 m_shouldCallCheckCompleted = false;
716 m_frame->view()->checkStopDelayingDeferredRepaints();
718 // Have we completed before?
722 // Are we still parsing?
723 if (m_frame->document()->parsing())
726 // Still waiting for images/scripts?
727 if (m_frame->document()->cachedResourceLoader()->requestCount())
730 // Still waiting for elements that don't go through a FrameLoader?
731 if (m_frame->document()->isDelayingLoadEvent())
734 // Any frame that hasn't completed yet?
735 if (!allChildrenAreComplete())
740 m_frame->document()->setReadyState(Document::Complete);
742 RefPtr<Frame> protect(m_frame);
743 checkCallImplicitClose(); // if we didn't do it before
745 m_frame->navigationScheduler()->startTimer();
752 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
754 if (Page* page = m_frame->page()) {
755 if (page->defersLoading())
758 if (m_shouldCallCheckCompleted)
760 if (m_shouldCallCheckLoadComplete)
764 void FrameLoader::startCheckCompleteTimer()
766 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
768 if (m_checkTimer.isActive())
770 m_checkTimer.startOneShot(0);
773 void FrameLoader::scheduleCheckCompleted()
775 m_shouldCallCheckCompleted = true;
776 startCheckCompleteTimer();
779 void FrameLoader::scheduleCheckLoadComplete()
781 m_shouldCallCheckLoadComplete = true;
782 startCheckCompleteTimer();
785 void FrameLoader::checkCallImplicitClose()
787 if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
790 if (!allChildrenAreComplete())
791 return; // still got a frame running -> too early
793 m_didCallImplicitClose = true;
794 m_wasUnloadEventEmitted = false;
795 m_frame->document()->implicitClose();
798 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
802 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
803 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);
804 if (subframeArchive) {
805 childFrame->loader()->loadArchive(subframeArchive.release());
808 #endif // ENABLE(WEB_ARCHIVE)
810 HistoryItem* parentItem = history()->currentItem();
811 // If we're moving in the back/forward list, we might want to replace the content
812 // of this child frame with whatever was there at that point.
813 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
814 && !m_frame->document()->loadEventFinished()) {
815 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
817 childFrame->loader()->loadDifferentDocumentItem(childItem, loadType());
822 childFrame->loader()->loadURL(url, referer, String(), false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
825 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
826 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
830 ArchiveResource* mainResource = m_archive->mainResource();
831 ASSERT(mainResource);
835 SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
837 ResourceRequest request(mainResource->url());
839 request.applyWebArchiveHackForMail();
842 RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
843 documentLoader->addAllArchiveResources(m_archive.get());
844 load(documentLoader.get());
846 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
848 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
850 String mimeType = mimeTypeIn;
851 String extension = url.path().substring(url.path().reverseFind('.') + 1);
853 // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
854 if (mimeType.isEmpty())
855 mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
857 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
858 if (mimeType.isEmpty())
859 mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
862 if (mimeType.isEmpty())
863 return ObjectContentFrame; // Go ahead and hope that we can display the content.
865 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
866 bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
868 bool plugInSupportsMIMEType = false;
871 if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
872 return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
874 if (plugInSupportsMIMEType)
875 return WebCore::ObjectContentNetscapePlugin;
877 if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
878 return WebCore::ObjectContentFrame;
880 return WebCore::ObjectContentNone;
883 String FrameLoader::outgoingReferrer() const
885 return m_outgoingReferrer;
888 String FrameLoader::outgoingOrigin() const
890 return m_frame->document()->securityOrigin()->toString();
893 bool FrameLoader::isMixedContent(SecurityOrigin* context, const KURL& url)
895 if (context->protocol() != "https")
896 return false; // We only care about HTTPS security origins.
898 if (!url.isValid() || SchemeRegistry::shouldTreatURLSchemeAsSecure(url.protocol()))
899 return false; // Loading these protocols is secure.
904 bool FrameLoader::checkIfDisplayInsecureContent(SecurityOrigin* context, const KURL& url)
906 if (!isMixedContent(context, url))
909 Settings* settings = m_frame->settings();
910 bool allowed = m_client->allowDisplayingInsecureContent(settings && settings->allowDisplayOfInsecureContent(), context, url);
911 String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
912 m_frame->document()->url().string() + " displayed insecure content from " + url.string() + ".\n";
914 m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
917 m_client->didDisplayInsecureContent();
922 bool FrameLoader::checkIfRunInsecureContent(SecurityOrigin* context, const KURL& url)
924 if (!isMixedContent(context, url))
927 Settings* settings = m_frame->settings();
928 bool allowed = m_client->allowRunningInsecureContent(settings && settings->allowRunningOfInsecureContent(), context, url);
929 String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
930 m_frame->document()->url().string() + " ran insecure content from " + url.string() + ".\n";
932 m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
935 m_client->didRunInsecureContent(context, url);
940 Frame* FrameLoader::opener()
945 void FrameLoader::setOpener(Frame* opener)
948 m_opener->loader()->m_openedFrames.remove(m_frame);
950 opener->loader()->m_openedFrames.add(m_frame);
953 if (m_frame->document()) {
954 m_frame->document()->initSecurityContext();
955 m_frame->domWindow()->setSecurityOrigin(m_frame->document()->securityOrigin());
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::willSetEncoding()
983 if (!m_hasReceivedFirstData)
987 void FrameLoader::updateFirstPartyForCookies()
989 if (m_frame->tree()->parent())
990 setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
992 setFirstPartyForCookies(m_frame->document()->url());
995 void FrameLoader::setFirstPartyForCookies(const KURL& url)
997 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
998 frame->document()->setFirstPartyForCookies(url);
1001 // This does the same kind of work that didOpenURL does, except it relies on the fact
1002 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1003 void FrameLoader::loadInSameDocument(const KURL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1005 // If we have a state object, we cannot also be a new navigation.
1006 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1008 // Update the data source's request with the new URL to fake the URL change
1009 KURL oldURL = m_frame->document()->url();
1010 m_frame->document()->setURL(url);
1011 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1012 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1013 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1014 // based on the current request. Must also happen before we openURL and displace the
1015 // scroll position, since adding the BF item will save away scroll state.
1017 // NB2: If we were loading a long, slow doc, and the user anchor nav'ed before
1018 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1019 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1020 // though its load is not yet done. I think this all works out OK, for one because
1021 // we have already saved away the scroll and doc state for the long slow load,
1022 // but it's not an obvious case.
1024 history()->updateBackForwardListForFragmentScroll();
1027 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1029 history()->updateForSameDocumentNavigation();
1031 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1033 m_frame->eventHandler()->stopAutoscrollTimer();
1035 // It's important to model this as a load that starts and immediately finishes.
1036 // Otherwise, the parent frame may think we never finished loading.
1039 // We need to scroll to the fragment whether or not a hash change occurred, since
1040 // the user might have scrolled since the previous navigation.
1041 if (FrameView* view = m_frame->view())
1042 view->scrollToFragment(url);
1044 m_isComplete = false;
1047 if (isNewNavigation) {
1048 // This will clear previousItem from the rest of the frame tree that didn't
1049 // doing any loading. We need to make a pass on this now, since for anchor nav
1050 // we'll not go through a real load and reach Completed state.
1051 checkLoadComplete();
1054 m_client->dispatchDidNavigateWithinPage();
1056 m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1057 m_client->dispatchDidPopStateWithinPage();
1060 m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1061 m_client->dispatchDidChangeLocationWithinPage();
1064 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1065 m_client->didFinishLoad();
1068 bool FrameLoader::isComplete() const
1070 return m_isComplete;
1073 void FrameLoader::completed()
1075 RefPtr<Frame> protect(m_frame);
1077 for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1078 descendant->navigationScheduler()->startTimer();
1080 if (Frame* parent = m_frame->tree()->parent())
1081 parent->loader()->checkCompleted();
1083 if (m_frame->view())
1084 m_frame->view()->maintainScrollPositionAtAnchor(0);
1087 void FrameLoader::started()
1089 for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1090 frame->loader()->m_isComplete = false;
1093 void FrameLoader::prepareForHistoryNavigation()
1095 // If there is no currentItem, but we still want to engage in
1096 // history navigation we need to manufacture one, and update
1097 // the state machine of this frame to impersonate having
1099 RefPtr<HistoryItem> currentItem = history()->currentItem();
1101 currentItem = HistoryItem::create();
1102 currentItem->setLastVisitWasFailure(true);
1103 history()->setCurrentItem(currentItem.get());
1104 frame()->page()->backForward()->setCurrentItem(currentItem.get());
1106 ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1107 stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1108 stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1112 void FrameLoader::prepareForLoadStart()
1114 if (Page* page = m_frame->page())
1115 page->progress()->progressStarted(m_frame);
1116 m_client->dispatchDidStartProvisionalLoad();
1119 void FrameLoader::setupForReplace()
1121 setState(FrameStateProvisional);
1122 m_provisionalDocumentLoader = m_documentLoader;
1123 m_documentLoader = 0;
1127 // This is a hack to allow keep navigation to http/https feeds working. To remove this
1128 // we need to introduce new API akin to registerURLSchemeAsLocal, that registers a
1129 // protocols navigation policy.
1130 static bool isFeedWithNestedProtocolInHTTPFamily(const KURL& url)
1132 const String& urlString = url.string();
1133 if (!urlString.startsWith("feed", false))
1136 return urlString.startsWith("feed://", false)
1137 || urlString.startsWith("feed:http:", false) || urlString.startsWith("feed:https:", false)
1138 || urlString.startsWith("feeds:http:", false) || urlString.startsWith("feeds:https:", false)
1139 || urlString.startsWith("feedsearch:http:", false) || urlString.startsWith("feedsearch:https:", false);
1142 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1143 PassRefPtr<Event> event, PassRefPtr<FormState> formState, ReferrerPolicy referrerPolicy)
1145 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1146 RefPtr<Frame> protect(m_frame);
1148 KURL url = request.resourceRequest().url();
1150 ASSERT(m_frame->document());
1151 // FIXME: Should we move the isFeedWithNestedProtocolInHTTPFamily logic inside SecurityOrigin::canDisplay?
1152 if (!isFeedWithNestedProtocolInHTTPFamily(url) && !request.requester()->canDisplay(url)) {
1153 reportLocalLoadFailed(m_frame, url.string());
1158 String argsReferrer = request.resourceRequest().httpReferrer();
1159 if (!argsReferrer.isEmpty())
1160 referrer = argsReferrer;
1162 referrer = m_outgoingReferrer;
1164 if (SecurityOrigin::shouldHideReferrer(url, referrer) || referrerPolicy == NoReferrer)
1165 referrer = String();
1167 FrameLoadType loadType;
1168 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1169 loadType = FrameLoadTypeReload;
1170 else if (lockBackForwardList)
1171 loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1173 loadType = FrameLoadTypeStandard;
1175 if (request.resourceRequest().httpMethod() == "POST")
1176 loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1178 loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1180 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1181 // load if frame names have changed.
1182 Frame* sourceFrame = formState ? formState->sourceFrame() : m_frame;
1183 Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName());
1184 if (targetFrame && targetFrame != sourceFrame) {
1185 if (Page* page = targetFrame->page())
1186 page->chrome()->focus();
1190 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1191 PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1193 if (m_inStopAllLoaders)
1196 RefPtr<FormState> formState = prpFormState;
1197 bool isFormSubmission = formState;
1199 ResourceRequest request(newURL);
1200 if (!referrer.isEmpty()) {
1201 request.setHTTPReferrer(referrer);
1202 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1203 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1205 addExtraFieldsToRequest(request, newLoadType, true);
1206 if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1207 request.setCachePolicy(ReloadIgnoringCacheData);
1209 ASSERT(newLoadType != FrameLoadTypeSame);
1211 // The search for a target frame is done earlier in the case of form submission.
1212 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1213 if (targetFrame && targetFrame != m_frame) {
1214 targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState.release());
1218 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1221 NavigationAction action(newURL, newLoadType, isFormSubmission, event);
1223 if (!targetFrame && !frameName.isEmpty()) {
1224 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1225 request, formState.release(), frameName, this);
1229 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1231 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1232 const String& httpMethod = request.httpMethod();
1234 // Make sure to do scroll to anchor processing even if the URL is
1235 // exactly the same so pages with '#' links and DHTML side effects
1237 if (shouldScrollToAnchor(isFormSubmission, httpMethod, newLoadType, newURL)) {
1238 oldDocumentLoader->setTriggeringAction(action);
1239 policyChecker()->stopCheck();
1240 policyChecker()->setLoadType(newLoadType);
1241 policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1242 callContinueFragmentScrollAfterNavigationPolicy, this);
1244 // must grab this now, since this load may stop the previous load and clear this flag
1245 bool isRedirect = m_quickRedirectComing;
1246 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1248 m_quickRedirectComing = false;
1249 if (m_provisionalDocumentLoader)
1250 m_provisionalDocumentLoader->setIsClientRedirect(true);
1251 } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1252 // Example of this case are sites that reload the same URL with a different cookie
1253 // driving the generated content, or a master frame with links that drive a target
1254 // frame, where the user has clicked on the same link repeatedly.
1255 m_loadType = FrameLoadTypeSame;
1259 void FrameLoader::load(const ResourceRequest& request, bool lockHistory)
1261 load(request, SubstituteData(), lockHistory);
1264 void FrameLoader::load(const ResourceRequest& request, const SubstituteData& substituteData, bool lockHistory)
1266 if (m_inStopAllLoaders)
1269 // FIXME: is this the right place to reset loadType? Perhaps this should be done after loading is finished or aborted.
1270 m_loadType = FrameLoadTypeStandard;
1271 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData);
1272 if (lockHistory && m_documentLoader)
1273 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1277 void FrameLoader::load(const ResourceRequest& request, const String& frameName, bool lockHistory)
1279 if (frameName.isEmpty()) {
1280 load(request, lockHistory);
1284 Frame* frame = findFrameForNavigation(frameName);
1286 frame->loader()->load(request, lockHistory);
1290 policyChecker()->checkNewWindowPolicy(NavigationAction(request.url(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request, 0, frameName, this);
1293 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1295 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1296 if (lockHistory && m_documentLoader)
1297 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1299 loader->setTriggeringAction(action);
1300 if (m_documentLoader)
1301 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1303 loadWithDocumentLoader(loader.get(), type, formState);
1306 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1308 ResourceRequest& r = newDocumentLoader->request();
1309 addExtraFieldsToMainResourceRequest(r);
1312 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1313 r.setCachePolicy(ReloadIgnoringCacheData);
1314 type = FrameLoadTypeSame;
1316 type = FrameLoadTypeStandard;
1318 if (m_documentLoader)
1319 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1321 // When we loading alternate content for an unreachable URL that we're
1322 // visiting in the history list, we treat it as a reload so the history list
1323 // is appropriately maintained.
1325 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1326 // shouldn't a more explicit type of reload be defined, that means roughly
1327 // "load without affecting history" ?
1328 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1329 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1330 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1331 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1332 history()->saveDocumentAndScrollState();
1334 ASSERT(type == FrameLoadTypeStandard);
1335 type = FrameLoadTypeReload;
1338 loadWithDocumentLoader(newDocumentLoader, type, 0);
1341 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1343 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1344 RefPtr<Frame> protect(m_frame);
1346 ASSERT(m_client->hasWebView());
1348 // Unfortunately the view must be non-nil, this is ultimately due
1349 // to parser requiring a FrameView. We should fix this dependency.
1351 ASSERT(m_frame->view());
1353 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1356 if (m_frame->document())
1357 m_previousUrl = m_frame->document()->url();
1359 policyChecker()->setLoadType(type);
1360 RefPtr<FormState> formState = prpFormState;
1361 bool isFormSubmission = formState;
1363 const KURL& newURL = loader->request().url();
1364 const String& httpMethod = loader->request().httpMethod();
1366 if (shouldScrollToAnchor(isFormSubmission, httpMethod, policyChecker()->loadType(), newURL)) {
1367 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1368 NavigationAction action(newURL, policyChecker()->loadType(), isFormSubmission);
1370 oldDocumentLoader->setTriggeringAction(action);
1371 policyChecker()->stopCheck();
1372 policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1373 callContinueFragmentScrollAfterNavigationPolicy, this);
1375 if (Frame* parent = m_frame->tree()->parent())
1376 loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
1378 policyChecker()->stopCheck();
1379 setPolicyDocumentLoader(loader);
1380 if (loader->triggeringAction().isEmpty())
1381 loader->setTriggeringAction(NavigationAction(newURL, policyChecker()->loadType(), isFormSubmission));
1383 if (Element* ownerElement = m_frame->ownerElement()) {
1384 // We skip dispatching the beforeload event if we've already
1385 // committed a real document load because the event would leak
1386 // subsequent activity by the frame which the parent frame isn't
1387 // supposed to learn. For example, if the child frame navigated to
1388 // a new URL, the parent frame shouldn't learn the URL.
1389 if (!m_stateMachine.committedFirstRealDocumentLoad()
1390 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1391 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1396 policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1397 callContinueLoadAfterNavigationPolicy, this);
1401 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1403 ASSERT(!url.isEmpty());
1407 frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Not allowed to load local resource: " + url, 0, String());
1410 const ResourceRequest& FrameLoader::initialRequest() const
1412 return activeDocumentLoader()->originalRequest();
1415 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1417 ResourceRequest request(url);
1419 unsigned long identifier;
1420 ResourceError error;
1421 requestFromDelegate(request, identifier, error);
1422 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1424 url = request.url();
1426 return error.isNull();
1429 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1431 KURL unreachableURL = docLoader->unreachableURL();
1433 if (unreachableURL.isEmpty())
1436 if (!isBackForwardLoadType(policyChecker()->loadType()))
1439 // We only treat unreachableURLs specially during the delegate callbacks
1440 // for provisional load errors and navigation policy decisions. The former
1441 // case handles well-formed URLs that can't be loaded, and the latter
1442 // case handles malformed URLs and unknown schemes. Loading alternate content
1443 // at other times behaves like a standard load.
1444 DocumentLoader* compareDocumentLoader = 0;
1445 if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1446 compareDocumentLoader = m_policyDocumentLoader.get();
1447 else if (m_delegateIsHandlingProvisionalLoadError)
1448 compareDocumentLoader = m_provisionalDocumentLoader.get();
1450 return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1453 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1455 if (!m_documentLoader)
1458 ResourceRequest request = m_documentLoader->request();
1459 KURL unreachableURL = m_documentLoader->unreachableURL();
1460 if (!unreachableURL.isEmpty())
1461 request.setURL(unreachableURL);
1463 request.setCachePolicy(ReturnCacheDataElseLoad);
1465 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1466 setPolicyDocumentLoader(loader.get());
1468 loader->setOverrideEncoding(encoding);
1470 loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1473 void FrameLoader::reload(bool endToEndReload)
1475 if (!m_documentLoader)
1478 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1479 // Reloading in this case will lose the current contents (see 4151001).
1480 if (m_documentLoader->request().url().isEmpty())
1483 ResourceRequest initialRequest = m_documentLoader->request();
1485 // Replace error-page URL with the URL we were trying to reach.
1486 KURL unreachableURL = m_documentLoader->unreachableURL();
1487 if (!unreachableURL.isEmpty())
1488 initialRequest.setURL(unreachableURL);
1490 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1491 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1492 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, SubstituteData());
1494 ResourceRequest& request = loader->request();
1496 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1497 request.setCachePolicy(ReloadIgnoringCacheData);
1499 // If we're about to re-post, set up action so the application can warn the user.
1500 if (request.httpMethod() == "POST")
1501 loader->setTriggeringAction(NavigationAction(request.url(), NavigationTypeFormResubmitted));
1503 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1505 loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1508 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
1510 // targetFrame can be NULL when we're trying to navigate a top-level frame
1511 // that has a NULL opener.
1515 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
1516 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
1517 Document* ancestorDocument = ancestorFrame->document();
1518 if (!ancestorDocument)
1521 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
1522 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
1525 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
1526 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
1533 bool FrameLoader::shouldAllowNavigation(Frame* targetFrame) const
1535 // The navigation change is safe if the active frame is:
1536 // - in the same security origin as the target or one of the target's
1539 // Or the target frame is:
1540 // - a top-level frame in the frame hierarchy and the active frame can
1541 // navigate the target frame's opener per above or it is the opener of
1542 // the target frame.
1547 // Performance optimization.
1548 if (m_frame == targetFrame)
1551 // Let a frame navigate the top-level window that contains it. This is
1552 // important to allow because it lets a site "frame-bust" (escape from a
1553 // frame created by another web site).
1554 if (!isDocumentSandboxed(m_frame, SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
1557 // A sandboxed frame can only navigate itself and its descendants.
1558 if (isDocumentSandboxed(m_frame, SandboxNavigation) && !targetFrame->tree()->isDescendantOf(m_frame))
1561 // Let a frame navigate its opener if the opener is a top-level window.
1562 if (!targetFrame->tree()->parent() && m_frame->loader()->opener() == targetFrame)
1565 Document* activeDocument = m_frame->document();
1566 ASSERT(activeDocument);
1567 const SecurityOrigin* activeSecurityOrigin = activeDocument->securityOrigin();
1569 // For top-level windows, check the opener.
1570 if (!targetFrame->tree()->parent() && canAccessAncestor(activeSecurityOrigin, targetFrame->loader()->opener()))
1573 // In general, check the frame's ancestors.
1574 if (canAccessAncestor(activeSecurityOrigin, targetFrame))
1577 Settings* settings = targetFrame->settings();
1578 if (settings && !settings->privateBrowsingEnabled()) {
1579 Document* targetDocument = targetFrame->document();
1580 // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
1581 String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
1582 targetDocument->url().string() + " from frame with URL " + activeDocument->url().string() + ".\n";
1584 // FIXME: should we print to the console of the activeFrame as well?
1585 targetFrame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1591 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1593 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1594 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1597 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1598 if (m_inStopAllLoaders)
1601 m_inStopAllLoaders = true;
1603 policyChecker()->stopCheck();
1605 // If no new load is in progress, we should clear the provisional item from history
1606 // before we call stopLoading.
1607 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1608 history()->setProvisionalItem(0);
1610 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1611 child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
1612 if (m_provisionalDocumentLoader)
1613 m_provisionalDocumentLoader->stopLoading();
1614 if (m_documentLoader)
1615 m_documentLoader->stopLoading();
1617 setProvisionalDocumentLoader(0);
1619 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
1620 if (m_documentLoader)
1621 m_documentLoader->clearArchiveResources();
1624 m_checkTimer.stop();
1626 m_inStopAllLoaders = false;
1629 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1633 if (deferCheckLoadComplete)
1634 scheduleCheckLoadComplete();
1635 else if (m_frame->page())
1636 checkLoadComplete();
1639 DocumentLoader* FrameLoader::activeDocumentLoader() const
1641 if (m_state == FrameStateProvisional)
1642 return m_provisionalDocumentLoader.get();
1643 return m_documentLoader.get();
1646 bool FrameLoader::isLoading() const
1648 DocumentLoader* docLoader = activeDocumentLoader();
1651 return docLoader->isLoadingMainResource() || docLoader->isLoadingSubresources() || docLoader->isLoadingPlugIns();
1654 bool FrameLoader::frameHasLoaded() const
1656 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1659 void FrameLoader::transferLoadingResourcesFromPage(Page* oldPage)
1661 ASSERT(oldPage != m_frame->page());
1663 activeDocumentLoader()->transferLoadingResourcesFromPage(oldPage);
1664 oldPage->progress()->progressCompleted(m_frame);
1665 if (m_frame->page())
1666 m_frame->page()->progress()->progressStarted(m_frame);
1670 void FrameLoader::dispatchTransferLoadingResourceFromPage(ResourceLoader* loader, const ResourceRequest& request, Page* oldPage)
1672 notifier()->dispatchTransferLoadingResourceFromPage(loader, request, oldPage);
1675 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1677 if (!loader && !m_documentLoader)
1680 ASSERT(loader != m_documentLoader);
1681 ASSERT(!loader || loader->frameLoader() == this);
1683 m_client->prepareForDataSourceReplacement();
1685 if (m_documentLoader)
1686 m_documentLoader->detachFromFrame();
1688 m_documentLoader = loader;
1690 // The following abomination is brought to you by the unload event.
1691 // The detachChildren() call above may trigger a child frame's unload event,
1692 // which could do something obnoxious like call document.write("") on
1693 // the main frame, which results in detaching children while detaching children.
1694 // This can cause the new m_documentLoader to be detached from its Frame*, but still
1695 // be alive. To make matters worse, DocumentLoaders with a null Frame* aren't supposed
1696 // to happen when they're still alive (and many places below us on the stack think the
1697 // DocumentLoader is still usable). Ergo, we reattach loader to its Frame, and pretend
1698 // like nothing ever happened.
1699 if (m_documentLoader && !m_documentLoader->frame()) {
1700 ASSERT(!m_documentLoader->isLoading());
1701 m_documentLoader->setFrame(m_frame);
1705 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1707 if (m_policyDocumentLoader == loader)
1712 loader->setFrame(m_frame);
1713 if (m_policyDocumentLoader
1714 && m_policyDocumentLoader != m_provisionalDocumentLoader
1715 && m_policyDocumentLoader != m_documentLoader)
1716 m_policyDocumentLoader->detachFromFrame();
1718 m_policyDocumentLoader = loader;
1721 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1723 ASSERT(!loader || !m_provisionalDocumentLoader);
1724 ASSERT(!loader || loader->frameLoader() == this);
1726 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1727 m_provisionalDocumentLoader->detachFromFrame();
1729 m_provisionalDocumentLoader = loader;
1732 double FrameLoader::timeOfLastCompletedLoad()
1734 return storedTimeOfLastCompletedLoad;
1737 void FrameLoader::setState(FrameState newState)
1741 if (newState == FrameStateProvisional)
1742 provisionalLoadStarted();
1743 else if (newState == FrameStateComplete) {
1744 frameLoadCompleted();
1745 storedTimeOfLastCompletedLoad = currentTime();
1746 if (m_documentLoader)
1747 m_documentLoader->stopRecordingResponses();
1751 void FrameLoader::clearProvisionalLoad()
1753 setProvisionalDocumentLoader(0);
1754 if (Page* page = m_frame->page())
1755 page->progress()->progressCompleted(m_frame);
1756 setState(FrameStateComplete);
1759 void FrameLoader::commitProvisionalLoad()
1761 RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1762 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1764 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1765 m_frame->document() ? m_frame->document()->url().string().utf8().data() : "",
1766 pdl ? pdl->url().string().utf8().data() : "<no provisional DocumentLoader>");
1768 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1769 // We are doing this here because we know for sure that a new page is about to be loaded.
1770 HistoryItem* item = history()->currentItem();
1771 if (!m_frame->tree()->parent() && PageCache::canCache(m_frame->page()) && !item->isInPageCache())
1772 pageCache()->add(item, m_frame->page());
1774 if (m_loadType != FrameLoadTypeReplace)
1775 closeOldDataSources();
1777 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1778 m_client->makeRepresentation(pdl.get());
1780 transitionToCommitted(cachedPage);
1783 // Check if the destination page is allowed to access the previous page's timing information.
1784 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1785 m_documentLoader->timing()->hasSameOriginAsPreviousDocument = securityOrigin->canRequest(m_previousUrl);
1788 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1789 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1790 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1791 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1792 if (m_sentRedirectNotification)
1793 clientRedirectCancelledOrFinished(false);
1795 if (cachedPage && cachedPage->document()) {
1796 prepareForCachedPageRestore();
1797 cachedPage->restore(m_frame->page());
1799 dispatchDidCommitLoad();
1801 // If we have a title let the WebView know about it.
1802 StringWithDirection title = m_documentLoader->title();
1803 if (!title.isNull())
1804 m_client->dispatchDidReceiveTitle(title);
1810 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1811 m_frame->document() ? m_frame->document()->url().string().utf8().data() : "");
1813 if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1814 history()->updateForClientRedirect();
1816 if (m_loadingFromCachedPage) {
1817 m_frame->document()->documentDidBecomeActive();
1819 // Force a layout to update view size and thereby update scrollbars.
1820 m_frame->view()->forceLayout();
1822 const ResponseVector& responses = m_documentLoader->responses();
1823 size_t count = responses.size();
1824 for (size_t i = 0; i < count; i++) {
1825 const ResourceResponse& response = responses[i];
1826 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1827 ResourceError error;
1828 unsigned long identifier;
1829 ResourceRequest request(response.url());
1830 requestFromDelegate(request, identifier, error);
1831 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1832 // However, with today's computers and networking speeds, this won't happen in practice.
1833 // Could be an issue with a giant local file.
1834 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1837 pageCache()->remove(history()->currentItem());
1839 m_documentLoader->setPrimaryLoadComplete(true);
1841 // FIXME: Why only this frame and not parent frames?
1842 checkLoadCompleteForThisFrame();
1846 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1848 ASSERT(m_client->hasWebView());
1849 ASSERT(m_state == FrameStateProvisional);
1851 if (m_state != FrameStateProvisional)
1854 if (m_frame->view())
1855 m_frame->view()->scrollAnimator()->cancelAnimations();
1857 m_client->setCopiesOnScroll();
1858 history()->updateForCommit();
1860 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1861 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1862 // or the two will stomp each other.
1863 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1864 if (m_documentLoader)
1866 if (pdl != m_provisionalDocumentLoader)
1869 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1870 if (m_documentLoader)
1871 m_documentLoader->stopLoadingSubresources();
1872 if (m_documentLoader)
1873 m_documentLoader->stopLoadingPlugIns();
1875 setDocumentLoader(m_provisionalDocumentLoader.get());
1876 setProvisionalDocumentLoader(0);
1877 setState(FrameStateCommittedPage);
1879 #if ENABLE(TOUCH_EVENTS)
1880 if (isLoadingMainFrame())
1881 m_frame->page()->chrome()->client()->needTouchEvents(false);
1884 // Handle adding the URL to the back/forward list.
1885 DocumentLoader* dl = m_documentLoader.get();
1887 switch (m_loadType) {
1888 case FrameLoadTypeForward:
1889 case FrameLoadTypeBack:
1890 case FrameLoadTypeIndexedBackForward:
1891 if (m_frame->page()) {
1892 // If the first load within a frame is a navigation within a back/forward list that was attached
1893 // without any of the items being loaded then we need to update the history in a similar manner as
1894 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1895 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1896 history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1898 history()->updateForBackForwardNavigation();
1900 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1901 if (history()->currentItem() && !cachedPage)
1902 m_pendingStateObject = history()->currentItem()->stateObject();
1904 // Create a document view for this document, or used the cached view.
1906 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1907 ASSERT(cachedDocumentLoader);
1908 cachedDocumentLoader->setFrame(m_frame);
1909 m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1912 m_client->transitionToCommittedForNewPage();
1916 case FrameLoadTypeReload:
1917 case FrameLoadTypeReloadFromOrigin:
1918 case FrameLoadTypeSame:
1919 case FrameLoadTypeReplace:
1920 history()->updateForReload();
1921 m_client->transitionToCommittedForNewPage();
1924 case FrameLoadTypeStandard:
1925 history()->updateForStandardLoad();
1926 if (m_frame->view())
1927 m_frame->view()->setScrollbarsSuppressed(true);
1928 m_client->transitionToCommittedForNewPage();
1931 case FrameLoadTypeRedirectWithLockedBackForwardList:
1932 history()->updateForRedirectWithLockedBackForwardList();
1933 m_client->transitionToCommittedForNewPage();
1936 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1937 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1939 ASSERT_NOT_REACHED();
1942 m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
1944 // Tell the client we've committed this URL.
1945 ASSERT(m_frame->view());
1947 if (m_stateMachine.creatingInitialEmptyDocument())
1950 if (!m_stateMachine.committedFirstRealDocumentLoad())
1951 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1953 if (!m_client->hasHTMLView())
1954 receivedFirstData();
1957 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1959 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1960 // the redirect succeeded. We should either rename this API, or add a new method, like
1961 // -webView:didFinishClientRedirectForFrame:
1962 m_client->dispatchDidCancelClientRedirect();
1964 if (!cancelWithLoadInProgress)
1965 m_quickRedirectComing = false;
1967 m_sentRedirectNotification = false;
1970 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
1972 m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
1974 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
1975 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
1976 m_sentRedirectNotification = true;
1978 // If a "quick" redirect comes in, we set a special mode so we treat the next
1979 // load as part of the original navigation. If we don't have a document loader, we have
1980 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
1981 // Loads triggered by JavaScript form submissions never count as quick redirects.
1982 m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
1985 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
1987 // This function implements the rule: "Don't reload if navigating by fragment within
1988 // the same URL, but do reload if going to a new URL or to the same URL with no
1989 // fragment identifier at all."
1990 if (!destinationURL.hasFragmentIdentifier())
1992 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
1995 void FrameLoader::closeOldDataSources()
1997 // FIXME: Is it important for this traversal to be postorder instead of preorder?
1998 // If so, add helpers for postorder traversal, and use them. If not, then lets not
1999 // use a recursive algorithm here.
2000 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
2001 child->loader()->closeOldDataSources();
2003 if (m_documentLoader)
2004 m_client->dispatchWillClose();
2006 m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2009 void FrameLoader::prepareForCachedPageRestore()
2011 ASSERT(!m_frame->tree()->parent());
2012 ASSERT(m_frame->page());
2013 ASSERT(m_frame->page()->mainFrame() == m_frame);
2015 m_frame->navigationScheduler()->cancel();
2017 // We still have to close the previous part page.
2020 // Delete old status bar messages (if it _was_ activated on last URL).
2021 if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
2022 if (DOMWindow* window = m_frame->existingDOMWindow()) {
2023 window->setStatus(String());
2024 window->setDefaultStatus(String());
2029 void FrameLoader::open(CachedFrameBase& cachedFrame)
2031 m_isComplete = false;
2033 // Don't re-emit the load event.
2034 m_didCallImplicitClose = true;
2036 KURL url = cachedFrame.url();
2038 // FIXME: I suspect this block of code doesn't do anything.
2039 if (url.protocolInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2042 m_hasReceivedFirstData = false;
2045 clear(true, true, cachedFrame.isMainFrame());
2047 Document* document = cachedFrame.document();
2049 document->setInPageCache(false);
2051 m_needsClear = true;
2052 m_isComplete = false;
2053 m_didCallImplicitClose = false;
2054 m_outgoingReferrer = url.string();
2056 FrameView* view = cachedFrame.view();
2058 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2060 view->setWasScrolledByUser(false);
2062 // Use the current ScrollView's frame rect.
2063 if (m_frame->view()) {
2064 IntRect rect = m_frame->view()->frameRect();
2065 view->setFrameRect(rect);
2066 view->setBoundsSize(rect.size());
2068 m_frame->setView(view);
2070 m_frame->setDocument(document);
2071 m_frame->setDOMWindow(cachedFrame.domWindow());
2072 m_frame->domWindow()->setURL(document->url());
2073 m_frame->domWindow()->setSecurityOrigin(document->securityOrigin());
2075 updateFirstPartyForCookies();
2077 cachedFrame.restore();
2080 void FrameLoader::finishedLoading()
2082 // Retain because the stop may release the last reference to it.
2083 RefPtr<Frame> protect(m_frame);
2085 RefPtr<DocumentLoader> dl = activeDocumentLoader();
2086 dl->finishedLoading();
2087 if (!dl->mainDocumentError().isNull() || !dl->frameLoader())
2089 dl->setPrimaryLoadComplete(true);
2090 m_client->dispatchDidLoadMainResource(dl.get());
2091 checkLoadComplete();
2094 bool FrameLoader::isHostedByObjectElement() const
2096 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2097 return owner && owner->hasTagName(objectTag);
2100 bool FrameLoader::isLoadingMainFrame() const
2102 Page* page = m_frame->page();
2103 return page && m_frame == page->mainFrame();
2106 void FrameLoader::finishedLoadingDocument(DocumentLoader* loader)
2108 if (m_stateMachine.creatingInitialEmptyDocument())
2111 #if !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
2112 m_client->finishedLoading(loader);
2114 // Give archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
2115 m_archive = ArchiveFactory::create(loader->response().url(), loader->mainResourceData().get(), loader->responseMIMEType());
2117 m_client->finishedLoading(loader);
2121 // FIXME: The remainder of this function should be moved to DocumentLoader.
2123 loader->addAllArchiveResources(m_archive.get());
2125 ArchiveResource* mainResource = m_archive->mainResource();
2126 loader->setParsedArchiveData(mainResource->data());
2128 loader->writer()->setMIMEType(mainResource->mimeType());
2133 ASSERT(m_frame->document());
2134 String userChosenEncoding = documentLoader()->overrideEncoding();
2135 bool encodingIsUserChosen = !userChosenEncoding.isNull();
2136 loader->writer()->setEncoding(encodingIsUserChosen ? userChosenEncoding : mainResource->textEncoding(), encodingIsUserChosen);
2137 loader->writer()->addData(mainResource->data()->data(), mainResource->data()->size());
2138 #endif // ENABLE(WEB_ARCHIVE)
2141 bool FrameLoader::isReplacing() const
2143 return m_loadType == FrameLoadTypeReplace;
2146 void FrameLoader::setReplacing()
2148 m_loadType = FrameLoadTypeReplace;
2151 bool FrameLoader::subframeIsLoading() const
2153 // It's most likely that the last added frame is the last to load so we walk backwards.
2154 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2155 FrameLoader* childLoader = child->loader();
2156 DocumentLoader* documentLoader = childLoader->documentLoader();
2157 if (documentLoader && documentLoader->isLoadingInAPISense())
2159 documentLoader = childLoader->provisionalDocumentLoader();
2160 if (documentLoader && documentLoader->isLoadingInAPISense())
2162 documentLoader = childLoader->policyDocumentLoader();
2169 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2171 m_client->willChangeTitle(loader);
2174 FrameLoadType FrameLoader::loadType() const
2179 CachePolicy FrameLoader::subresourceCachePolicy() const
2182 return CachePolicyVerify;
2184 if (m_loadType == FrameLoadTypeReloadFromOrigin)
2185 return CachePolicyReload;
2187 if (Frame* parentFrame = m_frame->tree()->parent()) {
2188 CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
2189 if (parentCachePolicy != CachePolicyVerify)
2190 return parentCachePolicy;
2193 if (m_loadType == FrameLoadTypeReload)
2194 return CachePolicyRevalidate;
2196 const ResourceRequest& request(documentLoader()->request());
2198 if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2199 return CachePolicyRevalidate;
2202 if (request.cachePolicy() == ReturnCacheDataElseLoad)
2203 return CachePolicyHistoryBuffer;
2205 return CachePolicyVerify;
2208 void FrameLoader::checkLoadCompleteForThisFrame()
2210 ASSERT(m_client->hasWebView());
2213 case FrameStateProvisional: {
2214 if (m_delegateIsHandlingProvisionalLoadError)
2217 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2221 // If we've received any errors we may be stuck in the provisional state and actually complete.
2222 const ResourceError& error = pdl->mainDocumentError();
2226 // Check all children first.
2227 RefPtr<HistoryItem> item;
2228 if (Page* page = m_frame->page())
2229 if (isBackForwardLoadType(loadType()))
2230 // Reset the back forward list to the last committed history item at the top level.
2231 item = page->mainFrame()->loader()->history()->currentItem();
2233 // Only reset if we aren't already going to a new provisional item.
2234 bool shouldReset = !history()->provisionalItem();
2235 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2236 m_delegateIsHandlingProvisionalLoadError = true;
2237 m_client->dispatchDidFailProvisionalLoad(error);
2238 m_delegateIsHandlingProvisionalLoadError = false;
2240 ASSERT(!pdl->isLoading());
2241 ASSERT(!pdl->isLoadingMainResource());
2242 ASSERT(!pdl->isLoadingSubresources());
2243 ASSERT(!pdl->isLoadingPlugIns());
2245 // If we're in the middle of loading multipart data, we need to restore the document loader.
2246 if (isReplacing() && !m_documentLoader.get())
2247 setDocumentLoader(m_provisionalDocumentLoader.get());
2249 // Finish resetting the load state, but only if another load hasn't been started by the
2250 // delegate callback.
2251 if (pdl == m_provisionalDocumentLoader)
2252 clearProvisionalLoad();
2253 else if (activeDocumentLoader()) {
2254 KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2255 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2256 shouldReset = false;
2259 if (shouldReset && item)
2260 if (Page* page = m_frame->page()) {
2261 page->backForward()->setCurrentItem(item.get());
2262 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2267 case FrameStateCommittedPage: {
2268 DocumentLoader* dl = m_documentLoader.get();
2269 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2272 setState(FrameStateComplete);
2274 // FIXME: Is this subsequent work important if we already navigated away?
2275 // Maybe there are bugs because of that, or extra work we can skip because
2276 // the new page is ready.
2278 m_client->forceLayoutForNonHTML();
2280 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2281 if (m_frame->page()) {
2282 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2283 history()->restoreScrollPositionAndViewState();
2286 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2289 if (Page* page = m_frame->page())
2290 page->progress()->progressCompleted(m_frame);
2292 const ResourceError& error = dl->mainDocumentError();
2293 if (!error.isNull())
2294 m_client->dispatchDidFailLoad(error);
2296 m_client->dispatchDidFinishLoad();
2301 case FrameStateComplete:
2302 frameLoadCompleted();
2306 ASSERT_NOT_REACHED();
2309 void FrameLoader::continueLoadAfterWillSubmitForm()
2311 if (!m_provisionalDocumentLoader)
2314 // DocumentLoader calls back to our prepareForLoadStart
2315 m_provisionalDocumentLoader->prepareForLoadStart();
2317 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2318 // so we need to null check it again.
2319 if (!m_provisionalDocumentLoader)
2322 DocumentLoader* activeDocLoader = activeDocumentLoader();
2323 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2326 m_loadingFromCachedPage = false;
2328 unsigned long identifier = 0;
2330 if (Page* page = m_frame->page()) {
2331 identifier = page->progress()->createUniqueIdentifier();
2332 notifier()->assignIdentifierToInitialRequest(identifier, m_provisionalDocumentLoader.get(), m_provisionalDocumentLoader->originalRequest());
2335 ASSERT(!m_provisionalDocumentLoader->timing()->navigationStart);
2336 m_provisionalDocumentLoader->timing()->navigationStart = currentTime();
2338 if (!m_provisionalDocumentLoader->startLoadingMainResource(identifier))
2339 m_provisionalDocumentLoader->updateLoading();
2342 void FrameLoader::didFirstLayout()
2344 if (m_frame->page() && isBackForwardLoadType(m_loadType))
2345 history()->restoreScrollPositionAndViewState();
2347 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2348 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2350 m_client->dispatchDidFirstLayout();
2353 void FrameLoader::didFirstVisuallyNonEmptyLayout()
2355 m_client->dispatchDidFirstVisuallyNonEmptyLayout();
2358 void FrameLoader::frameLoadCompleted()
2360 // Note: Can be called multiple times.
2362 m_client->frameLoadCompleted();
2364 history()->updateForFrameLoadCompleted();
2366 // After a canceled provisional load, firstLayoutDone is false.
2367 // Reset it to true if we're displaying a page.
2368 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2369 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2372 void FrameLoader::detachChildren()
2374 typedef Vector<RefPtr<Frame> > FrameVector;
2375 FrameVector childrenToDetach;
2376 childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2377 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2378 childrenToDetach.append(child);
2379 FrameVector::iterator end = childrenToDetach.end();
2380 for (FrameVector::iterator it = childrenToDetach.begin(); it != end; it++)
2381 (*it)->loader()->detachFromParent();
2384 void FrameLoader::closeAndRemoveChild(Frame* child)
2386 child->tree()->detachFromParent();
2389 if (child->ownerElement() && child->page())
2390 child->page()->decrementFrameCount();
2391 // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2392 child->pageDestroyed();
2394 m_frame->tree()->removeChild(child);
2397 // Called every time a resource is completely loaded or an error is received.
2398 void FrameLoader::checkLoadComplete()
2400 ASSERT(m_client->hasWebView());
2402 m_shouldCallCheckLoadComplete = false;
2404 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2405 // is currently needed in order to null out the previous history item for all frames.
2406 if (Page* page = m_frame->page()) {
2407 Vector<RefPtr<Frame>, 10> frames;
2408 for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2409 frames.append(frame);
2410 // To process children before their parents, iterate the vector backwards.
2411 for (size_t i = frames.size(); i; --i)
2412 frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
2416 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2419 return m_frame->document()->cachedResourceLoader()->requestCount();
2422 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2423 count += frame->document()->cachedResourceLoader()->requestCount();
2427 String FrameLoader::userAgent(const KURL& url) const
2429 String userAgent = m_client->userAgent(url);
2430 InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2434 void FrameLoader::handledOnloadEvents()
2436 m_client->dispatchDidHandleOnloadEvents();
2438 if (documentLoader())
2439 documentLoader()->handledOnloadEvents();
2442 void FrameLoader::frameDetached()
2445 m_frame->document()->stopActiveDOMObjects();
2449 void FrameLoader::detachFromParent()
2451 RefPtr<Frame> protect(m_frame);
2454 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2456 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2457 // will trigger the unload event handlers of any child frames, and those event
2458 // handlers might start a new subresource load in this frame.
2461 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2463 detachViewsAndDocumentLoader();
2465 if (Frame* parent = m_frame->tree()->parent()) {
2466 parent->loader()->closeAndRemoveChild(m_frame);
2467 parent->loader()->scheduleCheckCompleted();
2469 m_frame->setView(0);
2470 // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2471 m_frame->pageDestroyed();
2475 void FrameLoader::detachViewsAndDocumentLoader()
2477 m_client->detachedFromParent2();
2478 setDocumentLoader(0);
2479 m_client->detachedFromParent3();
2482 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2484 addExtraFieldsToRequest(request, m_loadType, false);
2487 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2489 addExtraFieldsToRequest(request, m_loadType, true);
2492 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2494 // Don't set the cookie policy URL if it's already been set.
2495 // But make sure to set it on all requests, as it has significance beyond the cookie policy for all protocols (<rdar://problem/6616664>).
2496 if (request.firstPartyForCookies().isEmpty()) {
2497 if (mainResource && isLoadingMainFrame())
2498 request.setFirstPartyForCookies(request.url());
2499 else if (Document* document = m_frame->document())
2500 request.setFirstPartyForCookies(document->firstPartyForCookies());
2503 // The remaining modifications are only necessary for HTTP and HTTPS.
2504 if (!request.url().isEmpty() && !request.url().protocolInHTTPFamily())
2507 applyUserAgent(request);
2509 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2510 // original request cache policy for two reasons:
2511 // 1. For POST requests, we mutate the cache policy for the main resource,
2512 // but we do not want this to apply to subresources
2513 // 2. Delegates that modify the cache policy using willSendRequest: should
2514 // not affect any other resources. Such changes need to be done
2516 if (!mainResource) {
2517 if (request.isConditional())
2518 request.setCachePolicy(ReloadIgnoringCacheData);
2519 else if (documentLoader()->isLoadingInAPISense())
2520 request.setCachePolicy(documentLoader()->originalRequest().cachePolicy());
2522 request.setCachePolicy(UseProtocolCachePolicy);
2523 } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2524 request.setCachePolicy(ReloadIgnoringCacheData);
2525 else if (isBackForwardLoadType(loadType) && m_stateMachine.committedFirstRealDocumentLoad())
2526 request.setCachePolicy(ReturnCacheDataElseLoad);
2528 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2529 if (loadType == FrameLoadTypeReload)
2530 request.setHTTPHeaderField("Cache-Control", "max-age=0");
2531 else if (loadType == FrameLoadTypeReloadFromOrigin) {
2532 request.setHTTPHeaderField("Cache-Control", "no-cache");
2533 request.setHTTPHeaderField("Pragma", "no-cache");
2538 request.setHTTPAccept(defaultAcceptHeader);
2540 // Make sure we send the Origin header.
2541 addHTTPOriginIfNeeded(request, String());
2543 #if PLATFORM(MAC) || PLATFORM(WIN)
2544 // The Apple Mac and Windows ports have decided not to behave like other
2545 // browsers and instead use a quirky fallback array.
2546 // FIXME: We should remove this code once CFNetwork implements RFC 6266.
2547 Settings* settings = m_frame->settings();
2548 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", activeDocumentLoader()->writer()->deprecatedFrameEncoding(), settings ? settings->defaultTextEncodingName() : String());
2552 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2554 if (!request.httpOrigin().isEmpty())
2555 return; // Request already has an Origin header.
2557 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2558 // For example, if an intranet page has a hyperlink to an external web
2559 // site, we don't want to include the Origin of the request because it
2560 // will leak the internal host name. Similar privacy concerns have lead
2561 // to the widespread suppression of the Referer header at the network
2563 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2566 // For non-GET and non-HEAD methods, always send an Origin header so the
2567 // server knows we support this feature.
2569 if (origin.isEmpty()) {
2570 // If we don't know what origin header to attach, we attach the value
2571 // for an empty origin.
2572 request.setHTTPOrigin(SecurityOrigin::createEmpty()->toString());
2576 request.setHTTPOrigin(origin);
2579 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2581 RefPtr<FormState> formState = prpFormState;
2583 // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a
2584 // bunch of parameters that would come in here and then be built back up to a ResourceRequest. In case
2585 // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2586 // from scratch as it did all along.
2587 const KURL& url = inRequest.url();
2588 RefPtr<FormData> formData = inRequest.httpBody();
2589 const String& contentType = inRequest.httpContentType();
2590 String origin = inRequest.httpOrigin();
2592 ResourceRequest workingResourceRequest(url);
2594 if (!referrer.isEmpty())
2595 workingResourceRequest.setHTTPReferrer(referrer);
2596 workingResourceRequest.setHTTPOrigin(origin);
2597 workingResourceRequest.setHTTPMethod("POST");
2598 workingResourceRequest.setHTTPBody(formData);
2599 workingResourceRequest.setHTTPContentType(contentType);
2600 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2602 NavigationAction action(url, loadType, true, event);
2604 if (!frameName.isEmpty()) {
2605 // The search for a target frame is done earlier in the case of form submission.
2606 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2607 targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2609 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2611 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2614 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2616 String referrer = m_outgoingReferrer;
2617 if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
2618 referrer = String();
2620 ResourceRequest initialRequest = request;
2621 initialRequest.setTimeoutInterval(10);
2623 if (!referrer.isEmpty())
2624 initialRequest.setHTTPReferrer(referrer);
2625 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2627 if (Page* page = m_frame->page())
2628 initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url());
2630 addExtraFieldsToSubresourceRequest(initialRequest);
2632 unsigned long identifier = 0;
2633 ResourceRequest newRequest(initialRequest);
2634 requestFromDelegate(newRequest, identifier, error);
2636 if (error.isNull()) {
2637 ASSERT(!newRequest.isNull());
2639 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
2640 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2642 ResourceHandle::loadResourceSynchronously(networkingContext(), newRequest, storedCredentials, error, response, data);
2643 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
2644 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2648 int encodedDataLength = response.resourceLoadInfo() ? static_cast<int>(response.resourceLoadInfo()->encodedDataLength) : -1;
2649 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, data.data(), data.size(), encodedDataLength, error);
2653 const ResourceRequest& FrameLoader::originalRequest() const
2655 return activeDocumentLoader()->originalRequestCopy();
2658 void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isComplete)
2660 // Retain because the stop may release the last reference to it.
2661 RefPtr<Frame> protect(m_frame);
2663 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2666 // FIXME: Don't want to do this if an entirely new load is going, so should check
2667 // that both data sources on the frame are either this or nil.
2669 if (m_client->shouldFallBack(error))
2670 handleFallbackContent();
2673 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2674 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2675 m_submittedFormURL = KURL();
2677 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2678 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2679 // so that the existing view (that wenever got far enough to replace) can continue being used.
2680 history()->invalidateCurrentItemCachedPage();
2682 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2683 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2684 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2685 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2687 if (m_sentRedirectNotification)
2688 clientRedirectCancelledOrFinished(false);
2691 loader->mainReceivedError(error, isComplete);
2694 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2695 const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2697 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2698 loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2701 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2703 m_quickRedirectComing = false;
2705 if (!shouldContinue)
2708 bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;
2709 loadInSameDocument(request.url(), 0, !isRedirect);
2712 bool FrameLoader::shouldScrollToAnchor(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2714 // Should we do anchor navigation within the existing content?
2716 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2717 // currently displaying a frameset, or if the URL does not have a fragment.
2718 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2720 // FIXME: What about load types other than Standard and Reload?
2722 return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2723 && loadType != FrameLoadTypeReload
2724 && loadType != FrameLoadTypeReloadFromOrigin
2725 && loadType != FrameLoadTypeSame
2726 && !shouldReload(m_frame->document()->url(), url)
2727 // We don't want to just scroll if a link from within a
2728 // frameset is trying to reload the frameset into _top.
2729 && !m_frame->document()->isFrameSet();
2732 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2733 const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2735 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2736 loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2739 bool FrameLoader::shouldClose()
2741 Page* page = m_frame->page();
2742 Chrome* chrome = page ? page->chrome() : 0;
2743 if (!chrome || !chrome->canRunBeforeUnloadConfirmPanel())
2746 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2747 Vector<RefPtr<Frame> > targetFrames;
2748 targetFrames.append(m_frame);
2749 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2750 targetFrames.append(child);
2752 bool shouldClose = false;
2754 NavigationDisablerForBeforeUnload navigationDisabler;
2757 for (i = 0; i < targetFrames.size(); i++) {
2758 if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2760 if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(chrome))
2764 if (i == targetFrames.size())
2769 m_submittedFormURL = KURL();
2774 bool FrameLoader::fireBeforeUnloadEvent(Chrome* chrome)
2776 DOMWindow* domWindow = m_frame->existingDOMWindow();
2780 RefPtr<Document> document = m_frame->document();
2781 if (!document->body())
2784 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2785 m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2786 domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2787 m_pageDismissalEventBeingDispatched = NoDismissal;
2789 if (!beforeUnloadEvent->defaultPrevented())
2790 document->defaultEventHandler(beforeUnloadEvent.get());
2791 if (beforeUnloadEvent->result().isNull())
2794 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2795 return chrome->runBeforeUnloadConfirmPanel(text, m_frame);
2798 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2800 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2801 // nil policyDataSource because loading the alternate page will have passed
2802 // through this method already, nested; otherwise, policyDataSource should still be set.
2803 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2805 bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2807 // Two reasons we can't continue:
2808 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
2809 // is the user responding Cancel to the form repost nag sheet.
2810 // 2) User responded Cancel to an alert popped up by the before unload event handler.
2811 bool canContinue = shouldContinue && shouldClose();
2814 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
2815 // need to report that the client redirect was cancelled.
2816 if (m_quickRedirectComing)
2817 clientRedirectCancelledOrFinished(false);
2819 setPolicyDocumentLoader(0);
2821 // If the navigation request came from the back/forward menu, and we punt on it, we have the
2822 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
2823 // we only do this when punting a navigation for the target frame or top-level frame.
2824 if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2825 if (Page* page = m_frame->page()) {
2826 Frame* mainFrame = page->mainFrame();
2827 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem()) {
2828 page->backForward()->setCurrentItem(resetItem);
2829 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2836 FrameLoadType type = policyChecker()->loadType();
2837 // A new navigation is in progress, so don't clear the history's provisional item.
2838 stopAllLoaders(ShouldNotClearProvisionalItem);
2840 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2841 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
2842 if (!m_frame->page())
2845 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2846 if (Page* page = m_frame->page()) {
2847 if (page->mainFrame() == m_frame)
2848 m_frame->page()->inspectorController()->resume();
2852 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2854 setState(FrameStateProvisional);
2856 setPolicyDocumentLoader(0);
2858 if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
2859 loadProvisionalItemFromCachedPage();
2864 m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
2866 continueLoadAfterWillSubmitForm();
2869 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
2870 const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2872 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2873 loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
2876 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
2877 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2879 if (!shouldContinue)
2882 RefPtr<Frame> frame = m_frame;
2883 RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
2887 if (frameName != "_blank")
2888 mainFrame->tree()->setName(frameName);
2890 mainFrame->page()->setOpenedByDOM();
2891 mainFrame->loader()->m_client->dispatchShow();
2892 if (!m_suppressOpenerInNewFrame)
2893 mainFrame->loader()->setOpener(frame.get());
2894 mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(), false, FrameLoadTypeStandard, formState);
2897 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
2899 ASSERT(!request.isNull());
2902 if (Page* page = m_frame->page()) {
2903 identifier = page->progress()->createUniqueIdentifier();
2904 notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
2907 ResourceRequest newRequest(request);
2908 notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
2910 if (newRequest.isNull())
2911 error = cancelledError(request);
2913 error = ResourceError();
2915 request = newRequest;
2918 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource)
2920 Page* page = m_frame->page();
2924 if (!resource->sendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
2927 if (!page->areMemoryCacheClientCallsEnabled()) {
2928 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2929 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->url());
2930 m_documentLoader->didTellClientAboutLoad(resource->url());
2934 ResourceRequest request(resource->url());
2935 if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize())) {
2936 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2937 m_documentLoader->didTellClientAboutLoad(resource->url());
2941 unsigned long identifier;
2942 ResourceError error;
2943 requestFromDelegate(request, identifier, error);
2944 InspectorInstrumentation::markResourceAsCached(page, identifier);
2945 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, resource->response(), 0, resource->encodedSize(), 0, error);
2948 void FrameLoader::applyUserAgent(ResourceRequest& request)
2950 String userAgent = this->userAgent(request.url());
2951 ASSERT(!userAgent.isNull());
2952 request.setHTTPUserAgent(userAgent);
2955 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url)
2957 Frame* topFrame = m_frame->tree()->top();
2958 if (m_frame == topFrame)
2961 if (equalIgnoringCase(content, "deny"))
2964 if (equalIgnoringCase(content, "sameorigin")) {
2965 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
2966 if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
2973 void FrameLoader::loadProvisionalItemFromCachedPage()
2975 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
2976 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().string().utf8().data());
2978 provisionalLoader->prepareForLoadStart();
2980 m_loadingFromCachedPage = true;
2982 // Should have timing data from previous time(s) the page was shown.
2983 ASSERT(provisionalLoader->timing()->navigationStart);
2984 provisionalLoader->resetTiming();
2985 provisionalLoader->timing()->navigationStart = currentTime();
2987 provisionalLoader->setCommitted(true);
2988 commitProvisionalLoad();
2991 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
2993 if (!history()->currentItem())
2995 return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
2998 void FrameLoader::checkDidPerformFirstNavigation()
3000 Page* page = m_frame->page();
3004 if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3005 m_didPerformFirstNavigation = true;
3006 m_client->didPerformFirstNavigation();
3010 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name)
3012 Frame* frame = m_frame->tree()->find(name);
3013 if (!shouldAllowNavigation(frame))
3018 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3020 ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3022 // Save user view state to the current history item here since we don't do a normal load.
3023 // FIXME: Does form state need to be saved here too?
3024 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3025 if (FrameView* view = m_frame->view())
3026 view->setWasScrolledByUser(false);
3028 history()->setCurrentItem(item);
3030 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3031 loadInSameDocument(item->url(), item->stateObject(), false);
3033 // Restore user view state from the current history item here since we don't do a normal load.
3034 history()->restoreScrollPositionAndViewState();
3037 // FIXME: This function should really be split into a couple pieces, some of
3038 // which should be methods of HistoryController and some of which should be
3039 // methods of FrameLoader.
3040 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType)
3042 // Remember this item so we can traverse any child items as child frames load
3043 history()->setProvisionalItem(item);
3045 if (CachedPage* cachedPage = pageCache()->get(item)) {
3046 loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
3050 KURL itemURL = item->url();
3051 KURL itemOriginalURL = item->originalURL();
3053 if (documentLoader())
3054 currentURL = documentLoader()->url();
3055 RefPtr<FormData> formData = item->formData();
3057 bool addedExtraFields = false;
3058 ResourceRequest request(itemURL);
3060 if (!item->referrer().isNull())
3061 request.setHTTPReferrer(item->referrer());
3063 // If this was a repost that failed the page cache, we might try to repost the form.
3064 NavigationAction action;
3066 formData->generateFiles(m_frame->document());
3068 request.setHTTPMethod("POST");
3069 request.setHTTPBody(formData);
3070 request.setHTTPContentType(item->formContentType());
3071 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3072 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3074 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3075 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3076 addExtraFieldsToRequest(request, m_loadType, true);
3077 addedExtraFields = true;
3079 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3080 // We want to know this before talking to the policy delegate, since it affects whether
3081 // we show the DoYouReallyWantToRepost nag.
3083 // This trick has a small bug (3123893) where we might find a cache hit, but then
3084 // have the item vanish when we try to use it in the ensuing nav. This should be
3085 // extremely rare, but in that case the user will get an error on the navigation.
3087 if (ResourceHandle::willLoadFromCache(request, m_frame))
3088 action = NavigationAction(itemURL, loadType, false);
3090 request.setCachePolicy(ReloadIgnoringCacheData);
3091 action = NavigationAction(itemURL, NavigationTypeFormResubmitted);
3095 case FrameLoadTypeReload:
3096 case FrameLoadTypeReloadFromOrigin:
3097 request.setCachePolicy(ReloadIgnoringCacheData);
3099 case FrameLoadTypeBack:
3100 case FrameLoadTypeForward:
3101 case FrameLoadTypeIndexedBackForward:
3102 // If the first load within a frame is a navigation within a back/forward list that was attached
3103 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3104 if (m_stateMachine.committedFirstRealDocumentLoad() && !itemURL.protocolIs("https"))
3105 request.setCachePolicy(ReturnCacheDataElseLoad);
3107 case FrameLoadTypeStandard:
3108 case FrameLoadTypeRedirectWithLockedBackForwardList:
3110 case FrameLoadTypeSame:
3112 ASSERT_NOT_REACHED();
3115 action = NavigationAction(itemOriginalURL, loadType, false);
3118 if (!addedExtraFields)
3119 addExtraFieldsToRequest(request, m_loadType, true);
3121 loadWithNavigationAction(request, action, false, loadType, 0);
3124 // Loads content into this frame, as specified by history item
3125 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3127 HistoryItem* currentItem = history()->currentItem();
3128 bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3130 if (sameDocumentNavigation)
3131 loadSameDocumentItem(item);
3133 loadDifferentDocumentItem(item, loadType);
3136 void FrameLoader::mainReceivedCompleteError(DocumentLoader* loader, const ResourceError&)
3138 loader->setPrimaryLoadComplete(true);
3139 m_client->dispatchDidLoadMainResource(activeDocumentLoader());
3141 if (m_frame->page())
3142 checkLoadComplete();
3145 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3147 ResourceError error = m_client->cancelledError(request);
3148 error.setIsCancellation(true);
3152 void FrameLoader::setTitle(const StringWithDirection& title)
3154 documentLoader()->setTitle(title);
3157 String FrameLoader::referrer() const
3159 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3162 void FrameLoader::dispatchDocumentElementAvailable()
3164 m_frame->injectUserScripts(InjectAtDocumentStart);
3165 m_client->documentElementAvailable();
3168 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3170 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3173 Vector<DOMWrapperWorld*> worlds;
3174 ScriptController::getAllWorlds(worlds);
3175 for (size_t i = 0; i < worlds.size(); ++i)
3176 dispatchDidClearWindowObjectInWorld(worlds[i]);
3179 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3181 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3184 m_client->dispatchDidClearWindowObjectInWorld(world);
3186 #if ENABLE(INSPECTOR)
3187 if (Page* page = m_frame->page())
3188 page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3191 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3194 void FrameLoader::updateSandboxFlags()
3196 SandboxFlags flags = m_forcedSandboxFlags;
3197 if (Frame* parentFrame = m_frame->tree()->parent())
3198 flags |= parentFrame->loader()->sandboxFlags();
3199 if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3200 flags |= ownerElement->sandboxFlags();
3202 if (m_sandboxFlags == flags)
3205 m_sandboxFlags = flags;
3207 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
3208 child->loader()->updateSandboxFlags();
3211 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3213 m_client->didChangeTitle(loader);
3215 if (loader == m_documentLoader) {
3216 // Must update the entries in the back-forward list too.
3217 history()->setCurrentItemTitle(loader->title());
3218 // This must go through the WebFrame because it has the right notion of the current b/f item.
3219 m_client->setTitle(loader->title(), loader->urlForHistory());
3220 m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3221 m_client->dispatchDidReceiveTitle(loader->title());
3225 void FrameLoader::didChangeIcons(DocumentLoader* loader, IconType type)
3227 if (loader == m_documentLoader)
3228 m_client->dispatchDidChangeIcons(type);
3231 void FrameLoader::dispatchDidCommitLoad()
3233 if (m_stateMachine.creatingInitialEmptyDocument())
3236 m_client->dispatchDidCommitLoad();
3238 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3241 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3243 ASSERT(m_frame->page());
3244 ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3246 if (!m_documentLoader)
3249 Vector<String> pastLoads;
3250 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3252 size_t size = pastLoads.size();
3253 for (size_t i = 0; i < size; ++i) {
3254 CachedResource* resource = memoryCache()->resourceForURL(KURL(ParsedURLString, pastLoads[i]));
3256 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3257 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3258 // Consider if there's some efficient way of remembering enough to deliver this client call.
3259 // We have the URL, but not the rest of the response or the length.
3263 ResourceRequest request(resource->url());
3264 m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3268 NetworkingContext* FrameLoader::networkingContext() const
3270 return m_networkingContext.get();
3273 bool FrameLoaderClient::hasHTMLView() const
3278 Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3280 ASSERT(!features.dialog || request.frameName().isEmpty());
3282 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3283 Frame* frame = lookupFrame->tree()->find(request.frameName());
3284 if (frame && openerFrame->loader()->shouldAllowNavigation(frame)) {
3285 if (Page* page = frame->page())
3286 page->chrome()->focus();
3292 // Sandboxed frames cannot open new auxiliary browsing contexts.
3293 if (isDocumentSandboxed(openerFrame, SandboxNavigation))
3296 // FIXME: Setting the referrer should be the caller's responsibility.
3297 FrameLoadRequest requestWithReferrer = request;
3298 requestWithReferrer.resourceRequest().setHTTPReferrer(openerFrame->loader()->outgoingReferrer());
3299 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
3301 Page* oldPage = openerFrame->page();
3305 NavigationAction action;
3306 Page* page = oldPage->chrome()->createWindow(openerFrame, requestWithReferrer, features, action);
3310 Frame* frame = page->mainFrame();
3311 if (request.frameName() != "_blank")
3312 frame->tree()->setName(request.frameName());
3314 page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3315 page->chrome()->setStatusbarVisible(features.statusBarVisible);
3316 page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
3317 page->chrome()->setMenubarVisible(features.menuBarVisible);
3318 page->chrome()->setResizable(features.resizable);
3320 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3321 // specify the size of the page. We can only resize the window, so
3322 // adjust for the difference between the window size and the page size.
3324 FloatRect windowRect = page->chrome()->windowRect();
3325 FloatSize pageSize = page->chrome()->pageRect().size();
3327 windowRect.setX(features.x);
3329 windowRect.setY(features.y);
3330 if (features.widthSet)
3331 windowRect.setWidth(features.width + (windowRect.width() - pageSize.width()));
3332 if (features.heightSet)
3333 windowRect.setHeight(features.height + (windowRect.height() - pageSize.height()));
3334 page->chrome()->setWindowRect(windowRect);
3336 page->chrome()->show();
3342 } // namespace WebCore