This source file includes following definitions.
- isBackForwardLoadType
- needsHistoryItemRestore
- m_forcedSandboxFlags
- init
- setDefersLoading
- stopLoading
- markDocumentStateDirty
- saveDocumentState
- saveScrollState
- clearScrollPositionAndViewState
- closeURL
- didExplicitOpen
- clear
- setHistoryItemStateForCommit
- loadTypeToCommitType
- receivedFirstData
- didFailContentSecurityPolicyCheck
- didBeginDocument
- finishedParsing
- loadDone
- allChildrenAreComplete
- allAncestorsAreComplete
- checkCompleted
- checkTimerFired
- startCheckCompleteTimer
- scheduleCheckCompleted
- opener
- setOpener
- allowPlugins
- updateForSameDocumentNavigation
- loadInSameDocument
- completed
- started
- setReferrerForFrameRequest
- isScriptTriggeredFormSubmissionInChildFrame
- determineFrameLoadType
- prepareRequestForThisFrame
- shouldOpenInNewWindow
- load
- defaultSubstituteDataForURL
- reportLocalLoadFailed
- requestFromHistoryItem
- reload
- stopAllLoaders
- didAccessInitialDocument
- didAccessInitialDocumentTimerFired
- notifyIfInitialDocumentAccessed
- isLoading
- commitProvisionalLoad
- isLoadingMainFrame
- loadType
- isDocumentDoneLoading
- checkLoadCompleteForThisFrame
- restoreScrollPositionAndViewState
- detachChildren
- closeAndRemoveChild
- checkLoadComplete
- checkLoadComplete
- userAgent
- frameDetached
- detachFromParent
- detachClient
- addHTTPOriginIfNeeded
- receivedMainResourceError
- shouldPerformFragmentNavigation
- scrollToFragmentWithParentBoundary
- shouldClose
- loadWithNavigationAction
- applyUserAgent
- shouldInterruptLoadForXFrameOptions
- shouldTreatURLAsSameAsCurrent
- shouldTreatURLAsSrcdocDocument
- findFrameForNavigation
- loadHistoryItem
- dispatchDocumentElementAvailable
- dispatchDidClearWindowObjectsInAllWorlds
- dispatchDidClearWindowObjectInWorld
- effectiveSandboxFlags
#include "config.h"
#include "core/loader/FrameLoader.h"
#include "HTMLNames.h"
#include "bindings/v8/DOMWrapperWorld.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/SerializedScriptValue.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/editing/Editor.h"
#include "core/editing/UndoStack.h"
#include "core/events/Event.h"
#include "core/events/PageTransitionEvent.h"
#include "core/fetch/FetchContext.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/DocumentLoadTiming.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FormState.h"
#include "core/loader/FormSubmission.h"
#include "core/loader/FrameFetchContext.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/ProgressTracker.h"
#include "core/loader/UniqueIdentifier.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
#include "core/page/BackForwardClient.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/CreateWindow.h"
#include "core/page/EventHandler.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
#include "core/frame/Settings.h"
#include "core/page/WindowFeatures.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/xml/parser/XMLDocumentParser.h"
#include "platform/Logging.h"
#include "platform/UserGestureIndicator.h"
#include "platform/geometry/FloatRect.h"
#include "platform/network/ContentSecurityPolicyResponseHeaders.h"
#include "platform/network/HTTPParsers.h"
#include "platform/network/ResourceRequest.h"
#include "platform/scroll/ScrollAnimator.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/weborigin/SecurityPolicy.h"
#include "wtf/TemporaryChange.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
using namespace HTMLNames;
bool isBackForwardLoadType(FrameLoadType type)
{
return type == FrameLoadTypeBackForward;
}
static bool needsHistoryItemRestore(FrameLoadType type)
{
return type == FrameLoadTypeBackForward || type == FrameLoadTypeReload || type == FrameLoadTypeReloadFromOrigin;
}
FrameLoader::FrameLoader(LocalFrame* frame, FrameLoaderClient* client)
: m_frame(frame)
, m_client(client)
, m_mixedContentChecker(frame)
, m_progressTracker(ProgressTracker::create(frame))
, m_state(FrameStateProvisional)
, m_loadType(FrameLoadTypeStandard)
, m_fetchContext(FrameFetchContext::create(frame))
, m_inStopAllLoaders(false)
, m_isComplete(false)
, m_checkTimer(this, &FrameLoader::checkTimerFired)
, m_shouldCallCheckCompleted(false)
, m_didAccessInitialDocument(false)
, m_didAccessInitialDocumentTimer(this, &FrameLoader::didAccessInitialDocumentTimerFired)
, m_forcedSandboxFlags(SandboxNone)
{
}
FrameLoader::~FrameLoader()
{
}
void FrameLoader::init()
{
m_provisionalDocumentLoader = m_client->createDocumentLoader(m_frame, ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData());
m_provisionalDocumentLoader->startLoadingMainResource();
m_frame->document()->cancelParsing();
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
}
void FrameLoader::setDefersLoading(bool defers)
{
if (m_documentLoader)
m_documentLoader->setDefersLoading(defers);
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setDefersLoading(defers);
if (m_policyDocumentLoader)
m_policyDocumentLoader->setDefersLoading(defers);
if (!defers) {
if (m_deferredHistoryLoad.isValid()) {
loadHistoryItem(m_deferredHistoryLoad.m_item.get(), m_deferredHistoryLoad.m_type, m_deferredHistoryLoad.m_cachePolicy);
m_deferredHistoryLoad = DeferredHistoryLoad();
}
m_frame->navigationScheduler().startTimer();
startCheckCompleteTimer();
}
}
void FrameLoader::stopLoading()
{
m_isComplete = true;
if (m_frame->document() && m_frame->document()->parsing()) {
finishedParsing();
m_frame->document()->setParsing(false);
}
if (Document* doc = m_frame->document()) {
doc->setReadyState(Document::Complete);
}
m_frame->navigationScheduler().cancel();
}
void FrameLoader::markDocumentStateDirty()
{
Document* document = m_frame->document();
document->setHistoryItemDocumentStateDirty(true);
m_client->didUpdateCurrentHistoryItem();
}
void FrameLoader::saveDocumentState()
{
Document* document = m_frame->document();
if (!m_currentItem || !document->historyItemDocumentStateDirty())
return;
if (m_currentItem->isCurrentDocument(document) && document->isActive())
m_currentItem->setDocumentState(document->formElementsState());
document->setHistoryItemDocumentStateDirty(false);
}
void FrameLoader::saveScrollState()
{
if (!m_currentItem || !m_frame->view())
return;
if (needsHistoryItemRestore(m_loadType) && !m_frame->view()->wasScrolledByUser())
return;
m_currentItem->setScrollPoint(m_frame->view()->scrollPosition());
if (m_frame->isMainFrame() && !m_frame->page()->inspectorController().deviceEmulationEnabled())
m_currentItem->setPageScaleFactor(m_frame->page()->pageScaleFactor());
m_client->didUpdateCurrentHistoryItem();
}
void FrameLoader::clearScrollPositionAndViewState()
{
ASSERT(m_frame->isMainFrame());
if (!m_currentItem)
return;
m_currentItem->clearScrollPoint();
m_currentItem->setPageScaleFactor(0);
}
bool FrameLoader::closeURL()
{
saveDocumentState();
saveScrollState();
if (m_frame->document())
m_frame->document()->dispatchUnloadEvents();
stopLoading();
if (Page* page = m_frame->page())
page->undoStack().didUnloadFrame(*m_frame);
return true;
}
void FrameLoader::didExplicitOpen()
{
m_isComplete = false;
if (!m_stateMachine.committedFirstRealDocumentLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
m_frame->navigationScheduler().cancel();
}
void FrameLoader::clear()
{
if (m_stateMachine.creatingInitialEmptyDocument())
return;
m_frame->editor().clear();
m_frame->document()->cancelParsing();
m_frame->document()->prepareForDestruction();
m_frame->document()->removeFocusedElementOfSubtree(m_frame->document());
m_frame->selection().prepareForDestruction();
m_frame->eventHandler().clear();
if (m_frame->view())
m_frame->view()->clear();
m_frame->script().enableEval();
m_frame->navigationScheduler().clear();
m_checkTimer.stop();
m_shouldCallCheckCompleted = false;
if (m_stateMachine.isDisplayingInitialEmptyDocument())
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
}
void FrameLoader::setHistoryItemStateForCommit(HistoryCommitType historyCommitType, bool isPushOrReplaceState, PassRefPtr<SerializedScriptValue> stateObject)
{
if (m_provisionalItem)
m_currentItem = m_provisionalItem.release();
if (!m_currentItem || historyCommitType == StandardCommit)
m_currentItem = HistoryItem::create();
else if (!isPushOrReplaceState && m_documentLoader->url() != m_currentItem->url())
m_currentItem->generateNewSequenceNumbers();
m_currentItem->setURL(m_documentLoader->urlForHistory());
m_currentItem->setTarget(m_frame->tree().uniqueName());
if (isPushOrReplaceState)
m_currentItem->setStateObject(stateObject);
m_currentItem->setReferrer(Referrer(m_documentLoader->request().httpReferrer(), m_documentLoader->request().referrerPolicy()));
m_currentItem->setFormInfoFromRequest(isPushOrReplaceState ? ResourceRequest() : m_documentLoader->request());
}
static HistoryCommitType loadTypeToCommitType(FrameLoadType type, bool isValidHistoryURL)
{
switch (type) {
case FrameLoadTypeStandard:
return isValidHistoryURL ? StandardCommit : HistoryInertCommit;
case FrameLoadTypeInitialInChildFrame:
return InitialCommitInChildFrame;
case FrameLoadTypeBackForward:
return BackForwardCommit;
default:
break;
}
return HistoryInertCommit;
}
void FrameLoader::receivedFirstData()
{
if (m_stateMachine.creatingInitialEmptyDocument())
return;
bool isValidHistoryURL = !m_documentLoader->urlForHistory().isEmpty() && (!opener() || m_currentItem || !m_documentLoader->originalRequest().url().isEmpty());
HistoryCommitType historyCommitType = loadTypeToCommitType(m_loadType, isValidHistoryURL);
setHistoryItemStateForCommit(historyCommitType);
if (!m_stateMachine.committedMultipleRealLoads() && m_loadType == FrameLoadTypeStandard)
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedMultipleRealLoads);
m_client->dispatchDidCommitLoad(m_frame, m_currentItem.get(), historyCommitType);
InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
m_frame->page()->didCommitLoad(m_frame);
dispatchDidClearWindowObjectsInAllWorlds();
}
static void didFailContentSecurityPolicyCheck(FrameLoader* loader)
{
RefPtr<LocalFrame> frame(loader->frame());
frame->document()->enforceSandboxFlags(SandboxOrigin);
loader->stopAllLoaders();
if (HTMLFrameOwnerElement* ownerElement = frame->ownerElement())
ownerElement->dispatchEvent(Event::create(EventTypeNames::load));
}
void FrameLoader::didBeginDocument(bool dispatch)
{
m_isComplete = false;
m_frame->document()->setReadyState(Document::Loading);
if (m_provisionalItem && m_loadType == FrameLoadTypeBackForward)
m_frame->domWindow()->statePopped(m_provisionalItem->stateObject());
if (dispatch)
dispatchDidClearWindowObjectsInAllWorlds();
m_frame->document()->initContentSecurityPolicy(m_documentLoader ? ContentSecurityPolicyResponseHeaders(m_documentLoader->response()) : ContentSecurityPolicyResponseHeaders());
if (!m_frame->document()->contentSecurityPolicy()->allowAncestors(m_frame)) {
didFailContentSecurityPolicyCheck(this);
return;
}
Settings* settings = m_frame->document()->settings();
if (settings) {
m_frame->document()->fetcher()->setImagesEnabled(settings->imagesEnabled());
m_frame->document()->fetcher()->setAutoLoadImages(settings->loadsImagesAutomatically());
}
if (m_documentLoader) {
const AtomicString& dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
if (!dnsPrefetchControl.isEmpty())
m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
String headerContentLanguage = m_documentLoader->response().httpHeaderField("Content-Language");
if (!headerContentLanguage.isEmpty()) {
size_t commaIndex = headerContentLanguage.find(',');
headerContentLanguage.truncate(commaIndex);
headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace<UChar>);
if (!headerContentLanguage.isEmpty())
m_frame->document()->setContentLanguage(AtomicString(headerContentLanguage));
}
}
if (m_provisionalItem && m_loadType == FrameLoadTypeBackForward)
m_frame->document()->setStateForNewFormElements(m_provisionalItem->documentState());
}
void FrameLoader::finishedParsing()
{
if (m_stateMachine.creatingInitialEmptyDocument())
return;
RefPtr<LocalFrame> protector = m_frame->view() ? m_frame : 0;
if (m_client)
m_client->dispatchDidFinishDocumentLoad();
checkCompleted();
if (!m_frame->view())
return;
m_frame->view()->restoreScrollbar();
scrollToFragmentWithParentBoundary(m_frame->document()->url());
}
void FrameLoader::loadDone()
{
checkCompleted();
}
bool FrameLoader::allChildrenAreComplete() const
{
for (LocalFrame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->loader().m_isComplete)
return false;
}
return true;
}
bool FrameLoader::allAncestorsAreComplete() const
{
for (LocalFrame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
if (!ancestor->document()->loadEventFinished())
return false;
}
return true;
}
void FrameLoader::checkCompleted()
{
RefPtr<LocalFrame> protect(m_frame);
m_shouldCallCheckCompleted = false;
if (m_frame->view())
m_frame->view()->handleLoadCompleted();
if (m_isComplete)
return;
if (m_frame->document()->parsing())
return;
if (!m_frame->document()->haveImportsLoaded())
return;
if (m_frame->document()->fetcher()->requestCount())
return;
if (m_frame->document()->isDelayingLoadEvent())
return;
if (!allChildrenAreComplete())
return;
m_isComplete = true;
m_frame->document()->setReadyState(Document::Complete);
if (m_frame->document()->loadEventStillNeeded())
m_frame->document()->implicitClose();
m_frame->navigationScheduler().startTimer();
completed();
if (m_frame->page())
checkLoadComplete();
if (m_frame->view())
m_frame->view()->handleLoadCompleted();
}
void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
{
RefPtr<LocalFrame> protect(m_frame);
if (Page* page = m_frame->page()) {
if (page->defersLoading())
return;
}
if (m_shouldCallCheckCompleted)
checkCompleted();
}
void FrameLoader::startCheckCompleteTimer()
{
if (!m_shouldCallCheckCompleted)
return;
if (m_checkTimer.isActive())
return;
m_checkTimer.startOneShot(0, FROM_HERE);
}
void FrameLoader::scheduleCheckCompleted()
{
m_shouldCallCheckCompleted = true;
startCheckCompleteTimer();
}
LocalFrame* FrameLoader::opener()
{
return m_client ? toLocalFrame(m_client->opener()) : 0;
}
void FrameLoader::setOpener(LocalFrame* opener)
{
if (m_client)
m_client->setOpener(opener);
}
bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
{
Settings* settings = m_frame->settings();
bool allowed = m_client->allowPlugins(settings && settings->pluginsEnabled());
if (!allowed && reason == AboutToInstantiatePlugin)
m_client->didNotAllowPlugins();
return allowed;
}
void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, UpdateBackForwardListPolicy updateBackForwardList)
{
m_frame->document()->setURL(newURL);
documentLoader()->updateForSameDocumentNavigation(newURL);
if (m_frame->document()->loadEventFinished())
m_client->didStartLoading(NavigationWithinSameDocument);
HistoryCommitType historyCommitType = updateBackForwardList == UpdateBackForwardList && m_currentItem ? StandardCommit : HistoryInertCommit;
setHistoryItemStateForCommit(historyCommitType, sameDocumentNavigationSource == SameDocumentNavigationHistoryApi, data);
m_client->dispatchDidNavigateWithinPage(m_currentItem.get(), historyCommitType);
m_client->dispatchDidReceiveTitle(m_frame->document()->title());
if (m_frame->document()->loadEventFinished())
m_client->didStopLoading();
}
void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, UpdateBackForwardListPolicy updateBackForwardList, ClientRedirectPolicy clientRedirect)
{
ASSERT(!stateObject || updateBackForwardList == DoNotUpdateBackForwardList);
if (m_provisionalDocumentLoader) {
m_provisionalDocumentLoader->stopLoading();
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = nullptr;
}
saveDocumentState();
saveScrollState();
KURL oldURL = m_frame->document()->url();
bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
if (hashChange) {
m_frame->eventHandler().stopAutoscroll();
m_frame->domWindow()->enqueueHashchangeEvent(oldURL, url);
}
m_documentLoader->setIsClientRedirect(clientRedirect == ClientRedirect);
bool replacesCurrentHistoryItem = updateBackForwardList == DoNotUpdateBackForwardList;
m_documentLoader->setReplacesCurrentHistoryItem(replacesCurrentHistoryItem);
updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, nullptr, updateBackForwardList);
m_frame->view()->setWasScrolledByUser(false);
started();
scrollToFragmentWithParentBoundary(url);
m_isComplete = false;
checkCompleted();
m_frame->domWindow()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
}
void FrameLoader::completed()
{
RefPtr<LocalFrame> protect(m_frame);
for (LocalFrame* descendant = m_frame->tree().traverseNext(m_frame); descendant; descendant = descendant->tree().traverseNext(m_frame))
descendant->navigationScheduler().startTimer();
if (LocalFrame* parent = m_frame->tree().parent())
parent->loader().checkCompleted();
if (m_frame->view())
m_frame->view()->maintainScrollPositionAtAnchor(0);
}
void FrameLoader::started()
{
for (LocalFrame* frame = m_frame; frame; frame = frame->tree().parent())
frame->loader().m_isComplete = false;
}
void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer, Document* originDocument)
{
if (shouldSendReferrer == NeverSendReferrer) {
request.clearHTTPReferrer();
return;
}
String argsReferrer(request.httpReferrer());
if (argsReferrer.isEmpty())
argsReferrer = originDocument->outgoingReferrer();
String referrer = SecurityPolicy::generateReferrerHeader(originDocument->referrerPolicy(), request.url(), argsReferrer);
request.setHTTPReferrer(Referrer(referrer, originDocument->referrerPolicy()));
RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
addHTTPOriginIfNeeded(request, referrerOrigin->toAtomicString());
}
bool FrameLoader::isScriptTriggeredFormSubmissionInChildFrame(const FrameLoadRequest& request) const
{
if (!m_frame->tree().parent() || UserGestureIndicator::processingUserGesture())
return false;
return request.formState() && request.formState()->formSubmissionTrigger() == SubmittedByJavaScript;
}
FrameLoadType FrameLoader::determineFrameLoadType(const FrameLoadRequest& request)
{
if (m_frame->tree().parent() && !m_stateMachine.startedFirstRealLoad())
return FrameLoadTypeInitialInChildFrame;
if (!m_frame->tree().parent() && !m_frame->page()->backForward().backForwardListCount())
return FrameLoadTypeStandard;
if (m_provisionalDocumentLoader && request.substituteData().failingURL() == m_provisionalDocumentLoader->url() && m_loadType == FrameLoadTypeBackForward)
return FrameLoadTypeBackForward;
if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
return FrameLoadTypeReload;
if (request.lockBackForwardList() || isScriptTriggeredFormSubmissionInChildFrame(request))
return FrameLoadTypeRedirectWithLockedBackForwardList;
if (!request.originDocument() && request.resourceRequest().url() == m_documentLoader->urlForHistory())
return FrameLoadTypeSame;
if (request.substituteData().failingURL() == m_documentLoader->urlForHistory() && m_loadType == FrameLoadTypeReload)
return FrameLoadTypeReload;
return FrameLoadTypeStandard;
}
bool FrameLoader::prepareRequestForThisFrame(FrameLoadRequest& request)
{
if (!request.originDocument())
return true;
KURL url = request.resourceRequest().url();
if (m_frame->script().executeScriptIfJavaScriptURL(url))
return false;
if (!request.originDocument()->securityOrigin()->canDisplay(url)) {
reportLocalLoadFailed(m_frame, url.elidedString());
return false;
}
if (!request.formState() && request.frameName().isEmpty())
request.setFrameName(m_frame->document()->baseTarget());
setReferrerForFrameRequest(request.resourceRequest(), request.shouldSendReferrer(), request.originDocument());
return true;
}
static bool shouldOpenInNewWindow(LocalFrame* targetFrame, const FrameLoadRequest& request, const NavigationAction& action)
{
if (!targetFrame && !request.frameName().isEmpty())
return true;
return request.formState() && action.shouldOpenInNewWindow();
}
void FrameLoader::load(const FrameLoadRequest& passedRequest)
{
ASSERT(m_frame->document());
RefPtr<LocalFrame> protect(m_frame);
if (m_inStopAllLoaders)
return;
FrameLoadRequest request(passedRequest);
if (!prepareRequestForThisFrame(request))
return;
RefPtr<LocalFrame> targetFrame = request.formState() ? 0 : findFrameForNavigation(AtomicString(request.frameName()), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
if (targetFrame && targetFrame != m_frame) {
request.setFrameName("_self");
targetFrame->loader().load(request);
if (Page* page = targetFrame->page())
page->chrome().focus();
return;
}
FrameLoadType newLoadType = determineFrameLoadType(request);
NavigationAction action(request.resourceRequest(), newLoadType, request.formState(), request.triggeringEvent());
if (shouldOpenInNewWindow(targetFrame.get(), request, action)) {
if (action.policy() == NavigationPolicyDownload)
m_client->loadURLExternally(action.resourceRequest(), NavigationPolicyDownload);
else
createWindowForRequest(request, *m_frame, action.policy(), request.shouldSendReferrer());
return;
}
const KURL& url = request.resourceRequest().url();
if (!action.shouldOpenInNewWindow() && shouldPerformFragmentNavigation(request.formState(), request.resourceRequest().httpMethod(), newLoadType, url)) {
m_documentLoader->setTriggeringAction(action);
loadInSameDocument(url, nullptr, newLoadType == FrameLoadTypeStandard && !shouldTreatURLAsSameAsCurrent(url) ? UpdateBackForwardList : DoNotUpdateBackForwardList, request.clientRedirect());
return;
}
bool sameURL = url == m_documentLoader->urlForHistory();
loadWithNavigationAction(action, newLoadType, request.formState(), request.substituteData(), request.clientRedirect());
if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin && request.resourceRequest().httpMethod() != "POST")
m_loadType = FrameLoadTypeSame;
}
SubstituteData FrameLoader::defaultSubstituteDataForURL(const KURL& url)
{
if (!shouldTreatURLAsSrcdocDocument(url))
return SubstituteData();
String srcdoc = m_frame->ownerElement()->fastGetAttribute(srcdocAttr);
ASSERT(!srcdoc.isNull());
CString encodedSrcdoc = srcdoc.utf8();
return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL());
}
void FrameLoader::reportLocalLoadFailed(LocalFrame* frame, const String& url)
{
ASSERT(!url.isEmpty());
if (!frame)
return;
frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
}
static ResourceRequest requestFromHistoryItem(HistoryItem* item, ResourceRequestCachePolicy cachePolicy)
{
RefPtr<FormData> formData = item->formData();
ResourceRequest request(item->url(), item->referrer());
request.setCachePolicy(cachePolicy);
if (formData) {
request.setHTTPMethod("POST");
request.setHTTPBody(formData);
request.setHTTPContentType(item->formContentType());
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer().referrer);
FrameLoader::addHTTPOriginIfNeeded(request, securityOrigin->toAtomicString());
}
return request;
}
void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, const AtomicString& overrideEncoding)
{
if (!m_currentItem)
return;
ResourceRequest request = requestFromHistoryItem(m_currentItem.get(), ReloadIgnoringCacheData);
if (!overrideURL.isEmpty()) {
request.setURL(overrideURL);
request.clearHTTPReferrer();
}
FrameLoadType type = reloadPolicy == EndToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload;
loadWithNavigationAction(NavigationAction(request, type), type, nullptr, SubstituteData(), NotClientRedirect, overrideEncoding);
}
void FrameLoader::stopAllLoaders()
{
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
if (m_inStopAllLoaders)
return;
RefPtr<LocalFrame> protect(m_frame);
m_inStopAllLoaders = true;
for (RefPtr<LocalFrame> child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
child->loader().stopAllLoaders();
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->stopLoading();
if (m_documentLoader)
m_documentLoader->stopLoading();
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = nullptr;
m_checkTimer.stop();
m_inStopAllLoaders = false;
if (m_client)
m_client->didStopAllLoaders();
}
void FrameLoader::didAccessInitialDocument()
{
if (isLoadingMainFrame() && !m_didAccessInitialDocument) {
m_didAccessInitialDocument = true;
m_didAccessInitialDocumentTimer.startOneShot(0, FROM_HERE);
}
}
void FrameLoader::didAccessInitialDocumentTimerFired(Timer<FrameLoader>*)
{
m_client->didAccessInitialDocument();
}
void FrameLoader::notifyIfInitialDocumentAccessed()
{
if (m_didAccessInitialDocumentTimer.isActive()) {
m_didAccessInitialDocumentTimer.stop();
didAccessInitialDocumentTimerFired(0);
}
}
bool FrameLoader::isLoading() const
{
if (m_provisionalDocumentLoader)
return true;
return m_documentLoader && m_documentLoader->isLoading();
}
void FrameLoader::commitProvisionalLoad()
{
ASSERT(m_client->hasWebView());
ASSERT(m_state == FrameStateProvisional);
RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
RefPtr<LocalFrame> protect(m_frame);
if (m_frame->document()) {
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
pdl->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_frame->document()->url()));
}
if (m_documentLoader) {
m_client->dispatchWillClose();
closeURL();
}
detachChildren();
if (pdl != m_provisionalDocumentLoader)
return;
if (m_documentLoader)
m_documentLoader->detachFromFrame();
m_documentLoader = m_provisionalDocumentLoader.release();
m_state = FrameStateCommittedPage;
if (isLoadingMainFrame())
m_frame->page()->chrome().client().needTouchEvents(false);
m_client->transitionToCommittedForNewPage();
m_frame->navigationScheduler().cancel();
m_frame->editor().clearLastEditCommand();
if (!m_stateMachine.creatingInitialEmptyDocument()) {
DOMWindow* window = m_frame->domWindow();
window->setStatus(String());
window->setDefaultStatus(String());
}
started();
}
bool FrameLoader::isLoadingMainFrame() const
{
return m_frame->isMainFrame();
}
FrameLoadType FrameLoader::loadType() const
{
return m_loadType;
}
static bool isDocumentDoneLoading(Document* document)
{
if (!document->loader())
return true;
if (document->loader()->isLoadingMainResource())
return false;
if (!document->loadEventFinished()) {
if (document->loader()->isLoading() || document->isDelayingLoadEvent())
return false;
}
if (document->fetcher()->requestCount())
return false;
if (document->processingLoadEvent())
return false;
if (document->hasActiveParser())
return false;
return true;
}
bool FrameLoader::checkLoadCompleteForThisFrame()
{
ASSERT(m_client->hasWebView());
RefPtr<LocalFrame> protect(m_frame);
if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
const ResourceError& error = m_provisionalDocumentLoader->mainDocumentError();
if (error.isNull())
return false;
RefPtr<DocumentLoader> loader = m_provisionalDocumentLoader;
m_client->dispatchDidFailProvisionalLoad(error);
if (loader != m_provisionalDocumentLoader)
return false;
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = nullptr;
m_progressTracker->progressCompleted();
m_state = FrameStateComplete;
return true;
}
bool allChildrenAreDoneLoading = true;
for (LocalFrame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
allChildrenAreDoneLoading &= child->loader().checkLoadCompleteForThisFrame();
if (!allChildrenAreDoneLoading)
return false;
if (m_state == FrameStateComplete)
return true;
if (m_provisionalDocumentLoader || !m_documentLoader)
return false;
if (!isDocumentDoneLoading(m_frame->document()) && !m_inStopAllLoaders)
return false;
m_state = FrameStateComplete;
restoreScrollPositionAndViewState();
if (!m_stateMachine.committedFirstRealDocumentLoad())
return true;
m_progressTracker->progressCompleted();
const ResourceError& error = m_documentLoader->mainDocumentError();
if (!error.isNull())
m_client->dispatchDidFailLoad(error);
else
m_client->dispatchDidFinishLoad();
m_loadType = FrameLoadTypeStandard;
return true;
}
void FrameLoader::restoreScrollPositionAndViewState()
{
FrameView* view = m_frame->view();
if (!m_frame->page() || !view || !m_currentItem || !m_stateMachine.committedFirstRealDocumentLoad())
return;
if (!needsHistoryItemRestore(m_loadType))
return;
bool canRestoreWithoutClamping = view->clampOffsetAtScale(m_currentItem->scrollPoint(), m_currentItem->pageScaleFactor()) == m_currentItem->scrollPoint();
bool canRestoreWithoutAnnoyingUser = !view->wasScrolledByUser() && (canRestoreWithoutClamping || m_state == FrameStateComplete);
if (!canRestoreWithoutAnnoyingUser)
return;
if (m_frame->isMainFrame() && m_currentItem->pageScaleFactor())
m_frame->page()->setPageScaleFactor(m_currentItem->pageScaleFactor(), m_currentItem->scrollPoint());
else
view->setScrollPositionNonProgrammatically(m_currentItem->scrollPoint());
if (m_frame->isMainFrame()) {
if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(view);
}
}
void FrameLoader::detachChildren()
{
typedef Vector<RefPtr<LocalFrame> > FrameVector;
FrameVector childrenToDetach;
childrenToDetach.reserveCapacity(m_frame->tree().childCount());
for (LocalFrame* child = m_frame->tree().lastChild(); child; child = child->tree().previousSibling())
childrenToDetach.append(child);
FrameVector::iterator end = childrenToDetach.end();
for (FrameVector::iterator it = childrenToDetach.begin(); it != end; ++it)
(*it)->loader().detachFromParent();
}
void FrameLoader::closeAndRemoveChild(LocalFrame* child)
{
child->setView(nullptr);
if (child->ownerElement() && child->page())
child->page()->decrementSubframeCount();
child->willDetachFrameHost();
child->loader().detachClient();
}
void FrameLoader::checkLoadComplete()
{
ASSERT(m_client->hasWebView());
if (Page* page = m_frame->page())
page->mainFrame()->loader().checkLoadCompleteForThisFrame();
}
void FrameLoader::checkLoadComplete(DocumentLoader* documentLoader)
{
if (documentLoader)
documentLoader->checkLoadComplete();
checkLoadComplete();
}
String FrameLoader::userAgent(const KURL& url) const
{
String userAgent = m_client->userAgent(url);
InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
return userAgent;
}
void FrameLoader::frameDetached()
{
RefPtr<LocalFrame> protect(m_frame);
stopAllLoaders();
detachFromParent();
}
void FrameLoader::detachFromParent()
{
RefPtr<LocalFrame> protect(m_frame);
closeURL();
detachChildren();
stopAllLoaders();
InspectorInstrumentation::frameDetachedFromParent(m_frame);
if (m_documentLoader)
m_documentLoader->detachFromFrame();
m_documentLoader = nullptr;
if (!m_client)
return;
if (LocalFrame* parent = m_frame->tree().parent()) {
parent->loader().closeAndRemoveChild(m_frame);
parent->loader().scheduleCheckCompleted();
} else {
m_frame->setView(nullptr);
m_frame->willDetachFrameHost();
detachClient();
}
m_frame->detachFromFrameHost();
}
void FrameLoader::detachClient()
{
ASSERT(m_client);
m_progressTracker.clear();
setOpener(0);
m_frame->script().clearForClose();
m_client->detachedFromParent();
m_client = 0;
}
void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const AtomicString& origin)
{
if (!request.httpOrigin().isEmpty())
return;
if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
return;
if (origin.isEmpty()) {
request.setHTTPOrigin(SecurityOrigin::createUnique()->toAtomicString());
return;
}
request.setHTTPOrigin(origin);
}
void FrameLoader::receivedMainResourceError(const ResourceError& error)
{
RefPtr<LocalFrame> protect(m_frame);
if (m_frame->document()->parser())
m_frame->document()->parser()->stopParsing();
ResourceError c(ResourceError::cancelledError(KURL()));
if ((error.errorCode() != c.errorCode() || error.domain() != c.domain()) && m_frame->ownerElement())
m_frame->ownerElement()->renderFallbackContent();
checkCompleted();
if (m_frame->page())
checkLoadComplete();
}
bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
{
ASSERT(loadType != FrameLoadTypeReloadFromOrigin);
return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
&& loadType != FrameLoadTypeReload
&& loadType != FrameLoadTypeSame
&& loadType != FrameLoadTypeBackForward
&& url.hasFragmentIdentifier()
&& equalIgnoringFragmentIdentifier(m_frame->document()->url(), url)
&& !m_frame->document()->isFrameSet();
}
void FrameLoader::scrollToFragmentWithParentBoundary(const KURL& url)
{
FrameView* view = m_frame->view();
if (!view)
return;
RefPtr<LocalFrame> boundaryFrame(url.hasFragmentIdentifier() ? m_frame->document()->findUnsafeParentScrollPropagationBoundary() : 0);
if (boundaryFrame)
boundaryFrame->view()->setSafeToPropagateScrollToParent(false);
view->scrollToFragment(url);
if (boundaryFrame)
boundaryFrame->view()->setSafeToPropagateScrollToParent(true);
}
bool FrameLoader::shouldClose()
{
Page* page = m_frame->page();
if (!page || !page->chrome().canRunBeforeUnloadConfirmPanel())
return true;
Vector<RefPtr<LocalFrame> > targetFrames;
targetFrames.append(m_frame);
for (LocalFrame* child = m_frame->tree().firstChild(); child; child = child->tree().traverseNext(m_frame))
targetFrames.append(child);
bool shouldClose = false;
{
NavigationDisablerForBeforeUnload navigationDisabler;
size_t i;
bool didAllowNavigation = false;
for (i = 0; i < targetFrames.size(); i++) {
if (!targetFrames[i]->tree().isDescendantOf(m_frame))
continue;
if (!targetFrames[i]->document()->dispatchBeforeUnloadEvent(page->chrome(), didAllowNavigation))
break;
}
if (i == targetFrames.size())
shouldClose = true;
}
return shouldClose;
}
void FrameLoader::loadWithNavigationAction(const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, ClientRedirectPolicy clientRedirect, const AtomicString& overrideEncoding)
{
ASSERT(m_client->hasWebView());
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
const ResourceRequest& request = action.resourceRequest();
if (!m_stateMachine.startedFirstRealLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
bool replacesCurrentHistoryItem = false;
if (type == FrameLoadTypeRedirectWithLockedBackForwardList
|| !m_stateMachine.committedFirstRealDocumentLoad()) {
replacesCurrentHistoryItem = true;
}
m_policyDocumentLoader = m_client->createDocumentLoader(m_frame, request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
m_policyDocumentLoader->setTriggeringAction(action);
m_policyDocumentLoader->setReplacesCurrentHistoryItem(replacesCurrentHistoryItem);
m_policyDocumentLoader->setIsClientRedirect(clientRedirect == ClientRedirect);
if (LocalFrame* parent = m_frame->tree().parent())
m_policyDocumentLoader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
else if (!overrideEncoding.isEmpty())
m_policyDocumentLoader->setOverrideEncoding(overrideEncoding);
else if (m_documentLoader)
m_policyDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
RefPtr<LocalFrame> protect(m_frame);
if ((!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request) || !shouldClose()) && m_policyDocumentLoader) {
m_policyDocumentLoader->detachFromFrame();
m_policyDocumentLoader = nullptr;
return;
}
stopAllLoaders();
if (!m_frame->page() || !m_policyDocumentLoader)
return;
if (isLoadingMainFrame())
m_frame->page()->inspectorController().resume();
m_frame->navigationScheduler().cancel();
m_provisionalDocumentLoader = m_policyDocumentLoader.release();
m_loadType = type;
m_state = FrameStateProvisional;
if (formState)
m_client->dispatchWillSubmitForm(formState->form());
m_progressTracker->progressStarted();
if (m_provisionalDocumentLoader->isClientRedirect())
m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url());
m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url());
m_client->dispatchDidStartProvisionalLoad();
ASSERT(m_provisionalDocumentLoader);
m_provisionalDocumentLoader->startLoadingMainResource();
}
void FrameLoader::applyUserAgent(ResourceRequest& request)
{
String userAgent = this->userAgent(request.url());
ASSERT(!userAgent.isNull());
request.setHTTPUserAgent(AtomicString(userAgent));
}
bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
{
UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptions);
LocalFrame* topFrame = m_frame->tree().top();
if (m_frame == topFrame)
return false;
XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
switch (disposition) {
case XFrameOptionsSameOrigin: {
UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptionsSameOrigin);
RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
return true;
for (LocalFrame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent()) {
if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
break;
}
}
return false;
}
case XFrameOptionsDeny:
return true;
case XFrameOptionsAllowAll:
return false;
case XFrameOptionsConflict:
m_frame->document()->addConsoleMessageWithRequestIdentifier(JSMessageSource, ErrorMessageLevel, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.elidedString() + "'. Falling back to 'DENY'.", requestIdentifier);
return true;
case XFrameOptionsInvalid:
m_frame->document()->addConsoleMessageWithRequestIdentifier(JSMessageSource, ErrorMessageLevel, "Invalid 'X-Frame-Options' header encountered when loading '" + url.elidedString() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
return false;
default:
ASSERT_NOT_REACHED();
return false;
}
}
bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
{
return m_currentItem && url == m_currentItem->url();
}
bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
{
if (!equalIgnoringCase(url.string(), "about:srcdoc"))
return false;
HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
if (!isHTMLIFrameElement(ownerElement))
return false;
return ownerElement->fastHasAttribute(srcdocAttr);
}
LocalFrame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
{
ASSERT(activeDocument);
LocalFrame* frame = m_frame->tree().find(name);
if (!activeDocument->canNavigate(frame))
return 0;
return frame;
}
void FrameLoader::loadHistoryItem(HistoryItem* item, HistoryLoadType historyLoadType, ResourceRequestCachePolicy cachePolicy)
{
if (m_frame->page()->defersLoading()) {
m_deferredHistoryLoad = DeferredHistoryLoad(item, historyLoadType, cachePolicy);
return;
}
m_provisionalItem = item;
if (historyLoadType == HistorySameDocumentLoad) {
m_loadType = FrameLoadTypeBackForward;
loadInSameDocument(item->url(), item->stateObject(), DoNotUpdateBackForwardList, NotClientRedirect);
restoreScrollPositionAndViewState();
return;
}
loadWithNavigationAction(NavigationAction(requestFromHistoryItem(item, cachePolicy), FrameLoadTypeBackForward), FrameLoadTypeBackForward, nullptr, SubstituteData());
}
void FrameLoader::dispatchDocumentElementAvailable()
{
m_client->documentElementAvailable();
}
void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
{
if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
return;
if (Page* page = m_frame->page())
page->inspectorController().didClearWindowObjectInMainWorld(m_frame);
InspectorInstrumentation::didClearWindowObjectInMainWorld(m_frame);
Vector<RefPtr<DOMWrapperWorld> > worlds;
DOMWrapperWorld::allWorldsInMainThread(worlds);
for (size_t i = 0; i < worlds.size(); ++i)
m_client->dispatchDidClearWindowObjectInWorld(*worlds[i]);
}
void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
{
if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script().existingWindowShell(world))
return;
m_client->dispatchDidClearWindowObjectInWorld(world);
}
SandboxFlags FrameLoader::effectiveSandboxFlags() const
{
SandboxFlags flags = m_forcedSandboxFlags;
if (LocalFrame* parentFrame = m_frame->tree().parent())
flags |= parentFrame->document()->sandboxFlags();
if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
flags |= ownerElement->sandboxFlags();
return flags;
}
}