2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
6 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
7 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
8 * Copyright (C) 2011 Google Inc. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
20 * its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
27 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "FrameLoader.h"
38 #include "ApplicationCacheHost.h"
39 #include "BackForwardController.h"
40 #include "BeforeUnloadEvent.h"
41 #include "MemoryCache.h"
42 #include "CachedPage.h"
43 #include "CachedResourceLoader.h"
45 #include "ChromeClient.h"
47 #include "ContentSecurityPolicy.h"
48 #include "DOMImplementation.h"
49 #include "DOMWindow.h"
51 #include "DocumentLoadTiming.h"
52 #include "DocumentLoader.h"
54 #include "EditorClient.h"
57 #include "EventNames.h"
58 #include "FloatRect.h"
59 #include "FormState.h"
60 #include "FormSubmission.h"
62 #include "FrameLoadRequest.h"
63 #include "FrameLoaderClient.h"
64 #include "FrameNetworkingContext.h"
65 #include "FrameTree.h"
66 #include "FrameView.h"
67 #include "HTMLAnchorElement.h"
68 #include "HTMLFormElement.h"
69 #include "HTMLNames.h"
70 #include "HTMLObjectElement.h"
71 #include "HTTPParsers.h"
72 #include "HistoryItem.h"
73 #include "InspectorController.h"
74 #include "InspectorInstrumentation.h"
76 #include "MIMETypeRegistry.h"
77 #include "MainResourceLoader.h"
79 #include "PageCache.h"
80 #include "PageGroup.h"
81 #include "PageTransitionEvent.h"
82 #include "PluginData.h"
83 #include "PluginDatabase.h"
84 #include "PluginDocument.h"
85 #include "ProgressTracker.h"
86 #include "ResourceHandle.h"
87 #include "ResourceRequest.h"
88 #include "SchemeRegistry.h"
89 #include "ScrollAnimator.h"
90 #include "ScriptController.h"
91 #include "ScriptSourceCode.h"
92 #include "SecurityOrigin.h"
93 #include "SecurityPolicy.h"
94 #include "SegmentedString.h"
95 #include "SerializedScriptValue.h"
97 #include "TextResourceDecoder.h"
98 #include "WindowFeatures.h"
99 #include "XMLDocumentParser.h"
100 #include <wtf/CurrentTime.h>
101 #include <wtf/StdLibExtras.h>
102 #include <wtf/text/CString.h>
103 #include <wtf/text/WTFString.h>
105 #if ENABLE(INPUT_COLOR)
106 #include "ColorChooser.h"
107 #include "ColorInputType.h"
110 #if ENABLE(SHARED_WORKERS)
111 #include "SharedWorkerRepository.h"
115 #include "SVGDocument.h"
116 #include "SVGLocatable.h"
117 #include "SVGNames.h"
118 #include "SVGPreserveAspectRatio.h"
119 #include "SVGSVGElement.h"
120 #include "SVGViewElement.h"
121 #include "SVGViewSpec.h"
124 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
126 #include "ArchiveFactory.h"
129 #if ENABLE(TIZEN_DOWNLOAD)
130 #include "CookieJar.h"
135 using namespace HTMLNames;
138 using namespace SVGNames;
141 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
143 static double storedTimeOfLastCompletedLoad;
145 bool isBackForwardLoadType(FrameLoadType type)
148 case FrameLoadTypeStandard:
149 case FrameLoadTypeReload:
150 case FrameLoadTypeReloadFromOrigin:
151 case FrameLoadTypeSame:
152 case FrameLoadTypeRedirectWithLockedBackForwardList:
153 case FrameLoadTypeReplace:
154 #if ENABLE(TIZEN_DOWNLOAD)
155 case FrameLoadTypeDownload:
158 case FrameLoadTypeBack:
159 case FrameLoadTypeForward:
160 case FrameLoadTypeIndexedBackForward:
163 ASSERT_NOT_REACHED();
167 // This is not in the FrameLoader class to emphasize that it does not depend on
168 // private FrameLoader data, and to avoid increasing the number of public functions
169 // with access to private data. Since only this .cpp file needs it, making it
170 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
173 static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
175 return frame->document() && frame->document()->isSandboxed(mask);
178 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
181 , m_policyChecker(frame)
184 , m_subframeLoader(frame)
186 , m_state(FrameStateCommittedPage)
187 , m_loadType(FrameLoadTypeStandard)
188 , m_delegateIsHandlingProvisionalLoadError(false)
189 , m_quickRedirectComing(false)
190 , m_sentRedirectNotification(false)
191 , m_inStopAllLoaders(false)
192 #if ENABLE(TIZEN_PAUSE_NETWORK)
193 , m_inSuspendAllLoaders(false)
195 , m_isExecutingJavaScriptFormAction(false)
196 , m_didCallImplicitClose(false)
197 , m_wasUnloadEventEmitted(false)
198 , m_pageDismissalEventBeingDispatched(NoDismissal)
199 , m_isComplete(false)
200 , m_isLoadingMainResource(false)
201 , m_hasReceivedFirstData(false)
202 , m_needsClear(false)
203 , m_checkTimer(this, &FrameLoader::checkTimerFired)
204 , m_shouldCallCheckCompleted(false)
205 , m_shouldCallCheckLoadComplete(false)
207 , m_didPerformFirstNavigation(false)
208 , m_loadingFromCachedPage(false)
209 , m_suppressOpenerInNewFrame(false)
210 , m_forcedSandboxFlags(SandboxNone)
214 FrameLoader::~FrameLoader()
218 HashSet<Frame*>::iterator end = m_openedFrames.end();
219 for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
220 (*it)->loader()->m_opener = 0;
222 m_client->frameLoaderDestroyed();
224 if (m_networkingContext)
225 m_networkingContext->invalidate();
228 void FrameLoader::init()
230 // This somewhat odd set of steps gives the frame an initial empty document.
231 // It would be better if this could be done with even fewer steps.
232 m_stateMachine.advanceTo(FrameLoaderStateMachine::CreatingInitialEmptyDocument);
233 setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, "")), SubstituteData()).get());
234 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
235 setState(FrameStateProvisional);
236 m_provisionalDocumentLoader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String()));
237 m_provisionalDocumentLoader->finishedLoading();
238 ASSERT(!m_frame->document());
239 m_documentLoader->writer()->begin(KURL(), false);
240 m_documentLoader->writer()->end();
241 m_frame->document()->cancelParsing();
242 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
243 m_didCallImplicitClose = true;
245 m_networkingContext = m_client->createNetworkingContext();
248 void FrameLoader::setDefersLoading(bool defers)
250 if (m_documentLoader)
251 m_documentLoader->setDefersLoading(defers);
252 if (m_provisionalDocumentLoader)
253 m_provisionalDocumentLoader->setDefersLoading(defers);
254 if (m_policyDocumentLoader)
255 m_policyDocumentLoader->setDefersLoading(defers);
256 history()->setDefersLoading(defers);
259 m_frame->navigationScheduler()->startTimer();
260 startCheckCompleteTimer();
264 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
266 RefPtr<Frame> protect(m_frame);
267 urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
268 0, lockHistory, lockBackForwardList, MaybeSendReferrer, ReplaceDocumentIfJavaScriptURL);
271 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer)
273 urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
274 triggeringEvent, lockHistory, lockBackForwardList, shouldSendReferrer, DoNotReplaceDocumentIfJavaScriptURL);
277 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
278 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
279 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
281 ASSERT(!m_suppressOpenerInNewFrame);
283 FrameLoadRequest frameRequest(passedRequest);
285 if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
288 if (frameRequest.frameName().isEmpty())
289 frameRequest.setFrameName(m_frame->document()->baseTarget());
291 if (shouldSendReferrer == NeverSendReferrer)
292 m_suppressOpenerInNewFrame = true;
293 if (frameRequest.resourceRequest().httpReferrer().isEmpty())
294 frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
295 addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
297 loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, shouldSendReferrer);
299 m_suppressOpenerInNewFrame = false;
302 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
304 ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
306 // FIXME: Find a good spot for these.
307 ASSERT(submission->data());
308 ASSERT(submission->state());
309 ASSERT(submission->state()->sourceFrame() == m_frame);
311 if (!m_frame->page())
314 if (submission->action().isEmpty())
317 if (isDocumentSandboxed(m_frame, SandboxForms))
320 if (protocolIsJavaScript(submission->action())) {
321 m_isExecutingJavaScriptFormAction = true;
322 m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
323 m_isExecutingJavaScriptFormAction = false;
327 Frame* targetFrame = m_frame->tree()->find(submission->target());
328 if (!shouldAllowNavigation(targetFrame))
331 if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
334 targetFrame = m_frame;
336 submission->clearTarget();
338 if (!targetFrame->page())
341 // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
343 // We do not want to submit more than one form from the same page, nor do we want to submit a single
344 // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
345 // The flag is reset in each time we start handle a new mouse or key down event, and
346 // also in setView since this part may get reused for a page from the back/forward cache.
347 // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
349 // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
350 // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
351 // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
353 if (m_frame->tree()->isDescendantOf(targetFrame)) {
354 if (m_submittedFormURL == submission->action())
356 m_submittedFormURL = submission->action();
359 submission->data()->generateFiles(m_frame->document());
360 submission->setReferrer(m_outgoingReferrer);
361 submission->setOrigin(outgoingOrigin());
363 targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
366 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
368 if (m_frame->document() && m_frame->document()->parser())
369 m_frame->document()->parser()->stopParsing();
371 if (unloadEventPolicy != UnloadEventPolicyNone) {
372 if (m_frame->document()) {
373 if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
374 Node* currentFocusedNode = m_frame->document()->focusedNode();
375 if (currentFocusedNode)
376 currentFocusedNode->aboutToUnload();
377 if (m_frame->domWindow() && m_pageDismissalEventBeingDispatched == NoDismissal) {
378 if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
379 m_pageDismissalEventBeingDispatched = PageHideDismissal;
380 m_frame->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
382 if (!m_frame->document()->inPageCache()) {
383 RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
384 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
385 // while dispatching the event, so protect it to prevent writing the end
386 // time into freed memory.
387 RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
388 m_pageDismissalEventBeingDispatched = UnloadDismissal;
389 if (documentLoader && !documentLoader->timing()->unloadEventStart && !documentLoader->timing()->unloadEventEnd) {
390 DocumentLoadTiming* timing = documentLoader->timing();
391 ASSERT(timing->navigationStart);
392 m_frame->domWindow()->dispatchTimedEvent(unloadEvent, m_frame->domWindow()->document(), &timing->unloadEventStart, &timing->unloadEventEnd);
394 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->domWindow()->document());
397 m_pageDismissalEventBeingDispatched = NoDismissal;
398 if (m_frame->document())
399 m_frame->document()->updateStyleIfNeeded();
400 m_wasUnloadEventEmitted = true;
404 // Dispatching the unload event could have made m_frame->document() null.
405 if (m_frame->document() && !m_frame->document()->inPageCache()) {
406 // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
407 bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
408 && m_frame->document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
410 if (!keepEventListeners)
411 m_frame->document()->removeAllEventListeners();
415 m_isComplete = true; // to avoid calling completed() in finishedParsing()
416 m_isLoadingMainResource = false;
417 m_didCallImplicitClose = true; // don't want that one either
419 if (m_frame->document() && m_frame->document()->parsing()) {
421 m_frame->document()->setParsing(false);
424 m_hasReceivedFirstData = true;
426 if (Document* doc = m_frame->document()) {
427 // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
428 // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
429 doc->setReadyState(Document::Complete);
431 #if ENABLE(SQL_DATABASE)
432 doc->stopDatabases(0);
436 // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
437 m_frame->navigationScheduler()->cancel();
440 void FrameLoader::stop()
442 // http://bugs.webkit.org/show_bug.cgi?id=10854
443 // The frame's last ref may be removed and it will be deleted by checkCompleted().
444 RefPtr<Frame> protector(m_frame);
446 if (DocumentParser* parser = m_frame->document()->parser()) {
447 parser->stopParsing();
451 icon()->stopLoader();
454 bool FrameLoader::closeURL()
456 history()->saveDocumentState();
458 // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.
459 Document* currentDocument = m_frame->document();
460 stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
462 m_frame->editor()->clearUndoRedoOperations();
466 bool FrameLoader::didOpenURL()
468 if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
469 // A redirect was scheduled before the document was created.
470 // This can happen when one frame changes another frame's location.
474 m_frame->navigationScheduler()->cancel();
475 m_frame->editor()->clearLastEditCommand();
477 m_isComplete = false;
478 m_isLoadingMainResource = true;
479 m_didCallImplicitClose = false;
481 // If we are still in the process of initializing an empty document then
482 // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
483 // since it may cause clients to attempt to render the frame.
484 if (!m_stateMachine.creatingInitialEmptyDocument()) {
485 if (DOMWindow* window = m_frame->existingDOMWindow()) {
486 window->setStatus(String());
487 window->setDefaultStatus(String());
490 m_hasReceivedFirstData = false;
497 void FrameLoader::didExplicitOpen()
499 m_isComplete = false;
500 m_didCallImplicitClose = false;
502 // Calling document.open counts as committing the first real document load.
503 if (!m_stateMachine.committedFirstRealDocumentLoad())
504 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
506 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
507 // from a subsequent window.document.open / window.document.write call.
508 // Canceling redirection here works for all cases because document.open
509 // implicitly precedes document.write.
510 m_frame->navigationScheduler()->cancel();
514 void FrameLoader::cancelAndClear()
516 m_frame->navigationScheduler()->cancel();
522 m_frame->script()->updatePlatformScriptObjects();
525 void FrameLoader::clear(bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
527 m_frame->editor()->clear();
531 m_needsClear = false;
533 if (!m_frame->document()->inPageCache()) {
534 m_frame->document()->cancelParsing();
535 m_frame->document()->stopActiveDOMObjects();
536 if (m_frame->document()->attached()) {
537 m_frame->document()->willRemove();
538 m_frame->document()->detach();
540 m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
544 // Do this after detaching the document so that the unload event works.
545 if (clearWindowProperties) {
546 m_frame->clearDOMWindow();
547 m_frame->script()->clearWindowShell(m_frame->document()->inPageCache());
550 m_frame->selection()->clear();
551 m_frame->eventHandler()->clear();
552 if (clearFrameView && m_frame->view())
553 m_frame->view()->clear();
555 // Do not drop the document before the ScriptController and view are cleared
556 // as some destructors might still try to access the document.
557 m_frame->setDocument(0);
559 m_subframeLoader.clear();
561 if (clearScriptObjects)
562 m_frame->script()->clearScriptObjects();
564 m_frame->navigationScheduler()->clear();
567 m_shouldCallCheckCompleted = false;
568 m_shouldCallCheckLoadComplete = false;
570 if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
571 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
574 void FrameLoader::receivedFirstData()
576 KURL workingURL = activeDocumentLoader()->documentURL();
577 #if ENABLE(WEB_ARCHIVE)
578 // FIXME: The document loader, not the frame loader, should be in charge of loading web archives.
579 // Once this is done, we can just make DocumentLoader::documentURL() return the right URL
580 // based on whether it has a non-null archive or not.
581 if (m_archive && activeDocumentLoader()->parsedArchiveData())
582 workingURL = m_archive->mainResource()->url();
585 activeDocumentLoader()->writer()->begin(workingURL, false);
586 activeDocumentLoader()->writer()->setDocumentWasLoadedAsPartOfNavigation();
590 // The origin is the MHTML file, we need to set the base URL to the document encoded in the MHTML so
591 // relative URLs are resolved properly.
592 m_frame->document()->setBaseURLOverride(m_archive->mainResource()->url());
596 dispatchDidCommitLoad();
597 dispatchDidClearWindowObjectsInAllWorlds();
599 if (m_documentLoader) {
600 StringWithDirection ptitle = m_documentLoader->title();
601 // If we have a title let the WebView know about it.
602 if (!ptitle.isNull())
603 m_client->dispatchDidReceiveTitle(ptitle);
606 m_hasReceivedFirstData = true;
608 if (!m_documentLoader)
610 if (m_frame->document()->isViewSource())
615 if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
618 url = m_frame->document()->url().string();
620 url = m_frame->document()->completeURL(url).string();
622 m_frame->navigationScheduler()->scheduleRedirect(delay, url);
625 void FrameLoader::setOutgoingReferrer(const KURL& url)
627 m_outgoingReferrer = url.strippedForUseAsReferrer();
630 void FrameLoader::didBeginDocument(bool dispatch)
633 m_isComplete = false;
634 m_didCallImplicitClose = false;
635 m_isLoadingMainResource = true;
636 m_frame->document()->setReadyState(Document::Loading);
638 if (m_pendingStateObject) {
639 m_frame->document()->statePopped(m_pendingStateObject.get());
640 m_pendingStateObject.clear();
644 dispatchDidClearWindowObjectsInAllWorlds();
646 updateFirstPartyForCookies();
648 Settings* settings = m_frame->document()->settings();
649 m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically());
651 if (m_documentLoader) {
652 String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
653 if (!dnsPrefetchControl.isEmpty())
654 m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
656 String contentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
657 if (!contentSecurityPolicy.isEmpty())
658 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(contentSecurityPolicy, ContentSecurityPolicy::EnforcePolicy);
660 String reportOnlyContentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
661 if (!reportOnlyContentSecurityPolicy.isEmpty())
662 m_frame->document()->contentSecurityPolicy()->didReceiveHeader(reportOnlyContentSecurityPolicy, ContentSecurityPolicy::ReportOnly);
665 history()->restoreDocumentState();
668 void FrameLoader::didEndDocument()
670 m_isLoadingMainResource = false;
673 void FrameLoader::finishedParsing()
675 m_frame->injectUserScripts(InjectAtDocumentEnd);
677 if (m_stateMachine.creatingInitialEmptyDocument())
680 // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
681 // because doing so will cause us to re-enter the destructor when protector goes out of scope.
682 // Null-checking the FrameView indicates whether or not we're in the destructor.
683 RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
685 m_client->dispatchDidFinishDocumentLoad();
689 if (!m_frame->view())
690 return; // We are being destroyed by something checkCompleted called.
692 // Check if the scrollbars are really needed for the content.
693 // If not, remove them, relayout, and repaint.
694 m_frame->view()->restoreScrollbar();
695 m_frame->view()->scrollToFragment(m_frame->document()->url());
698 void FrameLoader::loadDone()
703 bool FrameLoader::allChildrenAreComplete() const
705 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
706 if (!child->loader()->m_isComplete)
712 bool FrameLoader::allAncestorsAreComplete() const
714 for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
715 if (!ancestor->loader()->m_isComplete)
721 void FrameLoader::checkCompleted()
723 m_shouldCallCheckCompleted = false;
724 #if ENABLE(TIZEN_DUPLICATED_LOAD_URL_FIX)
725 m_duplicateCheckUrl = KURL();
729 m_frame->view()->checkStopDelayingDeferredRepaints();
731 // Have we completed before?
735 // Are we still parsing?
736 if (m_frame->document()->parsing())
739 // Still waiting for images/scripts?
740 if (m_frame->document()->cachedResourceLoader()->requestCount())
743 // Still waiting for elements that don't go through a FrameLoader?
744 if (m_frame->document()->isDelayingLoadEvent())
747 // Any frame that hasn't completed yet?
748 if (!allChildrenAreComplete())
753 m_frame->document()->setReadyState(Document::Complete);
755 RefPtr<Frame> protect(m_frame);
756 checkCallImplicitClose(); // if we didn't do it before
758 m_frame->navigationScheduler()->startTimer();
765 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
767 if (Page* page = m_frame->page()) {
768 if (page->defersLoading())
771 if (m_shouldCallCheckCompleted)
773 if (m_shouldCallCheckLoadComplete)
777 void FrameLoader::startCheckCompleteTimer()
779 if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
781 if (m_checkTimer.isActive())
783 m_checkTimer.startOneShot(0);
786 void FrameLoader::scheduleCheckCompleted()
788 m_shouldCallCheckCompleted = true;
789 startCheckCompleteTimer();
792 void FrameLoader::scheduleCheckLoadComplete()
794 m_shouldCallCheckLoadComplete = true;
795 startCheckCompleteTimer();
798 void FrameLoader::checkCallImplicitClose()
800 if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
803 if (!allChildrenAreComplete())
804 return; // still got a frame running -> too early
806 m_didCallImplicitClose = true;
807 m_wasUnloadEventEmitted = false;
808 m_frame->document()->implicitClose();
811 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
815 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
816 RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);
817 if (subframeArchive) {
818 childFrame->loader()->loadArchive(subframeArchive.release());
821 #endif // ENABLE(WEB_ARCHIVE)
823 HistoryItem* parentItem = history()->currentItem();
824 // If we're moving in the back/forward list, we might want to replace the content
825 // of this child frame with whatever was there at that point.
826 if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
827 && !m_frame->document()->loadEventFinished()) {
828 HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
830 childFrame->loader()->loadDifferentDocumentItem(childItem, loadType());
835 childFrame->loader()->loadURL(url, referer, String(), false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
838 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
839 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
843 ArchiveResource* mainResource = m_archive->mainResource();
844 ASSERT(mainResource);
848 SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
850 ResourceRequest request(mainResource->url());
852 request.applyWebArchiveHackForMail();
855 RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
856 documentLoader->addAllArchiveResources(m_archive.get());
857 load(documentLoader.get());
859 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
861 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
863 String mimeType = mimeTypeIn;
864 String decodedPath = decodeURLEscapeSequences(url.path());
865 String extension = decodedPath.substring(decodedPath.reverseFind('.') + 1);
867 // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
868 if (mimeType.isEmpty())
869 mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
871 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
872 if (mimeType.isEmpty())
873 mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
876 if (mimeType.isEmpty())
877 return ObjectContentFrame; // Go ahead and hope that we can display the content.
879 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
880 bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
882 bool plugInSupportsMIMEType = false;
885 if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
886 return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
888 if (plugInSupportsMIMEType)
889 return WebCore::ObjectContentNetscapePlugin;
891 if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
892 return WebCore::ObjectContentFrame;
894 return WebCore::ObjectContentNone;
897 String FrameLoader::outgoingReferrer() const
899 return m_outgoingReferrer;
902 String FrameLoader::outgoingOrigin() const
904 return m_frame->document()->securityOrigin()->toString();
907 bool FrameLoader::isMixedContent(SecurityOrigin* context, const KURL& url)
909 if (context->protocol() != "https")
910 return false; // We only care about HTTPS security origins.
912 if (!url.isValid() || SchemeRegistry::shouldTreatURLSchemeAsSecure(url.protocol()))
913 return false; // Loading these protocols is secure.
918 bool FrameLoader::checkIfDisplayInsecureContent(SecurityOrigin* context, const KURL& url)
920 if (!isMixedContent(context, url))
923 Settings* settings = m_frame->settings();
924 bool allowed = m_client->allowDisplayingInsecureContent(settings && settings->allowDisplayOfInsecureContent(), context, url);
925 String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
926 m_frame->document()->url().string() + " displayed insecure content from " + url.string() + ".\n";
928 m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
931 m_client->didDisplayInsecureContent();
936 bool FrameLoader::checkIfRunInsecureContent(SecurityOrigin* context, const KURL& url)
938 if (!isMixedContent(context, url))
941 Settings* settings = m_frame->settings();
942 bool allowed = m_client->allowRunningInsecureContent(settings && settings->allowRunningOfInsecureContent(), context, url);
943 String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
944 m_frame->document()->url().string() + " ran insecure content from " + url.string() + ".\n";
946 m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
949 m_client->didRunInsecureContent(context, url);
954 Frame* FrameLoader::opener()
959 void FrameLoader::setOpener(Frame* opener)
962 m_opener->loader()->m_openedFrames.remove(m_frame);
964 opener->loader()->m_openedFrames.add(m_frame);
967 if (m_frame->document()) {
968 m_frame->document()->initSecurityContext();
969 m_frame->domWindow()->setSecurityOrigin(m_frame->document()->securityOrigin());
973 // FIXME: This does not belong in FrameLoader!
974 void FrameLoader::handleFallbackContent()
976 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
977 if (!owner || !owner->hasTagName(objectTag))
979 static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
982 void FrameLoader::provisionalLoadStarted()
984 if (m_stateMachine.firstLayoutDone())
985 m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
986 m_frame->navigationScheduler()->cancel(true);
987 m_client->provisionalLoadStarted();
990 void FrameLoader::resetMultipleFormSubmissionProtection()
992 m_submittedFormURL = KURL();
995 void FrameLoader::willSetEncoding()
997 if (!m_hasReceivedFirstData)
1001 void FrameLoader::updateFirstPartyForCookies()
1003 if (m_frame->tree()->parent())
1004 setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
1006 setFirstPartyForCookies(m_frame->document()->url());
1009 void FrameLoader::setFirstPartyForCookies(const KURL& url)
1011 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
1012 frame->document()->setFirstPartyForCookies(url);
1015 // This does the same kind of work that didOpenURL does, except it relies on the fact
1016 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1017 void FrameLoader::loadInSameDocument(const KURL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1019 // If we have a state object, we cannot also be a new navigation.
1020 ASSERT(!stateObject || (stateObject && !isNewNavigation));
1022 // Update the data source's request with the new URL to fake the URL change
1023 KURL oldURL = m_frame->document()->url();
1024 m_frame->document()->setURL(url);
1025 documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1026 if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1027 // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
1028 // based on the current request. Must also happen before we openURL and displace the
1029 // scroll position, since adding the BF item will save away scroll state.
1031 // NB2: If we were loading a long, slow doc, and the user anchor nav'ed before
1032 // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1033 // before it. Adding the b/f item will bump the slow doc down to prevItem, even
1034 // though its load is not yet done. I think this all works out OK, for one because
1035 // we have already saved away the scroll and doc state for the long slow load,
1036 // but it's not an obvious case.
1038 history()->updateBackForwardListForFragmentScroll();
1041 bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1043 history()->updateForSameDocumentNavigation();
1045 // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1047 m_frame->eventHandler()->stopAutoscrollTimer();
1049 // It's important to model this as a load that starts and immediately finishes.
1050 // Otherwise, the parent frame may think we never finished loading.
1053 // We need to scroll to the fragment whether or not a hash change occurred, since
1054 // the user might have scrolled since the previous navigation.
1055 if (FrameView* view = m_frame->view())
1056 view->scrollToFragment(url);
1058 m_isComplete = false;
1061 if (isNewNavigation) {
1062 // This will clear previousItem from the rest of the frame tree that didn't
1063 // doing any loading. We need to make a pass on this now, since for anchor nav
1064 // we'll not go through a real load and reach Completed state.
1065 checkLoadComplete();
1068 m_client->dispatchDidNavigateWithinPage();
1070 m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1071 m_client->dispatchDidPopStateWithinPage();
1074 m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1075 m_client->dispatchDidChangeLocationWithinPage();
1078 // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1079 m_client->didFinishLoad();
1082 bool FrameLoader::isComplete() const
1084 return m_isComplete;
1087 void FrameLoader::completed()
1089 RefPtr<Frame> protect(m_frame);
1091 for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1092 descendant->navigationScheduler()->startTimer();
1094 if (Frame* parent = m_frame->tree()->parent())
1095 parent->loader()->checkCompleted();
1097 if (m_frame->view())
1098 m_frame->view()->maintainScrollPositionAtAnchor(0);
1101 void FrameLoader::started()
1103 for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1104 frame->loader()->m_isComplete = false;
1107 void FrameLoader::prepareForHistoryNavigation()
1109 // If there is no currentItem, but we still want to engage in
1110 // history navigation we need to manufacture one, and update
1111 // the state machine of this frame to impersonate having
1113 RefPtr<HistoryItem> currentItem = history()->currentItem();
1115 currentItem = HistoryItem::create();
1116 currentItem->setLastVisitWasFailure(true);
1117 history()->setCurrentItem(currentItem.get());
1118 frame()->page()->backForward()->setCurrentItem(currentItem.get());
1120 ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1121 stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1122 stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1126 void FrameLoader::prepareForLoadStart()
1128 if (Page* page = m_frame->page())
1129 page->progress()->progressStarted(m_frame);
1130 m_client->dispatchDidStartProvisionalLoad();
1133 void FrameLoader::setupForReplace()
1135 setState(FrameStateProvisional);
1136 m_provisionalDocumentLoader = m_documentLoader;
1137 m_documentLoader = 0;
1141 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1142 PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
1144 // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1145 RefPtr<Frame> protect(m_frame);
1147 KURL url = request.resourceRequest().url();
1149 ASSERT(m_frame->document());
1150 if (!request.requester()->canDisplay(url)) {
1151 reportLocalLoadFailed(m_frame, url.string());
1155 String argsReferrer = request.resourceRequest().httpReferrer();
1156 if (argsReferrer.isEmpty())
1157 argsReferrer = m_outgoingReferrer;
1159 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), url, argsReferrer);
1160 if (shouldSendReferrer == NeverSendReferrer)
1161 referrer = String();
1163 FrameLoadType loadType;
1164 if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1165 loadType = FrameLoadTypeReload;
1166 else if (lockBackForwardList)
1167 loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1169 loadType = FrameLoadTypeStandard;
1171 if (request.resourceRequest().httpMethod() == "POST")
1172 loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1174 loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1176 // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1177 // load if frame names have changed.
1178 Frame* sourceFrame = formState ? formState->sourceFrame() : m_frame;
1179 Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName());
1180 if (targetFrame && targetFrame != sourceFrame) {
1181 if (Page* page = targetFrame->page())
1182 page->chrome()->focus();
1186 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1187 PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1189 #if ENABLE(TIZEN_DUPLICATED_LOAD_URL_FIX)
1190 if (m_duplicateCheckUrl == newURL)
1193 m_duplicateCheckUrl = newURL;
1196 if (m_inStopAllLoaders)
1199 RefPtr<FormState> formState = prpFormState;
1200 bool isFormSubmission = formState;
1202 ResourceRequest request(newURL);
1203 if (!referrer.isEmpty()) {
1204 request.setHTTPReferrer(referrer);
1205 RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1206 addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1208 addExtraFieldsToRequest(request, newLoadType, true);
1209 if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1210 request.setCachePolicy(ReloadIgnoringCacheData);
1212 ASSERT(newLoadType != FrameLoadTypeSame);
1214 // The search for a target frame is done earlier in the case of form submission.
1215 Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1216 if (targetFrame && targetFrame != m_frame) {
1217 targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState.release());
1221 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1224 NavigationAction action(request, newLoadType, isFormSubmission, event);
1226 if (!targetFrame && !frameName.isEmpty()) {
1227 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1228 request, formState.release(), frameName, this);
1232 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1234 bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1235 const String& httpMethod = request.httpMethod();
1237 // Make sure to do scroll to anchor processing even if the URL is
1238 // exactly the same so pages with '#' links and DHTML side effects
1240 if (shouldScrollToAnchor(isFormSubmission, httpMethod, newLoadType, newURL)) {
1241 oldDocumentLoader->setTriggeringAction(action);
1242 policyChecker()->stopCheck();
1243 policyChecker()->setLoadType(newLoadType);
1244 policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1245 callContinueFragmentScrollAfterNavigationPolicy, this);
1247 // must grab this now, since this load may stop the previous load and clear this flag
1248 bool isRedirect = m_quickRedirectComing;
1249 loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1251 m_quickRedirectComing = false;
1252 if (m_provisionalDocumentLoader)
1253 m_provisionalDocumentLoader->setIsClientRedirect(true);
1254 } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1255 // Example of this case are sites that reload the same URL with a different cookie
1256 // driving the generated content, or a master frame with links that drive a target
1257 // frame, where the user has clicked on the same link repeatedly.
1258 m_loadType = FrameLoadTypeSame;
1262 void FrameLoader::load(const ResourceRequest& request, bool lockHistory)
1264 load(request, SubstituteData(), lockHistory);
1267 void FrameLoader::load(const ResourceRequest& request, const SubstituteData& substituteData, bool lockHistory)
1269 if (m_inStopAllLoaders)
1272 // FIXME: is this the right place to reset loadType? Perhaps this should be done after loading is finished or aborted.
1273 m_loadType = FrameLoadTypeStandard;
1274 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData);
1275 if (lockHistory && m_documentLoader)
1276 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1280 void FrameLoader::load(const ResourceRequest& request, const String& frameName, bool lockHistory)
1282 if (frameName.isEmpty()) {
1283 load(request, lockHistory);
1287 Frame* frame = findFrameForNavigation(frameName);
1289 frame->loader()->load(request, lockHistory);
1293 policyChecker()->checkNewWindowPolicy(NavigationAction(request, NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request, 0, frameName, this);
1296 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1298 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1299 if (lockHistory && m_documentLoader)
1300 loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1302 loader->setTriggeringAction(action);
1303 if (m_documentLoader)
1304 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1306 loadWithDocumentLoader(loader.get(), type, formState);
1309 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1311 ResourceRequest& r = newDocumentLoader->request();
1312 addExtraFieldsToMainResourceRequest(r);
1315 if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1316 r.setCachePolicy(ReloadIgnoringCacheData);
1317 type = FrameLoadTypeSame;
1319 type = FrameLoadTypeStandard;
1321 if (m_documentLoader)
1322 newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1324 // When we loading alternate content for an unreachable URL that we're
1325 // visiting in the history list, we treat it as a reload so the history list
1326 // is appropriately maintained.
1328 // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1329 // shouldn't a more explicit type of reload be defined, that means roughly
1330 // "load without affecting history" ?
1331 if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1332 // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1333 // In this case we should save the document state now. Otherwise the state can be lost because load type is
1334 // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1335 history()->saveDocumentAndScrollState();
1337 ASSERT(type == FrameLoadTypeStandard);
1338 type = FrameLoadTypeReload;
1341 loadWithDocumentLoader(newDocumentLoader, type, 0);
1344 #if ENABLE(TIZEN_DOWNLOAD)
1345 void FrameLoader::download(const ResourceRequest& request)
1347 if (m_inStopAllLoaders)
1350 m_loadType = FrameLoadTypeDownload;
1351 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1353 ResourceRequest& r = loader->request();
1354 addExtraFieldsToMainResourceRequest(r);
1356 if (m_documentLoader)
1357 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1359 loadWithDocumentLoader(loader.get(), FrameLoadTypeDownload, 0);
1363 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1365 // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1366 RefPtr<Frame> protect(m_frame);
1368 ASSERT(m_client->hasWebView());
1370 // Unfortunately the view must be non-nil, this is ultimately due
1371 // to parser requiring a FrameView. We should fix this dependency.
1373 ASSERT(m_frame->view());
1375 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1378 if (m_frame->document())
1379 m_previousUrl = m_frame->document()->url();
1381 policyChecker()->setLoadType(type);
1382 RefPtr<FormState> formState = prpFormState;
1383 bool isFormSubmission = formState;
1385 const KURL& newURL = loader->request().url();
1386 const String& httpMethod = loader->request().httpMethod();
1388 if (shouldScrollToAnchor(isFormSubmission, httpMethod, policyChecker()->loadType(), newURL)) {
1389 RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1390 NavigationAction action(loader->request(), policyChecker()->loadType(), isFormSubmission);
1392 oldDocumentLoader->setTriggeringAction(action);
1393 policyChecker()->stopCheck();
1394 policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1395 callContinueFragmentScrollAfterNavigationPolicy, this);
1397 if (Frame* parent = m_frame->tree()->parent())
1398 loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
1400 policyChecker()->stopCheck();
1401 setPolicyDocumentLoader(loader);
1402 if (loader->triggeringAction().isEmpty())
1403 loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker()->loadType(), isFormSubmission));
1405 if (Element* ownerElement = m_frame->ownerElement()) {
1406 // We skip dispatching the beforeload event if we've already
1407 // committed a real document load because the event would leak
1408 // subsequent activity by the frame which the parent frame isn't
1409 // supposed to learn. For example, if the child frame navigated to
1410 // a new URL, the parent frame shouldn't learn the URL.
1411 if (!m_stateMachine.committedFirstRealDocumentLoad()
1412 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1413 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1418 policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1419 callContinueLoadAfterNavigationPolicy, this);
1423 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1425 ASSERT(!url.isEmpty());
1429 frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Not allowed to load local resource: " + url, 0, String());
1432 const ResourceRequest& FrameLoader::initialRequest() const
1434 return activeDocumentLoader()->originalRequest();
1437 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1439 ResourceRequest request(url);
1441 unsigned long identifier;
1442 ResourceError error;
1443 requestFromDelegate(request, identifier, error);
1444 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1446 url = request.url();
1448 return error.isNull();
1451 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1453 KURL unreachableURL = docLoader->unreachableURL();
1455 if (unreachableURL.isEmpty())
1458 if (!isBackForwardLoadType(policyChecker()->loadType()))
1461 // We only treat unreachableURLs specially during the delegate callbacks
1462 // for provisional load errors and navigation policy decisions. The former
1463 // case handles well-formed URLs that can't be loaded, and the latter
1464 // case handles malformed URLs and unknown schemes. Loading alternate content
1465 // at other times behaves like a standard load.
1466 DocumentLoader* compareDocumentLoader = 0;
1467 if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1468 compareDocumentLoader = m_policyDocumentLoader.get();
1469 else if (m_delegateIsHandlingProvisionalLoadError)
1470 compareDocumentLoader = m_provisionalDocumentLoader.get();
1472 return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1475 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1477 if (!m_documentLoader)
1480 ResourceRequest request = m_documentLoader->request();
1481 KURL unreachableURL = m_documentLoader->unreachableURL();
1482 if (!unreachableURL.isEmpty())
1483 request.setURL(unreachableURL);
1485 request.setCachePolicy(ReturnCacheDataElseLoad);
1487 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1488 setPolicyDocumentLoader(loader.get());
1490 loader->setOverrideEncoding(encoding);
1492 loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1495 void FrameLoader::reload(bool endToEndReload)
1497 if (!m_documentLoader)
1500 // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1501 // Reloading in this case will lose the current contents (see 4151001).
1502 if (m_documentLoader->request().url().isEmpty())
1505 ResourceRequest initialRequest = m_documentLoader->request();
1507 // Replace error-page URL with the URL we were trying to reach.
1508 KURL unreachableURL = m_documentLoader->unreachableURL();
1509 if (!unreachableURL.isEmpty())
1510 initialRequest.setURL(unreachableURL);
1512 #if ENABLE(TIZEN_RELOAD_CACHE_POLICY_PATCH)
1513 initialRequest.setCachePolicy(ReloadIgnoringCacheData);
1516 // Create a new document loader for the reload, this will become m_documentLoader eventually,
1517 // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1518 RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, SubstituteData());
1520 ResourceRequest& request = loader->request();
1522 // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1523 request.setCachePolicy(ReloadIgnoringCacheData);
1525 // If we're about to re-post, set up action so the application can warn the user.
1526 if (request.httpMethod() == "POST")
1527 loader->setTriggeringAction(NavigationAction(request, NavigationTypeFormResubmitted));
1529 loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1531 loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1534 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
1536 // targetFrame can be NULL when we're trying to navigate a top-level frame
1537 // that has a NULL opener.
1541 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
1542 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
1543 Document* ancestorDocument = ancestorFrame->document();
1544 if (!ancestorDocument)
1547 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
1548 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
1551 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
1552 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
1559 bool FrameLoader::shouldAllowNavigation(Frame* targetFrame) const
1561 // The navigation change is safe if the active frame is:
1562 // - in the same security origin as the target or one of the target's
1565 // Or the target frame is:
1566 // - a top-level frame in the frame hierarchy and the active frame can
1567 // navigate the target frame's opener per above or it is the opener of
1568 // the target frame.
1573 // Performance optimization.
1574 if (m_frame == targetFrame)
1577 // Let a frame navigate the top-level window that contains it. This is
1578 // important to allow because it lets a site "frame-bust" (escape from a
1579 // frame created by another web site).
1580 if (!isDocumentSandboxed(m_frame, SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
1583 // A sandboxed frame can only navigate itself and its descendants.
1584 if (isDocumentSandboxed(m_frame, SandboxNavigation) && !targetFrame->tree()->isDescendantOf(m_frame))
1587 // Let a frame navigate its opener if the opener is a top-level window.
1588 if (!targetFrame->tree()->parent() && m_frame->loader()->opener() == targetFrame)
1591 Document* activeDocument = m_frame->document();
1592 ASSERT(activeDocument);
1593 const SecurityOrigin* activeSecurityOrigin = activeDocument->securityOrigin();
1595 // For top-level windows, check the opener.
1596 if (!targetFrame->tree()->parent() && canAccessAncestor(activeSecurityOrigin, targetFrame->loader()->opener()))
1599 // In general, check the frame's ancestors.
1600 if (canAccessAncestor(activeSecurityOrigin, targetFrame))
1603 Settings* settings = targetFrame->settings();
1604 if (settings && !settings->privateBrowsingEnabled()) {
1605 Document* targetDocument = targetFrame->document();
1606 // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
1607 String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
1608 targetDocument->url().string() + " from frame with URL " + activeDocument->url().string() + ".\n";
1610 // FIXME: should we print to the console of the activeFrame as well?
1611 targetFrame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1617 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1619 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1620 if (m_pageDismissalEventBeingDispatched != NoDismissal)
1623 // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1624 if (m_inStopAllLoaders)
1627 m_inStopAllLoaders = true;
1629 policyChecker()->stopCheck();
1631 // If no new load is in progress, we should clear the provisional item from history
1632 // before we call stopLoading.
1633 if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1634 history()->setProvisionalItem(0);
1636 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1637 child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
1638 if (m_provisionalDocumentLoader)
1639 m_provisionalDocumentLoader->stopLoading();
1640 if (m_documentLoader)
1641 m_documentLoader->stopLoading();
1643 setProvisionalDocumentLoader(0);
1645 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
1646 if (m_documentLoader)
1647 m_documentLoader->clearArchiveResources();
1650 m_checkTimer.stop();
1652 m_inStopAllLoaders = false;
1655 #if ENABLE(TIZEN_PAUSE_NETWORK)
1656 void FrameLoader::suspendLoadingSubframes()
1658 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
1659 child->loader()->suspendAllLoaders();
1663 void FrameLoader::resumeLoadingSubframes()
1665 for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
1666 child->loader()->resumeAllLoaders();
1670 void FrameLoader::suspendAllLoaders()
1672 ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1677 suspendLoadingSubframes();
1679 if (m_provisionalDocumentLoader)
1680 m_provisionalDocumentLoader->suspendLoading();
1682 if (m_documentLoader)
1683 m_documentLoader->suspendLoading();
1685 m_inSuspendAllLoaders = true;
1688 void FrameLoader::resumeAllLoaders()
1693 resumeLoadingSubframes();
1695 if (m_provisionalDocumentLoader)
1696 m_provisionalDocumentLoader->resumeLoading();
1698 if (m_documentLoader)
1699 m_documentLoader->resumeLoading();
1701 m_inSuspendAllLoaders = false;
1705 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1709 if (deferCheckLoadComplete)
1710 scheduleCheckLoadComplete();
1711 else if (m_frame->page())
1712 checkLoadComplete();
1715 DocumentLoader* FrameLoader::activeDocumentLoader() const
1717 if (m_state == FrameStateProvisional)
1718 return m_provisionalDocumentLoader.get();
1719 return m_documentLoader.get();
1722 bool FrameLoader::isLoading() const
1724 DocumentLoader* docLoader = activeDocumentLoader();
1727 return docLoader->isLoadingMainResource() || docLoader->isLoadingSubresources() || docLoader->isLoadingPlugIns();
1730 bool FrameLoader::frameHasLoaded() const
1732 return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
1735 void FrameLoader::transferLoadingResourcesFromPage(Page* oldPage)
1737 ASSERT(oldPage != m_frame->page());
1739 activeDocumentLoader()->transferLoadingResourcesFromPage(oldPage);
1740 oldPage->progress()->progressCompleted(m_frame);
1741 if (m_frame->page())
1742 m_frame->page()->progress()->progressStarted(m_frame);
1746 void FrameLoader::dispatchTransferLoadingResourceFromPage(ResourceLoader* loader, const ResourceRequest& request, Page* oldPage)
1748 notifier()->dispatchTransferLoadingResourceFromPage(loader, request, oldPage);
1751 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1753 if (!loader && !m_documentLoader)
1756 ASSERT(loader != m_documentLoader);
1757 ASSERT(!loader || loader->frameLoader() == this);
1759 m_client->prepareForDataSourceReplacement();
1761 if (m_documentLoader)
1762 m_documentLoader->detachFromFrame();
1764 m_documentLoader = loader;
1766 // The following abomination is brought to you by the unload event.
1767 // The detachChildren() call above may trigger a child frame's unload event,
1768 // which could do something obnoxious like call document.write("") on
1769 // the main frame, which results in detaching children while detaching children.
1770 // This can cause the new m_documentLoader to be detached from its Frame*, but still
1771 // be alive. To make matters worse, DocumentLoaders with a null Frame* aren't supposed
1772 // to happen when they're still alive (and many places below us on the stack think the
1773 // DocumentLoader is still usable). Ergo, we reattach loader to its Frame, and pretend
1774 // like nothing ever happened.
1775 if (m_documentLoader && !m_documentLoader->frame()) {
1776 ASSERT(!m_documentLoader->isLoading());
1777 m_documentLoader->setFrame(m_frame);
1781 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1783 if (m_policyDocumentLoader == loader)
1788 loader->setFrame(m_frame);
1789 if (m_policyDocumentLoader
1790 && m_policyDocumentLoader != m_provisionalDocumentLoader
1791 && m_policyDocumentLoader != m_documentLoader)
1792 m_policyDocumentLoader->detachFromFrame();
1794 m_policyDocumentLoader = loader;
1797 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1799 ASSERT(!loader || !m_provisionalDocumentLoader);
1800 ASSERT(!loader || loader->frameLoader() == this);
1802 if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1803 m_provisionalDocumentLoader->detachFromFrame();
1805 m_provisionalDocumentLoader = loader;
1808 double FrameLoader::timeOfLastCompletedLoad()
1810 return storedTimeOfLastCompletedLoad;
1813 void FrameLoader::setState(FrameState newState)
1817 if (newState == FrameStateProvisional)
1818 provisionalLoadStarted();
1819 else if (newState == FrameStateComplete) {
1820 frameLoadCompleted();
1821 storedTimeOfLastCompletedLoad = currentTime();
1822 if (m_documentLoader)
1823 m_documentLoader->stopRecordingResponses();
1827 void FrameLoader::clearProvisionalLoad()
1829 setProvisionalDocumentLoader(0);
1830 if (Page* page = m_frame->page())
1831 page->progress()->progressCompleted(m_frame);
1832 setState(FrameStateComplete);
1835 void FrameLoader::commitProvisionalLoad()
1837 RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1838 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1840 LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1841 m_frame->document() ? m_frame->document()->url().string().utf8().data() : "",
1842 pdl ? pdl->url().string().utf8().data() : "<no provisional DocumentLoader>");
1844 // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1845 // We are doing this here because we know for sure that a new page is about to be loaded.
1846 HistoryItem* item = history()->currentItem();
1847 if (!m_frame->tree()->parent() && PageCache::canCache(m_frame->page()) && !item->isInPageCache())
1848 pageCache()->add(item, m_frame->page());
1850 if (m_loadType != FrameLoadTypeReplace)
1851 closeOldDataSources();
1853 if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1854 m_client->makeRepresentation(pdl.get());
1856 transitionToCommitted(cachedPage);
1859 // Check if the destination page is allowed to access the previous page's timing information.
1860 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1861 m_documentLoader->timing()->hasSameOriginAsPreviousDocument = securityOrigin->canRequest(m_previousUrl);
1864 // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1865 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
1866 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are
1867 // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1868 if (m_sentRedirectNotification)
1869 clientRedirectCancelledOrFinished(false);
1871 if (cachedPage && cachedPage->document()) {
1872 prepareForCachedPageRestore();
1873 cachedPage->restore(m_frame->page());
1875 dispatchDidCommitLoad();
1877 // If we have a title let the WebView know about it.
1878 StringWithDirection title = m_documentLoader->title();
1879 if (!title.isNull())
1880 m_client->dispatchDidReceiveTitle(title);
1886 LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1887 m_frame->document() ? m_frame->document()->url().string().utf8().data() : "");
1889 if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1890 history()->updateForClientRedirect();
1892 if (m_loadingFromCachedPage) {
1893 m_frame->document()->documentDidBecomeActive();
1895 // Force a layout to update view size and thereby update scrollbars.
1896 m_frame->view()->forceLayout();
1898 const ResponseVector& responses = m_documentLoader->responses();
1899 size_t count = responses.size();
1900 for (size_t i = 0; i < count; i++) {
1901 const ResourceResponse& response = responses[i];
1902 // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1903 ResourceError error;
1904 unsigned long identifier;
1905 ResourceRequest request(response.url());
1906 requestFromDelegate(request, identifier, error);
1907 // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1908 // However, with today's computers and networking speeds, this won't happen in practice.
1909 // Could be an issue with a giant local file.
1910 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1913 pageCache()->remove(history()->currentItem());
1915 m_documentLoader->setPrimaryLoadComplete(true);
1917 // FIXME: Why only this frame and not parent frames?
1918 checkLoadCompleteForThisFrame();
1922 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1924 ASSERT(m_client->hasWebView());
1925 ASSERT(m_state == FrameStateProvisional);
1927 if (m_state != FrameStateProvisional)
1930 if (m_frame->view())
1931 m_frame->view()->scrollAnimator()->cancelAnimations();
1933 m_client->setCopiesOnScroll();
1934 history()->updateForCommit();
1936 // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1937 // JavaScript. If the script initiates a new load, we need to abandon the current load,
1938 // or the two will stomp each other.
1939 DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1940 if (m_documentLoader)
1942 if (pdl != m_provisionalDocumentLoader)
1945 // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1946 if (m_documentLoader)
1947 m_documentLoader->stopLoadingSubresources();
1948 if (m_documentLoader)
1949 m_documentLoader->stopLoadingPlugIns();
1951 setDocumentLoader(m_provisionalDocumentLoader.get());
1952 setProvisionalDocumentLoader(0);
1953 setState(FrameStateCommittedPage);
1955 #if ENABLE(TOUCH_EVENTS)
1956 if (isLoadingMainFrame())
1957 m_frame->page()->chrome()->client()->needTouchEvents(false);
1960 // Handle adding the URL to the back/forward list.
1961 DocumentLoader* dl = m_documentLoader.get();
1963 switch (m_loadType) {
1964 case FrameLoadTypeForward:
1965 case FrameLoadTypeBack:
1966 case FrameLoadTypeIndexedBackForward:
1967 if (m_frame->page()) {
1968 // If the first load within a frame is a navigation within a back/forward list that was attached
1969 // without any of the items being loaded then we need to update the history in a similar manner as
1970 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1971 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1972 history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1974 history()->updateForBackForwardNavigation();
1976 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1977 if (history()->currentItem() && !cachedPage)
1978 m_pendingStateObject = history()->currentItem()->stateObject();
1980 // Create a document view for this document, or used the cached view.
1982 DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1983 ASSERT(cachedDocumentLoader);
1984 cachedDocumentLoader->setFrame(m_frame);
1985 m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1988 m_client->transitionToCommittedForNewPage();
1992 case FrameLoadTypeReload:
1993 case FrameLoadTypeReloadFromOrigin:
1994 case FrameLoadTypeSame:
1995 case FrameLoadTypeReplace:
1996 history()->updateForReload();
1997 m_client->transitionToCommittedForNewPage();
2000 case FrameLoadTypeStandard:
2001 history()->updateForStandardLoad();
2002 if (m_frame->view())
2003 m_frame->view()->setScrollbarsSuppressed(true);
2004 m_client->transitionToCommittedForNewPage();
2007 case FrameLoadTypeRedirectWithLockedBackForwardList:
2008 history()->updateForRedirectWithLockedBackForwardList();
2009 m_client->transitionToCommittedForNewPage();
2012 // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
2013 // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
2015 ASSERT_NOT_REACHED();
2018 m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
2020 // Tell the client we've committed this URL.
2021 ASSERT(m_frame->view());
2023 if (m_stateMachine.creatingInitialEmptyDocument())
2026 if (!m_stateMachine.committedFirstRealDocumentLoad())
2027 m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
2029 if (!m_client->hasHTMLView())
2030 receivedFirstData();
2033 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
2035 // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
2036 // the redirect succeeded. We should either rename this API, or add a new method, like
2037 // -webView:didFinishClientRedirectForFrame:
2038 m_client->dispatchDidCancelClientRedirect();
2040 if (!cancelWithLoadInProgress)
2041 m_quickRedirectComing = false;
2043 m_sentRedirectNotification = false;
2046 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
2048 m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
2050 // Remember that we sent a redirect notification to the frame load delegate so that when we commit
2051 // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
2052 m_sentRedirectNotification = true;
2054 // If a "quick" redirect comes in, we set a special mode so we treat the next
2055 // load as part of the original navigation. If we don't have a document loader, we have
2056 // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
2057 // Loads triggered by JavaScript form submissions never count as quick redirects.
2058 m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
2061 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
2063 // This function implements the rule: "Don't reload if navigating by fragment within
2064 // the same URL, but do reload if going to a new URL or to the same URL with no
2065 // fragment identifier at all."
2066 if (!destinationURL.hasFragmentIdentifier())
2068 return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
2071 void FrameLoader::closeOldDataSources()
2073 // FIXME: Is it important for this traversal to be postorder instead of preorder?
2074 // If so, add helpers for postorder traversal, and use them. If not, then lets not
2075 // use a recursive algorithm here.
2076 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
2077 child->loader()->closeOldDataSources();
2079 if (m_documentLoader)
2080 m_client->dispatchWillClose();
2082 m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2085 void FrameLoader::prepareForCachedPageRestore()
2087 ASSERT(!m_frame->tree()->parent());
2088 ASSERT(m_frame->page());
2089 ASSERT(m_frame->page()->mainFrame() == m_frame);
2091 m_frame->navigationScheduler()->cancel();
2093 // We still have to close the previous part page.
2096 // Delete old status bar messages (if it _was_ activated on last URL).
2097 if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
2098 if (DOMWindow* window = m_frame->existingDOMWindow()) {
2099 window->setStatus(String());
2100 window->setDefaultStatus(String());
2105 void FrameLoader::open(CachedFrameBase& cachedFrame)
2107 m_isComplete = false;
2109 // Don't re-emit the load event.
2110 m_didCallImplicitClose = true;
2112 KURL url = cachedFrame.url();
2114 // FIXME: I suspect this block of code doesn't do anything.
2115 if (url.protocolInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2118 m_hasReceivedFirstData = false;
2121 clear(true, true, cachedFrame.isMainFrame());
2123 Document* document = cachedFrame.document();
2125 document->setInPageCache(false);
2127 m_needsClear = true;
2128 m_isComplete = false;
2129 m_didCallImplicitClose = false;
2130 m_outgoingReferrer = url.string();
2132 FrameView* view = cachedFrame.view();
2134 // When navigating to a CachedFrame its FrameView should never be null. If it is we'll crash in creative ways downstream.
2136 view->setWasScrolledByUser(false);
2138 // Use the current ScrollView's frame rect.
2139 if (m_frame->view())
2140 view->setFrameRect(m_frame->view()->frameRect());
2141 m_frame->setView(view);
2143 m_frame->setDocument(document);
2144 m_frame->setDOMWindow(cachedFrame.domWindow());
2145 m_frame->domWindow()->setURL(document->url());
2146 m_frame->domWindow()->setSecurityOrigin(document->securityOrigin());
2148 updateFirstPartyForCookies();
2150 cachedFrame.restore();
2153 void FrameLoader::finishedLoading()
2155 // Retain because the stop may release the last reference to it.
2156 RefPtr<Frame> protect(m_frame);
2158 RefPtr<DocumentLoader> dl = activeDocumentLoader();
2159 dl->finishedLoading();
2160 if (!dl->mainDocumentError().isNull() || !dl->frameLoader())
2162 dl->setPrimaryLoadComplete(true);
2163 m_client->dispatchDidLoadMainResource(dl.get());
2164 checkLoadComplete();
2167 bool FrameLoader::isHostedByObjectElement() const
2169 HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2170 return owner && owner->hasTagName(objectTag);
2173 bool FrameLoader::isLoadingMainFrame() const
2175 Page* page = m_frame->page();
2176 return page && m_frame == page->mainFrame();
2179 void FrameLoader::finishedLoadingDocument(DocumentLoader* loader)
2181 if (m_stateMachine.creatingInitialEmptyDocument())
2184 #if !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
2185 m_client->finishedLoading(loader);
2187 // Give archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
2188 m_archive = ArchiveFactory::create(loader->response().url(), loader->mainResourceData().get(), loader->responseMIMEType());
2190 m_client->finishedLoading(loader);
2194 // FIXME: The remainder of this function should be moved to DocumentLoader.
2196 loader->addAllArchiveResources(m_archive.get());
2198 ArchiveResource* mainResource = m_archive->mainResource();
2199 loader->setParsedArchiveData(mainResource->data());
2201 loader->writer()->setMIMEType(mainResource->mimeType());
2206 ASSERT(m_frame->document());
2207 String userChosenEncoding = documentLoader()->overrideEncoding();
2208 bool encodingIsUserChosen = !userChosenEncoding.isNull();
2209 loader->writer()->setEncoding(encodingIsUserChosen ? userChosenEncoding : mainResource->textEncoding(), encodingIsUserChosen);
2210 loader->writer()->addData(mainResource->data()->data(), mainResource->data()->size());
2211 #endif // ENABLE(WEB_ARCHIVE)
2214 bool FrameLoader::isReplacing() const
2216 return m_loadType == FrameLoadTypeReplace;
2219 void FrameLoader::setReplacing()
2221 m_loadType = FrameLoadTypeReplace;
2224 bool FrameLoader::subframeIsLoading() const
2226 // It's most likely that the last added frame is the last to load so we walk backwards.
2227 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2228 FrameLoader* childLoader = child->loader();
2229 DocumentLoader* documentLoader = childLoader->documentLoader();
2230 if (documentLoader && documentLoader->isLoadingInAPISense())
2232 documentLoader = childLoader->provisionalDocumentLoader();
2233 if (documentLoader && documentLoader->isLoadingInAPISense())
2235 documentLoader = childLoader->policyDocumentLoader();
2242 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2244 m_client->willChangeTitle(loader);
2247 FrameLoadType FrameLoader::loadType() const
2252 CachePolicy FrameLoader::subresourceCachePolicy() const
2255 return CachePolicyVerify;
2257 if (m_loadType == FrameLoadTypeReloadFromOrigin)
2258 return CachePolicyReload;
2260 if (Frame* parentFrame = m_frame->tree()->parent()) {
2261 CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
2262 if (parentCachePolicy != CachePolicyVerify)
2263 return parentCachePolicy;
2266 if (m_loadType == FrameLoadTypeReload)
2267 return CachePolicyRevalidate;
2269 const ResourceRequest& request(documentLoader()->request());
2271 if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2272 return CachePolicyRevalidate;
2275 if (request.cachePolicy() == ReturnCacheDataElseLoad)
2276 return CachePolicyHistoryBuffer;
2278 return CachePolicyVerify;
2281 void FrameLoader::checkLoadCompleteForThisFrame()
2283 ASSERT(m_client->hasWebView());
2286 case FrameStateProvisional: {
2287 if (m_delegateIsHandlingProvisionalLoadError)
2290 RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2294 // If we've received any errors we may be stuck in the provisional state and actually complete.
2295 const ResourceError& error = pdl->mainDocumentError();
2299 // Check all children first.
2300 RefPtr<HistoryItem> item;
2301 if (Page* page = m_frame->page())
2302 if (isBackForwardLoadType(loadType()))
2303 // Reset the back forward list to the last committed history item at the top level.
2304 item = page->mainFrame()->loader()->history()->currentItem();
2306 // Only reset if we aren't already going to a new provisional item.
2307 bool shouldReset = !history()->provisionalItem();
2308 if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2309 m_delegateIsHandlingProvisionalLoadError = true;
2310 m_client->dispatchDidFailProvisionalLoad(error);
2311 m_delegateIsHandlingProvisionalLoadError = false;
2313 ASSERT(!pdl->isLoading());
2314 ASSERT(!pdl->isLoadingMainResource());
2315 ASSERT(!pdl->isLoadingSubresources());
2316 ASSERT(!pdl->isLoadingPlugIns());
2318 // If we're in the middle of loading multipart data, we need to restore the document loader.
2319 if (isReplacing() && !m_documentLoader.get())
2320 setDocumentLoader(m_provisionalDocumentLoader.get());
2322 // Finish resetting the load state, but only if another load hasn't been started by the
2323 // delegate callback.
2324 if (pdl == m_provisionalDocumentLoader)
2325 clearProvisionalLoad();
2326 else if (activeDocumentLoader()) {
2327 KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2328 if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2329 shouldReset = false;
2332 if (shouldReset && item)
2333 if (Page* page = m_frame->page()) {
2334 page->backForward()->setCurrentItem(item.get());
2335 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2340 case FrameStateCommittedPage: {
2341 DocumentLoader* dl = m_documentLoader.get();
2342 if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2345 setState(FrameStateComplete);
2347 // FIXME: Is this subsequent work important if we already navigated away?
2348 // Maybe there are bugs because of that, or extra work we can skip because
2349 // the new page is ready.
2351 m_client->forceLayoutForNonHTML();
2353 // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2354 if (m_frame->page()) {
2355 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2356 history()->restoreScrollPositionAndViewState();
2359 if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2362 if (Page* page = m_frame->page())
2363 page->progress()->progressCompleted(m_frame);
2365 const ResourceError& error = dl->mainDocumentError();
2366 if (!error.isNull())
2367 m_client->dispatchDidFailLoad(error);
2369 m_client->dispatchDidFinishLoad();
2374 case FrameStateComplete:
2375 frameLoadCompleted();
2379 ASSERT_NOT_REACHED();
2382 void FrameLoader::continueLoadAfterWillSubmitForm()
2384 if (!m_provisionalDocumentLoader)
2387 // DocumentLoader calls back to our prepareForLoadStart
2388 m_provisionalDocumentLoader->prepareForLoadStart();
2390 // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
2391 // so we need to null check it again.
2392 if (!m_provisionalDocumentLoader)
2395 DocumentLoader* activeDocLoader = activeDocumentLoader();
2396 if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2399 m_loadingFromCachedPage = false;
2401 unsigned long identifier = 0;
2403 if (Page* page = m_frame->page()) {
2404 identifier = page->progress()->createUniqueIdentifier();
2405 notifier()->assignIdentifierToInitialRequest(identifier, m_provisionalDocumentLoader.get(), m_provisionalDocumentLoader->originalRequest());
2408 ASSERT(!m_provisionalDocumentLoader->timing()->navigationStart);
2409 m_provisionalDocumentLoader->timing()->navigationStart = currentTime();
2411 if (!m_provisionalDocumentLoader->startLoadingMainResource(identifier))
2412 m_provisionalDocumentLoader->updateLoading();
2415 static KURL originatingURLFromBackForwardList(Page* page)
2417 // FIXME: Can this logic be replaced with m_frame->document()->firstPartyForCookies()?
2418 // It has the same meaning of "page a user thinks is the current one".
2421 int backCount = page->backForward()->backCount();
2422 for (int backIndex = 0; backIndex <= backCount; backIndex++) {
2423 // FIXME: At one point we had code here to check a "was user gesture" flag.
2424 // Do we need to restore that logic?
2425 HistoryItem* historyItem = page->backForward()->itemAtIndex(-backIndex);
2429 originalURL = historyItem->originalURL();
2430 if (!originalURL.isNull())
2437 void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
2441 // If there is no referrer, assume that the download was initiated directly, so current document is
2442 // completely unrelated to it. See <rdar://problem/5294691>.
2443 // FIXME: Referrer is not sent in many other cases, so we will often miss this important information.
2444 // Find a better way to decide whether the download was unrelated to current document.
2445 if (!request.httpReferrer().isNull()) {
2446 // find the first item in the history that was originated by the user
2447 originalURL = originatingURLFromBackForwardList(m_frame->page());
2450 if (originalURL.isNull())
2451 originalURL = request.url();
2453 if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
2454 unsigned port = originalURL.port();
2456 // Original URL is needed to show the user where a file was downloaded from. We should make a URL that won't result in downloading the file again.
2457 // FIXME: Using host-only URL is a very heavy-handed approach. We should attempt to provide the actual page where the download was initiated from, as a reminder to the user.
2458 String hostOnlyURLString;
2460 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ":", String::number(port));
2462 hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
2464 // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
2465 request.setFirstPartyForCookies(KURL(KURL(), hostOnlyURLString));
2469 void FrameLoader::didFirstLayout()
2471 if (m_frame->page() && isBackForwardLoadType(m_loadType))
2472 history()->restoreScrollPositionAndViewState();
2474 if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2475 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2477 m_client->dispatchDidFirstLayout();
2480 void FrameLoader::didFirstVisuallyNonEmptyLayout()
2482 m_client->dispatchDidFirstVisuallyNonEmptyLayout();
2485 void FrameLoader::frameLoadCompleted()
2487 // Note: Can be called multiple times.
2489 m_client->frameLoadCompleted();
2491 history()->updateForFrameLoadCompleted();
2493 // After a canceled provisional load, firstLayoutDone is false.
2494 // Reset it to true if we're displaying a page.
2495 if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2496 m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2499 void FrameLoader::detachChildren()
2501 typedef Vector<RefPtr<Frame> > FrameVector;
2502 FrameVector childrenToDetach;
2503 childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2504 for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2505 childrenToDetach.append(child);
2506 FrameVector::iterator end = childrenToDetach.end();
2507 for (FrameVector::iterator it = childrenToDetach.begin(); it != end; it++)
2508 (*it)->loader()->detachFromParent();
2511 void FrameLoader::closeAndRemoveChild(Frame* child)
2513 child->tree()->detachFromParent();
2516 if (child->ownerElement() && child->page())
2517 child->page()->decrementFrameCount();
2518 // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2519 child->pageDestroyed();
2521 m_frame->tree()->removeChild(child);
2524 // Called every time a resource is completely loaded or an error is received.
2525 void FrameLoader::checkLoadComplete()
2527 ASSERT(m_client->hasWebView());
2529 m_shouldCallCheckLoadComplete = false;
2531 // FIXME: Always traversing the entire frame tree is a bit inefficient, but
2532 // is currently needed in order to null out the previous history item for all frames.
2533 if (Page* page = m_frame->page()) {
2534 Vector<RefPtr<Frame>, 10> frames;
2535 for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2536 frames.append(frame);
2537 // To process children before their parents, iterate the vector backwards.
2538 for (size_t i = frames.size(); i; --i)
2539 frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
2543 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2546 return m_frame->document()->cachedResourceLoader()->requestCount();
2549 for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2550 count += frame->document()->cachedResourceLoader()->requestCount();
2554 String FrameLoader::userAgent(const KURL& url) const
2556 String userAgent = m_client->userAgent(url);
2557 InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2561 void FrameLoader::handledOnloadEvents()
2563 m_client->dispatchDidHandleOnloadEvents();
2565 if (documentLoader())
2566 documentLoader()->handledOnloadEvents();
2569 void FrameLoader::frameDetached()
2572 m_frame->document()->stopActiveDOMObjects();
2576 void FrameLoader::detachFromParent()
2578 RefPtr<Frame> protect(m_frame);
2581 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2583 // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2584 // will trigger the unload event handlers of any child frames, and those event
2585 // handlers might start a new subresource load in this frame.
2588 InspectorInstrumentation::frameDetachedFromParent(m_frame);
2590 detachViewsAndDocumentLoader();
2592 if (Frame* parent = m_frame->tree()->parent()) {
2593 parent->loader()->closeAndRemoveChild(m_frame);
2594 parent->loader()->scheduleCheckCompleted();
2596 m_frame->setView(0);
2597 // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2598 m_frame->pageDestroyed();
2602 void FrameLoader::detachViewsAndDocumentLoader()
2604 m_client->detachedFromParent2();
2605 setDocumentLoader(0);
2606 m_client->detachedFromParent3();
2609 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2611 addExtraFieldsToRequest(request, m_loadType, false);
2614 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2616 addExtraFieldsToRequest(request, m_loadType, true);
2619 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2621 // Don't set the cookie policy URL if it's already been set.
2622 // But make sure to set it on all requests, as it has significance beyond the cookie policy for all protocols (<rdar://problem/6616664>).
2623 if (request.firstPartyForCookies().isEmpty()) {
2624 if (mainResource && isLoadingMainFrame())
2625 request.setFirstPartyForCookies(request.url());
2626 else if (Document* document = m_frame->document())
2627 request.setFirstPartyForCookies(document->firstPartyForCookies());
2630 // The remaining modifications are only necessary for HTTP and HTTPS.
2631 if (!request.url().isEmpty() && !request.url().protocolInHTTPFamily())
2634 #if ENABLE(TIZEN_DOWNLOAD)
2635 String cookie = cookies(NULL, request.firstPartyForCookies());
2636 if (!cookie.isEmpty())
2637 request.setHTTPHeaderField("Cookie", cookie);
2640 applyUserAgent(request);
2641 #if ENABLE(TIZEN_CUSTOM_HEADERS)
2642 applyCustomHeaders(request, request.url());
2645 // If we inherit cache policy from a main resource, we use the DocumentLoader's
2646 // original request cache policy for two reasons:
2647 // 1. For POST requests, we mutate the cache policy for the main resource,
2648 // but we do not want this to apply to subresources
2649 // 2. Delegates that modify the cache policy using willSendRequest: should
2650 // not affect any other resources. Such changes need to be done
2652 if (!mainResource) {
2653 if (request.isConditional())
2654 request.setCachePolicy(ReloadIgnoringCacheData);
2655 else if (documentLoader()->isLoadingInAPISense())
2656 request.setCachePolicy(documentLoader()->originalRequest().cachePolicy());
2658 request.setCachePolicy(UseProtocolCachePolicy);
2659 } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2660 request.setCachePolicy(ReloadIgnoringCacheData);
2661 else if (isBackForwardLoadType(loadType) && m_stateMachine.committedFirstRealDocumentLoad())
2662 request.setCachePolicy(ReturnCacheDataElseLoad);
2664 if (request.cachePolicy() == ReloadIgnoringCacheData) {
2665 if (loadType == FrameLoadTypeReload)
2666 request.setHTTPHeaderField("Cache-Control", "max-age=0");
2667 else if (loadType == FrameLoadTypeReloadFromOrigin) {
2668 request.setHTTPHeaderField("Cache-Control", "no-cache");
2669 request.setHTTPHeaderField("Pragma", "no-cache");
2674 request.setHTTPAccept(defaultAcceptHeader);
2676 // Make sure we send the Origin header.
2677 addHTTPOriginIfNeeded(request, String());
2679 #if PLATFORM(MAC) || PLATFORM(WIN)
2680 // The Apple Mac and Windows ports have decided not to behave like other
2681 // browsers and instead use a quirky fallback array.
2682 // FIXME: We should remove this code once CFNetwork implements RFC 6266.
2683 Settings* settings = m_frame->settings();
2684 request.setResponseContentDispositionEncodingFallbackArray("UTF-8", activeDocumentLoader()->writer()->deprecatedFrameEncoding(), settings ? settings->defaultTextEncodingName() : String());
2688 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2690 if (!request.httpOrigin().isEmpty())
2691 return; // Request already has an Origin header.
2693 // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2694 // For example, if an intranet page has a hyperlink to an external web
2695 // site, we don't want to include the Origin of the request because it
2696 // will leak the internal host name. Similar privacy concerns have lead
2697 // to the widespread suppression of the Referer header at the network
2699 if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2702 // For non-GET and non-HEAD methods, always send an Origin header so the
2703 // server knows we support this feature.
2705 if (origin.isEmpty()) {
2706 // If we don't know what origin header to attach, we attach the value
2707 // for an empty origin.
2708 request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
2712 request.setHTTPOrigin(origin);
2715 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2717 RefPtr<FormState> formState = prpFormState;
2719 // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a
2720 // bunch of parameters that would come in here and then be built back up to a ResourceRequest. In case
2721 // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2722 // from scratch as it did all along.
2723 const KURL& url = inRequest.url();
2724 RefPtr<FormData> formData = inRequest.httpBody();
2725 const String& contentType = inRequest.httpContentType();
2726 String origin = inRequest.httpOrigin();
2728 ResourceRequest workingResourceRequest(url);
2730 if (!referrer.isEmpty())
2731 workingResourceRequest.setHTTPReferrer(referrer);
2732 workingResourceRequest.setHTTPOrigin(origin);
2733 workingResourceRequest.setHTTPMethod("POST");
2734 workingResourceRequest.setHTTPBody(formData);
2735 workingResourceRequest.setHTTPContentType(contentType);
2736 addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2738 NavigationAction action(workingResourceRequest, loadType, true, event);
2740 if (!frameName.isEmpty()) {
2741 // The search for a target frame is done earlier in the case of form submission.
2742 if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2743 targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2745 policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2747 loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2750 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2752 ASSERT(m_frame->document());
2753 String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), m_outgoingReferrer);
2755 ResourceRequest initialRequest = request;
2756 initialRequest.setTimeoutInterval(10);
2758 if (!referrer.isEmpty())
2759 initialRequest.setHTTPReferrer(referrer);
2760 addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2762 if (Page* page = m_frame->page())
2763 initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url());
2765 #if ENABLE(TIZEN_CUSTOM_HEADERS)
2766 applyCustomHeaders(initialRequest, request.url());
2769 addExtraFieldsToSubresourceRequest(initialRequest);
2771 unsigned long identifier = 0;
2772 ResourceRequest newRequest(initialRequest);
2773 requestFromDelegate(newRequest, identifier, error);
2775 if (error.isNull()) {
2776 ASSERT(!newRequest.isNull());
2778 if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2779 ResourceHandle::loadResourceSynchronously(networkingContext(), newRequest, storedCredentials, error, response, data);
2780 documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2783 int encodedDataLength = response.resourceLoadInfo() ? static_cast<int>(response.resourceLoadInfo()->encodedDataLength) : -1;
2784 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, data.data(), data.size(), encodedDataLength, error);
2788 const ResourceRequest& FrameLoader::originalRequest() const
2790 return activeDocumentLoader()->originalRequestCopy();
2793 void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isComplete)
2795 // Retain because the stop may release the last reference to it.
2796 RefPtr<Frame> protect(m_frame);
2798 RefPtr<DocumentLoader> loader = activeDocumentLoader();
2801 // FIXME: Don't want to do this if an entirely new load is going, so should check
2802 // that both data sources on the frame are either this or nil.
2804 if (m_client->shouldFallBack(error))
2805 handleFallbackContent();
2808 if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2809 if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2810 m_submittedFormURL = KURL();
2812 // We might have made a page cache item, but now we're bailing out due to an error before we ever
2813 // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state
2814 // so that the existing view (that wenever got far enough to replace) can continue being used.
2815 history()->invalidateCurrentItemCachedPage();
2817 // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2818 // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2819 // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2820 // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2822 if (m_sentRedirectNotification)
2823 clientRedirectCancelledOrFinished(false);
2826 loader->mainReceivedError(error, isComplete);
2829 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2830 const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2832 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2833 loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2836 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2838 m_quickRedirectComing = false;
2840 if (!shouldContinue)
2843 // If we have a provisional request for a different document, a fragment scroll should cancel it.
2844 if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
2845 m_provisionalDocumentLoader->stopLoading();
2846 setProvisionalDocumentLoader(0);
2849 bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;
2850 loadInSameDocument(request.url(), 0, !isRedirect);
2853 bool FrameLoader::shouldScrollToAnchor(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2855 // Should we do anchor navigation within the existing content?
2857 // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2858 // currently displaying a frameset, or if the URL does not have a fragment.
2859 // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2861 // FIXME: What about load types other than Standard and Reload?
2863 return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2864 && loadType != FrameLoadTypeReload
2865 && loadType != FrameLoadTypeReloadFromOrigin
2866 && loadType != FrameLoadTypeSame
2867 && !shouldReload(m_frame->document()->url(), url)
2868 // We don't want to just scroll if a link from within a
2869 // frameset is trying to reload the frameset into _top.
2870 && !m_frame->document()->isFrameSet();
2873 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2874 const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2876 FrameLoader* loader = static_cast<FrameLoader*>(argument);
2877 loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2880 bool FrameLoader::shouldClose()
2882 Page* page = m_frame->page();
2883 Chrome* chrome = page ? page->chrome() : 0;
2884 if (!chrome || !chrome->canRunBeforeUnloadConfirmPanel())
2887 // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2888 Vector<RefPtr<Frame> > targetFrames;
2889 targetFrames.append(m_frame);
2890 for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2891 targetFrames.append(child);
2893 bool shouldClose = false;
2895 NavigationDisablerForBeforeUnload navigationDisabler;
2898 for (i = 0; i < targetFrames.size(); i++) {
2899 if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2901 if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(chrome))
2905 if (i == targetFrames.size())
2910 m_submittedFormURL = KURL();
2915 bool FrameLoader::fireBeforeUnloadEvent(Chrome* chrome)
2917 DOMWindow* domWindow = m_frame->existingDOMWindow();
2921 RefPtr<Document> document = m_frame->document();
2922 if (!document->body())
2925 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2926 m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2927 domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2928 m_pageDismissalEventBeingDispatched = NoDismissal;
2930 if (!beforeUnloadEvent->defaultPrevented())
2931 document->defaultEventHandler(beforeUnloadEvent.get());
2932 if (beforeUnloadEvent->result().isNull())
2935 String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2936 return chrome->runBeforeUnloadConfirmPanel(text, m_frame);
2939 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2941 // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2942 // nil policyDataSource because loading the alternate page will have passed
2943 // through this method already, nested; otherwise, policyDataSource should still be set.
2944 ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2946 bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2948 // Two reasons we can't continue:
2949 // 1) Navigation policy delegate said we can't so request is nil. A primary case of this
2950 // is the user responding Cancel to the form repost nag sheet.
2951 // 2) User responded Cancel to an alert popped up by the before unload event handler.
2952 bool canContinue = shouldContinue && shouldClose();
2955 // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we
2956 // need to report that the client redirect was cancelled.
2957 if (m_quickRedirectComing)
2958 clientRedirectCancelledOrFinished(false);
2960 setPolicyDocumentLoader(0);
2962 // If the navigation request came from the back/forward menu, and we punt on it, we have the
2963 // problem that we have optimistically moved the b/f cursor already, so move it back. For sanity,
2964 // we only do this when punting a navigation for the target frame or top-level frame.
2965 if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2966 if (Page* page = m_frame->page()) {
2967 Frame* mainFrame = page->mainFrame();
2968 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem()) {
2969 page->backForward()->setCurrentItem(resetItem);
2970 m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2977 FrameLoadType type = policyChecker()->loadType();
2978 // A new navigation is in progress, so don't clear the history's provisional item.
2979 stopAllLoaders(ShouldNotClearProvisionalItem);
2981 // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2982 // might detach the current FrameLoader, in which case we should bail on this newly defunct load.
2983 if (!m_frame->page())
2986 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2987 if (Page* page = m_frame->page()) {
2988 if (page->mainFrame() == m_frame)
2989 m_frame->page()->inspectorController()->resume();
2993 setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2995 setState(FrameStateProvisional);
2997 setPolicyDocumentLoader(0);
2999 if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
3000 loadProvisionalItemFromCachedPage();
3005 m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
3007 continueLoadAfterWillSubmitForm();
3010 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
3011 const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
3013 FrameLoader* loader = static_cast<FrameLoader*>(argument);
3014 loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
3017 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
3018 PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
3020 if (!shouldContinue)
3023 RefPtr<Frame> frame = m_frame;
3024 RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
3028 if (frameName != "_blank")
3029 mainFrame->tree()->setName(frameName);
3031 mainFrame->page()->setOpenedByDOM();
3032 mainFrame->loader()->m_client->dispatchShow();
3033 if (!m_suppressOpenerInNewFrame)
3034 mainFrame->loader()->setOpener(frame.get());
3035 mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(request), false, FrameLoadTypeStandard, formState);
3038 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
3040 ASSERT(!request.isNull());
3043 if (Page* page = m_frame->page()) {
3044 identifier = page->progress()->createUniqueIdentifier();
3045 notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
3048 ResourceRequest newRequest(request);
3049 notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
3051 if (newRequest.isNull())
3052 error = cancelledError(request);
3054 error = ResourceError();
3056 request = newRequest;
3059 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource)
3061 Page* page = m_frame->page();
3065 if (!resource->sendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
3068 if (!page->areMemoryCacheClientCallsEnabled()) {
3069 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
3070 m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->url());
3071 m_documentLoader->didTellClientAboutLoad(resource->url());
3075 ResourceRequest request(resource->url());
3076 if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize())) {
3077 InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
3078 m_documentLoader->didTellClientAboutLoad(resource->url());
3082 unsigned long identifier;
3083 ResourceError error;
3084 requestFromDelegate(request, identifier, error);
3085 InspectorInstrumentation::markResourceAsCached(page, identifier);
3086 notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, resource->response(), 0, resource->encodedSize(), 0, error);
3089 void FrameLoader::applyUserAgent(ResourceRequest& request)
3091 String userAgent = this->userAgent(request.url());
3092 ASSERT(!userAgent.isNull());
3093 request.setHTTPUserAgent(userAgent);
3096 #if ENABLE(TIZEN_CUSTOM_HEADERS)
3097 void FrameLoader::applyCustomHeaders(ResourceRequest& request, const KURL& url)
3099 HTTPHeaderMap headers = client()->customHeaders(url);
3100 for ( HTTPHeaderMap::iterator i = headers.begin(); i != headers.end(); ++i )
3102 request.setHTTPHeaderField(i->first, i->second);
3107 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url)
3109 Frame* topFrame = m_frame->tree()->top();
3110 if (m_frame == topFrame)
3113 if (equalIgnoringCase(content, "deny"))
3116 if (equalIgnoringCase(content, "sameorigin")) {
3117 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
3118 if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
3125 void FrameLoader::loadProvisionalItemFromCachedPage()
3127 DocumentLoader* provisionalLoader = provisionalDocumentLoader();
3128 LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().string().utf8().data());
3130 provisionalLoader->prepareForLoadStart();
3132 m_loadingFromCachedPage = true;
3134 // Should have timing data from previous time(s) the page was shown.
3135 ASSERT(provisionalLoader->timing()->navigationStart);
3136 provisionalLoader->resetTiming();
3137 provisionalLoader->timing()->navigationStart = currentTime();
3139 provisionalLoader->setCommitted(true);
3140 commitProvisionalLoad();
3143 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
3145 if (!history()->currentItem())
3147 return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
3150 void FrameLoader::checkDidPerformFirstNavigation()
3152 Page* page = m_frame->page();
3156 if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3157 m_didPerformFirstNavigation = true;
3158 m_client->didPerformFirstNavigation();
3162 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name)
3164 Frame* frame = m_frame->tree()->find(name);
3165 if (!shouldAllowNavigation(frame))
3170 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3172 ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3174 // Save user view state to the current history item here since we don't do a normal load.
3175 // FIXME: Does form state need to be saved here too?
3176 history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3177 if (FrameView* view = m_frame->view())
3178 view->setWasScrolledByUser(false);
3180 history()->setCurrentItem(item);
3182 // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3183 loadInSameDocument(item->url(), item->stateObject(), false);
3185 // Restore user view state from the current history item here since we don't do a normal load.
3186 history()->restoreScrollPositionAndViewState();
3189 // FIXME: This function should really be split into a couple pieces, some of
3190 // which should be methods of HistoryController and some of which should be
3191 // methods of FrameLoader.
3192 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType)
3194 // Remember this item so we can traverse any child items as child frames load
3195 history()->setProvisionalItem(item);
3197 if (CachedPage* cachedPage = pageCache()->get(item)) {
3198 loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
3202 KURL itemURL = item->url();
3203 KURL itemOriginalURL = item->originalURL();
3205 if (documentLoader())
3206 currentURL = documentLoader()->url();
3207 RefPtr<FormData> formData = item->formData();
3209 ResourceRequest request(itemURL);
3211 if (!item->referrer().isNull())
3212 request.setHTTPReferrer(item->referrer());
3214 // If this was a repost that failed the page cache, we might try to repost the form.
3215 NavigationAction action;
3217 formData->generateFiles(m_frame->document());
3219 request.setHTTPMethod("POST");
3220 request.setHTTPBody(formData);
3221 request.setHTTPContentType(item->formContentType());
3222 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3223 addHTTPOriginIfNeeded(request, securityOrigin->toString());
3225 // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3226 // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3227 addExtraFieldsToRequest(request, m_loadType, true);
3229 // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3230 // We want to know this before talking to the policy delegate, since it affects whether
3231 // we show the DoYouReallyWantToRepost nag.
3233 // This trick has a small bug (3123893) where we might find a cache hit, but then
3234 // have the item vanish when we try to use it in the ensuing nav. This should be
3235 // extremely rare, but in that case the user will get an error on the navigation.
3237 if (ResourceHandle::willLoadFromCache(request, m_frame))
3238 action = NavigationAction(request, loadType, false);
3240 request.setCachePolicy(ReloadIgnoringCacheData);
3241 action = NavigationAction(request, NavigationTypeFormResubmitted);
3245 case FrameLoadTypeReload:
3246 case FrameLoadTypeReloadFromOrigin:
3247 request.setCachePolicy(ReloadIgnoringCacheData);
3249 case FrameLoadTypeBack:
3250 case FrameLoadTypeForward:
3251 case FrameLoadTypeIndexedBackForward:
3252 // If the first load within a frame is a navigation within a back/forward list that was attached
3253 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3254 if (m_stateMachine.committedFirstRealDocumentLoad() && !itemURL.protocolIs("https"))
3255 request.setCachePolicy(ReturnCacheDataElseLoad);
3257 case FrameLoadTypeStandard:
3258 case FrameLoadTypeRedirectWithLockedBackForwardList:
3260 case FrameLoadTypeSame:
3262 ASSERT_NOT_REACHED();
3265 addExtraFieldsToRequest(request, m_loadType, true);
3267 ResourceRequest requestForOriginalURL(request);
3268 requestForOriginalURL.setURL(itemOriginalURL);
3269 action = NavigationAction(requestForOriginalURL, loadType, false);
3272 loadWithNavigationAction(request, action, false, loadType, 0);
3275 // Loads content into this frame, as specified by history item
3276 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3278 HistoryItem* currentItem = history()->currentItem();
3279 bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3281 if (sameDocumentNavigation)
3282 loadSameDocumentItem(item);
3284 loadDifferentDocumentItem(item, loadType);
3287 void FrameLoader::mainReceivedCompleteError(DocumentLoader* loader, const ResourceError&)
3289 loader->setPrimaryLoadComplete(true);
3290 m_client->dispatchDidLoadMainResource(activeDocumentLoader());
3292 if (m_frame->page())
3293 checkLoadComplete();
3296 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3298 ResourceError error = m_client->cancelledError(request);
3299 error.setIsCancellation(true);
3303 void FrameLoader::setTitle(const StringWithDirection& title)
3305 documentLoader()->setTitle(title);
3308 String FrameLoader::referrer() const
3310 return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3313 void FrameLoader::dispatchDocumentElementAvailable()
3315 m_frame->injectUserScripts(InjectAtDocumentStart);
3316 m_client->documentElementAvailable();
3319 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3321 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3324 Vector<DOMWrapperWorld*> worlds;
3325 ScriptController::getAllWorlds(worlds);
3326 for (size_t i = 0; i < worlds.size(); ++i)
3327 dispatchDidClearWindowObjectInWorld(worlds[i]);
3330 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3332 if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3335 m_client->dispatchDidClearWindowObjectInWorld(world);
3337 #if ENABLE(INSPECTOR)
3338 if (Page* page = m_frame->page())
3339 page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3342 InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3345 SandboxFlags FrameLoader::effectiveSandboxFlags() const
3347 SandboxFlags flags = m_forcedSandboxFlags;
3348 if (Frame* parentFrame = m_frame->tree()->parent())
3349 flags |= parentFrame->document()->sandboxFlags();
3350 if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3351 flags |= ownerElement->sandboxFlags();
3355 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3357 m_client->didChangeTitle(loader);
3359 if (loader == m_documentLoader) {
3360 // Must update the entries in the back-forward list too.
3361 history()->setCurrentItemTitle(loader->title());
3362 // This must go through the WebFrame because it has the right notion of the current b/f item.
3363 m_client->setTitle(loader->title(), loader->urlForHistory());
3364 m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3365 m_client->dispatchDidReceiveTitle(loader->title());
3369 void FrameLoader::didChangeIcons(IconType type)
3371 m_client->dispatchDidChangeIcons(type);
3374 void FrameLoader::dispatchDidCommitLoad()
3376 if (m_stateMachine.creatingInitialEmptyDocument())
3379 m_client->dispatchDidCommitLoad();
3381 InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3384 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3386 ASSERT(m_frame->page());
3387 ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3389 if (!m_documentLoader)
3392 Vector<String> pastLoads;
3393 m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3395 size_t size = pastLoads.size();
3396 for (size_t i = 0; i < size; ++i) {
3397 CachedResource* resource = memoryCache()->resourceForURL(KURL(ParsedURLString, pastLoads[i]));
3399 // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3400 // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3401 // Consider if there's some efficient way of remembering enough to deliver this client call.
3402 // We have the URL, but not the rest of the response or the length.
3406 ResourceRequest request(resource->url());
3407 m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3411 NetworkingContext* FrameLoader::networkingContext() const
3413 return m_networkingContext.get();
3416 bool FrameLoaderClient::hasHTMLView() const
3421 Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3423 ASSERT(!features.dialog || request.frameName().isEmpty());
3425 if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3426 Frame* frame = lookupFrame->tree()->find(request.frameName());
3427 if (frame && openerFrame->loader()->shouldAllowNavigation(frame)) {
3428 if (Page* page = frame->page())
3429 page->chrome()->focus();
3435 // Sandboxed frames cannot open new auxiliary browsing contexts.
3436 if (isDocumentSandboxed(openerFrame, SandboxPopups))
3439 // FIXME: Setting the referrer should be the caller's responsibility.
3440 FrameLoadRequest requestWithReferrer = request;
3441 requestWithReferrer.resourceRequest().setHTTPReferrer(openerFrame->loader()->outgoingReferrer());
3442 FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
3444 Page* oldPage = openerFrame->page();
3448 NavigationAction action(requestWithReferrer.resourceRequest());
3449 Page* page = oldPage->chrome()->createWindow(openerFrame, requestWithReferrer, features, action);
3453 Frame* frame = page->mainFrame();
3455 frame->loader()->forceSandboxFlags(openerFrame->document()->sandboxFlags());
3457 if (request.frameName() != "_blank")
3458 frame->tree()->setName(request.frameName());
3460 page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3461 page->chrome()->setStatusbarVisible(features.statusBarVisible);
3462 page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
3463 page->chrome()->setMenubarVisible(features.menuBarVisible);
3464 page->chrome()->setResizable(features.resizable);
3466 // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3467 // specify the size of the page. We can only resize the window, so
3468 // adjust for the difference between the window size and the page size.
3470 FloatRect windowRect = page->chrome()->windowRect();
3471 FloatSize pageSize = page->chrome()->pageRect().size();
3473 windowRect.setX(features.x);
3475 windowRect.setY(features.y);
3476 if (features.widthSet)
3477 windowRect.setWidth(features.width + (windowRect.width() - pageSize.width()));
3478 if (features.heightSet)
3479 windowRect.setHeight(features.height + (windowRect.height() - pageSize.height()));
3480 page->chrome()->setWindowRect(windowRect);
3482 page->chrome()->show();
3488 } // namespace WebCore