#include "config.h"
#include "FrameLoader.h"
#include "AXObjectCache.h"
#include "ApplicationCacheHost.h"
#include "BackForwardController.h"
#include "BeforeUnloadEvent.h"
#include "CachedPage.h"
#include "CachedResourceLoader.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "ContentSecurityPolicy.h"
#include "DOMImplementation.h"
#include "DOMWindow.h"
#include "DatabaseManager.h"
#include "Document.h"
#include "DocumentLoadTiming.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "Event.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "FloatRect.h"
#include "FormState.h"
#include "FormSubmission.h"
#include "FrameLoadRequest.h"
#include "FrameLoaderClient.h"
#include "FrameNetworkingContext.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HTMLAnchorElement.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLObjectElement.h"
#include "HTMLParserIdioms.h"
#include "HTTPHeaderNames.h"
#include "HTTPParsers.h"
#include "HistoryController.h"
#include "HistoryItem.h"
#include "IconController.h"
#include "InspectorController.h"
#include "InspectorInstrumentation.h"
#include "LoaderStrategy.h"
#include "Logging.h"
#include "MIMETypeRegistry.h"
#include "MainFrame.h"
#include "MemoryCache.h"
#include "Page.h"
#include "PageActivityAssertionToken.h"
#include "PageCache.h"
#include "PageThrottler.h"
#include "PageTransitionEvent.h"
#include "PlatformStrategies.h"
#include "PluginData.h"
#include "PluginDatabase.h"
#include "PluginDocument.h"
#include "PolicyChecker.h"
#include "ProgressTracker.h"
#include "ResourceHandle.h"
#include "ResourceRequest.h"
#include "SVGDocument.h"
#include "SVGLocatable.h"
#include "SVGNames.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGSVGElement.h"
#include "SVGViewElement.h"
#include "SVGViewSpec.h"
#include "SchemeRegistry.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ScrollAnimator.h"
#include "SecurityOrigin.h"
#include "SecurityPolicy.h"
#include "SegmentedString.h"
#include "SerializedScriptValue.h"
#include "Settings.h"
#include "SubframeLoader.h"
#include "TextResourceDecoder.h"
#include "WindowFeatures.h"
#include "XMLDocumentParser.h"
#include <wtf/CurrentTime.h>
#include <wtf/Ref.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#if ENABLE(SHARED_WORKERS)
#include "SharedWorkerRepository.h"
#endif
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
#include "Archive.h"
#endif
#if PLATFORM(IOS)
#include "DocumentType.h"
#include "MemoryPressureHandler.h"
#include "ResourceLoader.h"
#include "RuntimeApplicationChecksIOS.h"
#include "SystemMemory.h"
#include "WKContentObservation.h"
#endif
namespace WebCore {
using namespace HTMLNames;
using namespace SVGNames;
static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
#if PLATFORM(IOS)
const int memoryLevelThresholdToPrunePageCache = 20;
#endif
bool isBackForwardLoadType(FrameLoadType type)
{
switch (type) {
case FrameLoadType::Standard:
case FrameLoadType::Reload:
case FrameLoadType::ReloadFromOrigin:
case FrameLoadType::Same:
case FrameLoadType::RedirectWithLockedBackForwardList:
case FrameLoadType::Replace:
return false;
case FrameLoadType::Back:
case FrameLoadType::Forward:
case FrameLoadType::IndexedBackForward:
return true;
}
ASSERT_NOT_REACHED();
return false;
}
static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
{
return frame->document() && frame->document()->isSandboxed(mask);
}
class FrameLoader::FrameProgressTracker {
public:
explicit FrameProgressTracker(Frame& frame)
: m_frame(frame)
, m_inProgress(false)
{
}
~FrameProgressTracker()
{
ASSERT(!m_inProgress || m_frame.page());
if (m_inProgress)
m_frame.page()->progress().progressCompleted(m_frame);
}
void progressStarted()
{
ASSERT(m_frame.page());
if (!m_inProgress)
m_frame.page()->progress().progressStarted(m_frame);
m_inProgress = true;
}
void progressCompleted()
{
ASSERT(m_inProgress);
ASSERT(m_frame.page());
m_inProgress = false;
m_frame.page()->progress().progressCompleted(m_frame);
}
private:
Frame& m_frame;
bool m_inProgress;
};
FrameLoader::FrameLoader(Frame& frame, FrameLoaderClient& client)
: m_frame(frame)
, m_client(client)
, m_policyChecker(std::make_unique<PolicyChecker>(frame))
, m_history(std::make_unique<HistoryController>(frame))
, m_notifier(frame)
, m_subframeLoader(std::make_unique<SubframeLoader>(frame))
, m_icon(std::make_unique<IconController>(frame))
, m_mixedContentChecker(frame)
, m_state(FrameStateProvisional)
, m_loadType(FrameLoadType::Standard)
, m_delegateIsHandlingProvisionalLoadError(false)
, m_quickRedirectComing(false)
, m_sentRedirectNotification(false)
, m_inStopAllLoaders(false)
, m_isExecutingJavaScriptFormAction(false)
, m_didCallImplicitClose(true)
, m_wasUnloadEventEmitted(false)
, m_pageDismissalEventBeingDispatched(NoDismissal)
, m_isComplete(false)
, m_needsClear(false)
, m_checkTimer(this, &FrameLoader::checkTimerFired)
, m_shouldCallCheckCompleted(false)
, m_shouldCallCheckLoadComplete(false)
, m_opener(nullptr)
, m_loadingFromCachedPage(false)
, m_suppressOpenerInNewFrame(false)
, m_currentNavigationHasShownBeforeUnloadConfirmPanel(false)
, m_loadsSynchronously(false)
, m_forcedSandboxFlags(SandboxNone)
{
}
FrameLoader::~FrameLoader()
{
setOpener(nullptr);
HashSet<Frame*>::iterator end = m_openedFrames.end();
for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
(*it)->loader().m_opener = 0;
m_client.frameLoaderDestroyed();
if (m_networkingContext)
m_networkingContext->invalidate();
}
void FrameLoader::init()
{
setPolicyDocumentLoader(m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData()).get());
setProvisionalDocumentLoader(m_policyDocumentLoader.get());
m_provisionalDocumentLoader->startLoadingMainResource();
Ref<Frame> protect(m_frame);
m_frame.document()->cancelParsing();
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
m_networkingContext = m_client.createNetworkingContext();
m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
}
#if PLATFORM(IOS)
void FrameLoader::initForSynthesizedDocument(const URL&)
{
RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(ResourceRequest(URL(ParsedURLString, emptyString())), SubstituteData());
loader->setFrame(&m_frame);
loader->setResponse(ResourceResponse(URL(), ASCIILiteral("text/html"), 0, String(), String()));
loader->setCommitted(true);
setDocumentLoader(loader.get());
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
m_client.transitionToCommittedForNewPage();
m_didCallImplicitClose = true;
m_isComplete = true;
m_state = FrameStateComplete;
m_needsClear = true;
m_networkingContext = m_client.createNetworkingContext();
m_progressTracker = std::make_unique<FrameProgressTracker>(m_frame);
}
#endif
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);
history().setDefersLoading(defers);
if (!defers) {
m_frame.navigationScheduler().startTimer();
startCheckCompleteTimer();
}
}
void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool refresh)
{
urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
0, lockHistory, lockBackForwardList, MaybeSendReferrer, ReplaceDocumentIfJavaScriptURL);
}
void FrameLoader::urlSelected(const URL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer)
{
urlSelected(FrameLoadRequest(m_frame.document()->securityOrigin(), ResourceRequest(url), passedTarget),
triggeringEvent, lockHistory, lockBackForwardList, shouldSendReferrer, DoNotReplaceDocumentIfJavaScriptURL);
}
void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, LockHistory lockHistory, LockBackForwardList lockBackForwardList, ShouldSendReferrer shouldSendReferrer, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
{
ASSERT(!m_suppressOpenerInNewFrame);
Ref<Frame> protect(m_frame);
FrameLoadRequest frameRequest(passedRequest);
if (m_frame.script().executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
return;
if (frameRequest.frameName().isEmpty())
frameRequest.setFrameName(m_frame.document()->baseTarget());
if (shouldSendReferrer == NeverSendReferrer)
m_suppressOpenerInNewFrame = true;
addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, shouldSendReferrer);
m_suppressOpenerInNewFrame = false;
}
void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
{
ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
ASSERT(submission->data());
ASSERT(submission->state());
ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == &m_frame);
if (!m_frame.page())
return;
if (submission->action().isEmpty())
return;
if (isDocumentSandboxed(&m_frame, SandboxForms)) {
m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked form submission to '" + submission->action().stringCenterEllipsizedToLength() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
return;
}
if (protocolIsJavaScript(submission->action())) {
if (!m_frame.document()->contentSecurityPolicy()->allowFormAction(URL(submission->action())))
return;
m_isExecutingJavaScriptFormAction = true;
Ref<Frame> protect(m_frame);
m_frame.script().executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
m_isExecutingJavaScriptFormAction = false;
return;
}
Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
if (!targetFrame) {
if (!DOMWindow::allowPopUp(&m_frame) && !ScriptController::processingUserGesture())
return;
targetFrame = &m_frame;
} else
submission->clearTarget();
if (!targetFrame->page())
return;
if (m_frame.tree().isDescendantOf(targetFrame)) {
if (m_submittedFormURL == submission->requestURL())
return;
m_submittedFormURL = submission->requestURL();
}
submission->data()->generateFiles(m_frame.document());
submission->setReferrer(outgoingReferrer());
submission->setOrigin(outgoingOrigin());
targetFrame->navigationScheduler().scheduleFormSubmission(submission);
}
void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
{
if (m_frame.document() && m_frame.document()->parser())
m_frame.document()->parser()->stopParsing();
if (unloadEventPolicy != UnloadEventPolicyNone) {
if (m_frame.document()) {
if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
Element* currentFocusedElement = m_frame.document()->focusedElement();
if (currentFocusedElement && currentFocusedElement->toInputElement())
currentFocusedElement->toInputElement()->endEditing();
if (m_pageDismissalEventBeingDispatched == NoDismissal) {
if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
m_pageDismissalEventBeingDispatched = PageHideDismissal;
m_frame.document()->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame.document()->inPageCache()), m_frame.document());
}
if (!m_frame.document()->inPageCache()) {
RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
m_pageDismissalEventBeingDispatched = UnloadDismissal;
if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
DocumentLoadTiming* timing = documentLoader->timing();
ASSERT(timing->navigationStart());
timing->markUnloadEventStart();
m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
timing->markUnloadEventEnd();
} else
m_frame.document()->domWindow()->dispatchEvent(unloadEvent, m_frame.document());
}
}
m_pageDismissalEventBeingDispatched = NoDismissal;
if (m_frame.document())
m_frame.document()->updateStyleIfNeeded();
m_wasUnloadEventEmitted = true;
}
}
if (m_frame.document() && !m_frame.document()->inPageCache()) {
bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
&& m_frame.document()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
if (!keepEventListeners)
m_frame.document()->removeAllEventListeners();
}
}
m_isComplete = true; m_didCallImplicitClose = 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);
#if ENABLE(SQL_DATABASE)
DatabaseManager::manager().stopDatabases(doc, 0);
#endif
}
m_frame.navigationScheduler().cancel();
}
void FrameLoader::stop()
{
Ref<Frame> protect(m_frame);
if (DocumentParser* parser = m_frame.document()->parser()) {
parser->stopParsing();
parser->finish();
}
icon().stopLoader();
}
void FrameLoader::willTransitionToCommitted()
{
if (m_frame.editor().hasComposition()) {
m_frame.editor().confirmComposition();
if (EditorClient* editorClient = m_frame.editor().client())
editorClient->respondToChangedSelection(&m_frame);
}
}
bool FrameLoader::closeURL()
{
history().saveDocumentState();
Document* currentDocument = m_frame.document();
stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
m_frame.editor().clearUndoRedoOperations();
return true;
}
bool FrameLoader::didOpenURL()
{
if (m_frame.navigationScheduler().redirectScheduledDuringLoad()) {
return false;
}
m_frame.navigationScheduler().cancel();
m_frame.editor().clearLastEditCommand();
m_isComplete = false;
m_didCallImplicitClose = false;
if (!m_stateMachine.creatingInitialEmptyDocument()) {
DOMWindow* window = m_frame.document()->domWindow();
window->setStatus(String());
window->setDefaultStatus(String());
}
started();
return true;
}
void FrameLoader::didExplicitOpen()
{
m_isComplete = false;
m_didCallImplicitClose = false;
if (!m_stateMachine.committedFirstRealDocumentLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
m_frame.navigationScheduler().cancel();
}
void FrameLoader::cancelAndClear()
{
m_frame.navigationScheduler().cancel();
if (!m_isComplete)
closeURL();
clear(m_frame.document(), false);
m_frame.script().updatePlatformScriptObjects();
}
void FrameLoader::clear(Document* newDocument, bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
{
m_frame.editor().clear();
if (!m_needsClear)
return;
m_needsClear = false;
if (!m_frame.document()->inPageCache()) {
m_frame.document()->cancelParsing();
m_frame.document()->stopActiveDOMObjects();
bool hadLivingRenderTree = m_frame.document()->hasLivingRenderTree();
m_frame.document()->prepareForDestruction();
if (hadLivingRenderTree)
m_frame.document()->removeFocusedNodeOfSubtree(m_frame.document());
}
if (clearWindowProperties) {
InspectorInstrumentation::frameWindowDiscarded(&m_frame, m_frame.document()->domWindow());
m_frame.document()->domWindow()->resetUnlessSuspendedForPageCache();
m_frame.script().clearWindowShell(newDocument->domWindow(), m_frame.document()->inPageCache());
}
m_frame.selection().prepareForDestruction();
m_frame.eventHandler().clear();
if (clearFrameView && m_frame.view())
m_frame.view()->clear();
m_frame.setDocument(0);
subframeLoader().clear();
if (clearScriptObjects)
m_frame.script().clearScriptObjects();
m_frame.script().enableEval();
m_frame.navigationScheduler().clear();
m_checkTimer.stop();
m_shouldCallCheckCompleted = false;
m_shouldCallCheckLoadComplete = false;
if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
}
void FrameLoader::receivedFirstData()
{
dispatchDidCommitLoad();
dispatchDidClearWindowObjectsInAllWorlds();
dispatchGlobalObjectAvailableInAllWorlds();
if (m_documentLoader) {
StringWithDirection ptitle = m_documentLoader->title();
if (!ptitle.isNull())
m_client.dispatchDidReceiveTitle(ptitle);
}
if (!m_documentLoader)
return;
double delay;
String urlString;
if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField(HTTPHeaderName::Refresh), false, delay, urlString))
return;
URL completedURL;
if (urlString.isEmpty())
completedURL = m_frame.document()->url();
else
completedURL = m_frame.document()->completeURL(urlString);
if (!protocolIsJavaScript(completedURL))
m_frame.navigationScheduler().scheduleRedirect(delay, completedURL);
else {
String message = "Refused to refresh " + m_frame.document()->url().stringCenterEllipsizedToLength() + " to a javascript: URL";
m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
}
}
void FrameLoader::setOutgoingReferrer(const URL& url)
{
m_outgoingReferrer = url.strippedForUseAsReferrer();
}
void FrameLoader::didBeginDocument(bool dispatch)
{
m_needsClear = true;
m_isComplete = false;
m_didCallImplicitClose = false;
m_frame.document()->setReadyState(Document::Loading);
if (m_pendingStateObject) {
m_frame.document()->statePopped(m_pendingStateObject.get());
m_pendingStateObject.clear();
}
if (dispatch)
dispatchDidClearWindowObjectsInAllWorlds();
updateFirstPartyForCookies();
m_frame.document()->initContentSecurityPolicy();
const Settings& settings = m_frame.settings();
m_frame.document()->cachedResourceLoader()->setImagesEnabled(settings.areImagesEnabled());
m_frame.document()->cachedResourceLoader()->setAutoLoadImages(settings.loadsImagesAutomatically());
if (m_documentLoader) {
String dnsPrefetchControl = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XDNSPrefetchControl);
if (!dnsPrefetchControl.isEmpty())
m_frame.document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
String policyValue = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentSecurityPolicy);
if (!policyValue.isEmpty())
m_frame.document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Enforce);
policyValue = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentSecurityPolicyReportOnly);
if (!policyValue.isEmpty())
m_frame.document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::Report);
policyValue = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XWebKitCSP);
if (!policyValue.isEmpty())
m_frame.document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedEnforce);
policyValue = m_documentLoader->response().httpHeaderField(HTTPHeaderName::XWebKitCSPReportOnly);
if (!policyValue.isEmpty())
m_frame.document()->contentSecurityPolicy()->didReceiveHeader(policyValue, ContentSecurityPolicy::PrefixedReport);
String headerContentLanguage = m_documentLoader->response().httpHeaderField(HTTPHeaderName::ContentLanguage);
if (!headerContentLanguage.isEmpty()) {
size_t commaIndex = headerContentLanguage.find(',');
headerContentLanguage.truncate(commaIndex); headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace);
if (!headerContentLanguage.isEmpty())
m_frame.document()->setContentLanguage(headerContentLanguage);
}
}
history().restoreDocumentState();
}
void FrameLoader::finishedParsing()
{
m_frame.injectUserScripts(InjectAtDocumentEnd);
if (m_stateMachine.creatingInitialEmptyDocument())
return;
RefPtr<Frame> protector = m_frame.view() ? &m_frame : 0;
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 (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->loader().m_isComplete)
return false;
}
return true;
}
bool FrameLoader::allAncestorsAreComplete() const
{
for (Frame* ancestor = &m_frame; ancestor; ancestor = ancestor->tree().parent()) {
if (!ancestor->loader().m_isComplete)
return false;
}
return true;
}
void FrameLoader::checkCompleted()
{
m_shouldCallCheckCompleted = false;
if (m_isComplete)
return;
if (m_frame.document()->parsing())
return;
if (m_frame.document()->cachedResourceLoader()->requestCount())
return;
if (m_frame.document()->isDelayingLoadEvent())
return;
if (!allChildrenAreComplete())
return;
Ref<Frame> protect(m_frame);
m_isComplete = true;
m_requestedHistoryItem = 0;
m_frame.document()->setReadyState(Document::Complete);
#if PLATFORM(IOS)
if (m_frame.document()->url().isEmpty()) {
m_frame.document()->setURL(activeDocumentLoader()->documentURL());
}
#endif
checkCallImplicitClose();
m_frame.navigationScheduler().startTimer();
completed();
if (m_frame.page())
checkLoadComplete();
}
void FrameLoader::checkTimerFired(Timer<FrameLoader>&)
{
Ref<Frame> protect(m_frame);
if (Page* page = m_frame.page()) {
if (page->defersLoading())
return;
}
if (m_shouldCallCheckCompleted)
checkCompleted();
if (m_shouldCallCheckLoadComplete)
checkLoadComplete();
}
void FrameLoader::startCheckCompleteTimer()
{
if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
return;
if (m_checkTimer.isActive())
return;
m_checkTimer.startOneShot(0);
}
void FrameLoader::scheduleCheckCompleted()
{
m_shouldCallCheckCompleted = true;
startCheckCompleteTimer();
}
void FrameLoader::scheduleCheckLoadComplete()
{
m_shouldCallCheckLoadComplete = true;
startCheckCompleteTimer();
}
void FrameLoader::checkCallImplicitClose()
{
if (m_didCallImplicitClose || m_frame.document()->parsing() || m_frame.document()->isDelayingLoadEvent())
return;
if (!allChildrenAreComplete())
return;
m_didCallImplicitClose = true;
m_wasUnloadEventEmitted = false;
m_frame.document()->implicitClose();
}
void FrameLoader::loadURLIntoChildFrame(const URL& url, const String& referer, Frame* childFrame)
{
ASSERT(childFrame);
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree().uniqueName(), url);
if (subframeArchive) {
childFrame->loader().loadArchive(subframeArchive.release());
return;
}
#endif // ENABLE(WEB_ARCHIVE)
HistoryItem* parentItem = history().currentItem();
if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType())
&& !m_frame.document()->loadEventFinished()) {
HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree().uniqueName());
if (childItem) {
childFrame->loader().m_requestedHistoryItem = childItem;
childFrame->loader().loadDifferentDocumentItem(childItem, loadType(), MayAttemptCacheOnlyLoadForFormSubmissionItem);
return;
}
}
childFrame->loader().loadURL(url, referer, "_self", LockHistory::No, FrameLoadType::RedirectWithLockedBackForwardList, 0, 0);
}
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
{
ArchiveResource* mainResource = archive->mainResource();
ASSERT(mainResource);
if (!mainResource)
return;
SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), URL());
ResourceRequest request(mainResource->url());
#if PLATFORM(MAC)
request.applyWebArchiveHackForMail();
#endif
RefPtr<DocumentLoader> documentLoader = m_client.createDocumentLoader(request, substituteData);
documentLoader->setArchive(archive.get());
load(documentLoader.get());
}
#endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
ObjectContentType FrameLoader::defaultObjectContentType(const URL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
{
String mimeType = mimeTypeIn;
if (mimeType.isEmpty())
mimeType = mimeTypeFromURL(url);
#if !PLATFORM(COCOA) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does EFL
if (mimeType.isEmpty()) {
String decodedPath = decodeURLEscapeSequences(url.path());
mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(decodedPath.substring(decodedPath.reverseFind('.') + 1));
}
#endif
if (mimeType.isEmpty())
return ObjectContentFrame;
#if !PLATFORM(COCOA) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does EFL
bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
#else
bool plugInSupportsMIMEType = false;
#endif
if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
if (plugInSupportsMIMEType)
return WebCore::ObjectContentNetscapePlugin;
if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
return WebCore::ObjectContentFrame;
return WebCore::ObjectContentNone;
}
String FrameLoader::outgoingReferrer() const
{
Frame* frame = &m_frame;
while (frame->document()->isSrcdocDocument()) {
frame = frame->tree().parent();
ASSERT(frame);
}
return frame->loader().m_outgoingReferrer;
}
String FrameLoader::outgoingOrigin() const
{
return m_frame.document()->securityOrigin()->toString();
}
bool FrameLoader::checkIfFormActionAllowedByCSP(const URL& url) const
{
if (m_submittedFormURL.isEmpty())
return true;
return m_frame.document()->contentSecurityPolicy()->allowFormAction(url);
}
Frame* FrameLoader::opener()
{
return m_opener;
}
void FrameLoader::setOpener(Frame* opener)
{
if (m_opener && !opener)
m_client.didDisownOpener();
if (m_opener)
m_opener->loader().m_openedFrames.remove(&m_frame);
if (opener)
opener->loader().m_openedFrames.add(&m_frame);
m_opener = opener;
if (m_frame.document())
m_frame.document()->initSecurityContext();
}
void FrameLoader::handleFallbackContent()
{
HTMLFrameOwnerElement* owner = m_frame.ownerElement();
if (!owner || !owner->hasTagName(objectTag))
return;
toHTMLObjectElement(owner)->renderFallbackContent();
}
void FrameLoader::provisionalLoadStarted()
{
if (m_stateMachine.firstLayoutDone())
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
m_frame.navigationScheduler().cancel(true);
m_client.provisionalLoadStarted();
}
void FrameLoader::resetMultipleFormSubmissionProtection()
{
m_submittedFormURL = URL();
}
void FrameLoader::updateFirstPartyForCookies()
{
if (m_frame.tree().parent())
setFirstPartyForCookies(m_frame.tree().parent()->document()->firstPartyForCookies());
else
setFirstPartyForCookies(m_frame.document()->url());
}
void FrameLoader::setFirstPartyForCookies(const URL& url)
{
for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
frame->document()->setFirstPartyForCookies(url);
}
void FrameLoader::loadInSameDocument(const URL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
{
ASSERT(!stateObject || (stateObject && !isNewNavigation));
URL oldURL = m_frame.document()->url();
m_frame.document()->setURL(url);
setOutgoingReferrer(url);
documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
history().updateBackForwardListForFragmentScroll();
}
bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
history().updateForSameDocumentNavigation();
if (hashChange)
m_frame.eventHandler().stopAutoscrollTimer();
started();
scrollToFragmentWithParentBoundary(url);
m_isComplete = false;
checkCompleted();
if (isNewNavigation) {
checkLoadComplete();
}
m_client.dispatchDidNavigateWithinPage();
m_frame.document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
m_client.dispatchDidPopStateWithinPage();
if (hashChange) {
m_frame.document()->enqueueHashchangeEvent(oldURL, url);
m_client.dispatchDidChangeLocationWithinPage();
}
m_client.didFinishLoad();
}
bool FrameLoader::isComplete() const
{
return m_isComplete;
}
void FrameLoader::completed()
{
Ref<Frame> protect(m_frame);
for (Frame* descendant = m_frame.tree().traverseNext(&m_frame); descendant; descendant = descendant->tree().traverseNext(&m_frame))
descendant->navigationScheduler().startTimer();
if (Frame* parent = m_frame.tree().parent())
parent->loader().checkCompleted();
if (m_frame.view())
m_frame.view()->maintainScrollPositionAtAnchor(0);
m_activityAssertion = nullptr;
}
void FrameLoader::started()
{
if (m_frame.page() && m_frame.page()->pageThrottler())
m_activityAssertion = m_frame.page()->pageThrottler()->pageLoadActivityToken();
for (Frame* frame = &m_frame; frame; frame = frame->tree().parent())
frame->loader().m_isComplete = false;
}
void FrameLoader::prepareForHistoryNavigation()
{
RefPtr<HistoryItem> currentItem = history().currentItem();
if (!currentItem) {
currentItem = HistoryItem::create();
currentItem->setLastVisitWasFailure(true);
history().setCurrentItem(currentItem.get());
m_frame.page()->backForward().setCurrentItem(currentItem.get());
ASSERT(stateMachine().isDisplayingInitialEmptyDocument());
stateMachine().advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
stateMachine().advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
}
}
void FrameLoader::prepareForLoadStart()
{
m_progressTracker->progressStarted();
m_client.dispatchDidStartProvisionalLoad();
if (AXObjectCache::accessibilityEnabled()) {
if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache()) {
AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadType::Reload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
cache->frameLoadingEventNotification(&m_frame, loadingEvent);
}
}
}
void FrameLoader::setupForReplace()
{
m_client.revertToProvisionalState(m_documentLoader.get());
setState(FrameStateProvisional);
m_provisionalDocumentLoader = m_documentLoader;
m_documentLoader = 0;
detachChildren();
}
void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, LockHistory lockHistory, LockBackForwardList lockBackForwardList,
PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
{
Ref<Frame> protect(m_frame);
URL url = request.resourceRequest().url();
ASSERT(m_frame.document());
if (!request.requester()->canDisplay(url)) {
reportLocalLoadFailed(&m_frame, url.stringCenterEllipsizedToLength());
return;
}
String argsReferrer = request.resourceRequest().httpReferrer();
if (argsReferrer.isEmpty())
argsReferrer = outgoingReferrer();
String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), url, argsReferrer);
if (shouldSendReferrer == NeverSendReferrer)
referrer = String();
FrameLoadType loadType;
if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
loadType = FrameLoadType::Reload;
else if (lockBackForwardList == LockBackForwardList::Yes)
loadType = FrameLoadType::RedirectWithLockedBackForwardList;
else
loadType = FrameLoadType::Standard;
if (request.resourceRequest().httpMethod() == "POST")
loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
else
loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : &m_frame;
if (!sourceFrame)
sourceFrame = &m_frame;
Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(request.frameName());
if (targetFrame && targetFrame != sourceFrame) {
if (Page* page = targetFrame->page())
page->chrome().focus();
}
}
void FrameLoader::loadURL(const URL& newURL, const String& referrer, const String& frameName, LockHistory lockHistory, FrameLoadType newLoadType,
PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
{
if (m_inStopAllLoaders)
return;
Ref<Frame> protect(m_frame);
RefPtr<FormState> formState = prpFormState;
bool isFormSubmission = formState;
ResourceRequest request(newURL);
if (!referrer.isEmpty()) {
request.setHTTPReferrer(referrer);
RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
addHTTPOriginIfNeeded(request, referrerOrigin->toString());
}
#if ENABLE(CACHE_PARTITIONING)
if (&m_frame.tree().top() != &m_frame)
request.setCachePartition(m_frame.tree().top().document()->securityOrigin()->cachePartition());
#endif
addExtraFieldsToRequest(request, newLoadType, true);
if (newLoadType == FrameLoadType::Reload || newLoadType == FrameLoadType::ReloadFromOrigin)
request.setCachePolicy(ReloadIgnoringCacheData);
ASSERT(newLoadType != FrameLoadType::Same);
Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
if (targetFrame && targetFrame != &m_frame) {
targetFrame->loader().loadURL(newURL, referrer, "_self", lockHistory, newLoadType, event, formState.release());
return;
}
if (m_pageDismissalEventBeingDispatched != NoDismissal)
return;
NavigationAction action(request, newLoadType, isFormSubmission, event);
if (!targetFrame && !frameName.isEmpty()) {
policyChecker().checkNewWindowPolicy(action, request, formState.release(), frameName, [this](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
});
return;
}
RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
const String& httpMethod = request.httpMethod();
if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, newLoadType, newURL)) {
oldDocumentLoader->setTriggeringAction(action);
oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
policyChecker().stopCheck();
policyChecker().setLoadType(newLoadType);
policyChecker().checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(), [this](const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue) {
continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
});
return;
}
bool isRedirect = m_quickRedirectComing;
loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
if (isRedirect) {
m_quickRedirectComing = false;
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setIsClientRedirect(true);
} else if (sameURL && newLoadType != FrameLoadType::Reload && newLoadType != FrameLoadType::ReloadFromOrigin) {
m_loadType = FrameLoadType::Same;
}
}
SubstituteData FrameLoader::defaultSubstituteDataForURL(const URL& 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", URL());
}
void FrameLoader::load(const FrameLoadRequest& passedRequest)
{
FrameLoadRequest request(passedRequest);
if (m_inStopAllLoaders)
return;
if (!request.frameName().isEmpty()) {
Frame* frame = findFrameForNavigation(request.frameName());
if (frame) {
request.setShouldCheckNewWindowPolicy(false);
if (&frame->loader() != this) {
frame->loader().load(request);
return;
}
}
}
if (request.shouldCheckNewWindowPolicy()) {
policyChecker().checkNewWindowPolicy(NavigationAction(request.resourceRequest(), NavigationTypeOther), request.resourceRequest(), nullptr, request.frameName(), [this](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
});
return;
}
if (!request.hasSubstituteData())
request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url()));
RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(request.resourceRequest(), request.substituteData());
load(loader.get());
}
void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, LockHistory lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
{
RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
if (lockHistory == LockHistory::Yes && m_documentLoader)
loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
loader->setTriggeringAction(action);
if (m_documentLoader)
loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
loadWithDocumentLoader(loader.get(), type, formState);
}
void FrameLoader::load(DocumentLoader* newDocumentLoader)
{
ResourceRequest& r = newDocumentLoader->request();
addExtraFieldsToMainResourceRequest(r);
FrameLoadType type;
if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
r.setCachePolicy(ReloadIgnoringCacheData);
type = FrameLoadType::Same;
} else if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->unreachableURL()) && m_loadType == FrameLoadType::Reload)
type = FrameLoadType::Reload;
else
type = FrameLoadType::Standard;
if (m_documentLoader)
newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
history().saveDocumentAndScrollState();
ASSERT(type == FrameLoadType::Standard);
type = FrameLoadType::Reload;
}
loadWithDocumentLoader(newDocumentLoader, type, 0);
}
void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
{
Ref<Frame> protect(m_frame);
ASSERT(m_client.hasWebView());
ASSERT(m_frame.view());
if (m_pageDismissalEventBeingDispatched != NoDismissal)
return;
if (m_frame.document())
m_previousURL = m_frame.document()->url();
policyChecker().setLoadType(type);
RefPtr<FormState> formState = prpFormState;
bool isFormSubmission = formState;
const URL& newURL = loader->request().url();
const String& httpMethod = loader->request().httpMethod();
if (shouldPerformFragmentNavigation(isFormSubmission, httpMethod, policyChecker().loadType(), newURL)) {
RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
NavigationAction action(loader->request(), policyChecker().loadType(), isFormSubmission);
oldDocumentLoader->setTriggeringAction(action);
oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
policyChecker().stopCheck();
policyChecker().checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState, [this](const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue) {
continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
});
return;
}
if (Frame* parent = m_frame.tree().parent())
loader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
policyChecker().stopCheck();
setPolicyDocumentLoader(loader);
if (loader->triggeringAction().isEmpty())
loader->setTriggeringAction(NavigationAction(loader->request(), policyChecker().loadType(), isFormSubmission));
if (Element* ownerElement = m_frame.ownerElement()) {
if (!m_stateMachine.committedFirstRealDocumentLoad()
&& !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
continueLoadAfterNavigationPolicy(loader->request(), formState, false);
return;
}
}
policyChecker().checkNavigationPolicy(loader->request(), loader, formState, [this](const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue) {
continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
});
}
void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
{
ASSERT(!url.isEmpty());
if (!frame)
return;
frame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to load local resource: " + url);
}
const ResourceRequest& FrameLoader::initialRequest() const
{
return activeDocumentLoader()->originalRequest();
}
bool FrameLoader::willLoadMediaElementURL(URL& url)
{
#if PLATFORM(IOS)
if (applicationIsMobileStore())
return m_client.shouldLoadMediaElementURL(url);
#endif
ResourceRequest request(url);
unsigned long identifier;
ResourceError error;
requestFromDelegate(request, identifier, error);
notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
url = request.url();
return error.isNull();
}
bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
{
URL unreachableURL = docLoader->unreachableURL();
if (unreachableURL.isEmpty())
return false;
if (!isBackForwardLoadType(policyChecker().loadType()))
return false;
DocumentLoader* compareDocumentLoader = 0;
if (policyChecker().delegateIsDecidingNavigationPolicy() || policyChecker().delegateIsHandlingUnimplementablePolicy())
compareDocumentLoader = m_policyDocumentLoader.get();
else if (m_delegateIsHandlingProvisionalLoadError)
compareDocumentLoader = m_provisionalDocumentLoader.get();
return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
}
void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
{
if (!m_documentLoader)
return;
ResourceRequest request = m_documentLoader->request();
URL unreachableURL = m_documentLoader->unreachableURL();
if (!unreachableURL.isEmpty())
request.setURL(unreachableURL);
request.setCachePolicy(ReturnCacheDataElseLoad);
RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(request, defaultSubstituteDataForURL(request.url()));
setPolicyDocumentLoader(loader.get());
loader->setOverrideEncoding(encoding);
loadWithDocumentLoader(loader.get(), FrameLoadType::Reload, 0);
}
void FrameLoader::reload(bool endToEndReload)
{
if (!m_documentLoader)
return;
if (m_documentLoader->request().url().isEmpty())
return;
ResourceRequest initialRequest = m_documentLoader->request();
URL unreachableURL = m_documentLoader->unreachableURL();
if (!unreachableURL.isEmpty())
initialRequest.setURL(unreachableURL);
RefPtr<DocumentLoader> loader = m_client.createDocumentLoader(initialRequest, defaultSubstituteDataForURL(initialRequest.url()));
ResourceRequest& request = loader->request();
request.setCachePolicy(ReloadIgnoringCacheData);
if (request.httpMethod() == "POST")
loader->setTriggeringAction(NavigationAction(request, NavigationTypeFormResubmitted));
loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadType::ReloadFromOrigin : FrameLoadType::Reload, 0);
}
void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
{
ASSERT(!m_frame.document() || !m_frame.document()->inPageCache());
if (m_pageDismissalEventBeingDispatched != NoDismissal)
return;
if (m_inStopAllLoaders)
return;
Ref<Frame> protect(m_frame);
m_inStopAllLoaders = true;
policyChecker().stopCheck();
if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
history().setProvisionalItem(0);
for (RefPtr<Frame> child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
child->loader().stopAllLoaders(clearProvisionalItemPolicy);
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->stopLoading();
if (m_documentLoader)
m_documentLoader->stopLoading();
setProvisionalDocumentLoader(0);
m_checkTimer.stop();
m_inStopAllLoaders = false;
}
void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
{
stopAllLoaders();
#if PLATFORM(IOS)
if (m_frame.view() && !m_frame.view()->didFirstLayout())
m_frame.view()->layout();
#endif
if (deferCheckLoadComplete)
scheduleCheckLoadComplete();
else if (m_frame.page())
checkLoadComplete();
}
DocumentLoader* FrameLoader::activeDocumentLoader() const
{
if (m_state == FrameStateProvisional)
return m_provisionalDocumentLoader.get();
return m_documentLoader.get();
}
bool FrameLoader::isLoading() const
{
DocumentLoader* docLoader = activeDocumentLoader();
if (!docLoader)
return false;
return docLoader->isLoading();
}
bool FrameLoader::frameHasLoaded() const
{
return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument());
}
void FrameLoader::setDocumentLoader(DocumentLoader* loader)
{
if (!loader && !m_documentLoader)
return;
ASSERT(loader != m_documentLoader);
ASSERT(!loader || loader->frameLoader() == this);
m_client.prepareForDataSourceReplacement();
detachChildren();
if (loader && !loader->frame())
return;
if (m_documentLoader)
m_documentLoader->detachFromFrame();
m_documentLoader = loader;
}
void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
{
if (m_policyDocumentLoader == loader)
return;
if (loader)
loader->setFrame(&m_frame);
if (m_policyDocumentLoader
&& m_policyDocumentLoader != m_provisionalDocumentLoader
&& m_policyDocumentLoader != m_documentLoader)
m_policyDocumentLoader->detachFromFrame();
m_policyDocumentLoader = loader;
}
void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
{
ASSERT(!loader || !m_provisionalDocumentLoader);
ASSERT(!loader || loader->frameLoader() == this);
if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = loader;
}
void FrameLoader::setState(FrameState newState)
{
m_state = newState;
if (newState == FrameStateProvisional)
provisionalLoadStarted();
else if (newState == FrameStateComplete) {
frameLoadCompleted();
if (m_documentLoader)
m_documentLoader->stopRecordingResponses();
}
}
void FrameLoader::clearProvisionalLoad()
{
setProvisionalDocumentLoader(0);
m_progressTracker->progressCompleted();
setState(FrameStateComplete);
}
void FrameLoader::commitProvisionalLoad()
{
RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
Ref<Frame> protect(m_frame);
std::unique_ptr<CachedPage> cachedPage;
if (m_loadingFromCachedPage)
cachedPage = pageCache()->take(history().provisionalItem());
LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame.tree().uniqueName().string().utf8().data(),
m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "",
pdl ? pdl->url().stringCenterEllipsizedToLength().utf8().data() : "<no provisional DocumentLoader>");
#if PLATFORM(IOS)
if (!cachedPage) {
if (memoryPressureHandler().isUnderMemoryPressure()) {
LOG(MemoryPressure, "Pruning page cache because under memory pressure at: %s", __PRETTY_FUNCTION__);
LOG(PageCache, "Pruning page cache to 0 due to memory pressure");
pageCache()->pruneToCapacityNow(0);
} else if (systemMemoryLevel() <= memoryLevelThresholdToPrunePageCache) {
LOG(MemoryPressure, "Pruning page cache because system memory level is %d at: %s", systemMemoryLevel(), __PRETTY_FUNCTION__);
LOG(PageCache, "Pruning page cache to %d due to low memory (level %d less or equal to %d threshold)", pageCache()->capacity() / 2, systemMemoryLevel(), memoryLevelThresholdToPrunePageCache);
pageCache()->pruneToCapacityNow(pageCache()->capacity() / 2);
}
}
#endif
willTransitionToCommitted();
HistoryItem* item = history().currentItem();
if (!m_frame.tree().parent() && pageCache()->canCache(m_frame.page()) && !item->isInPageCache())
pageCache()->add(item, *m_frame.page());
if (m_loadType != FrameLoadType::Replace)
closeOldDataSources();
if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
m_client.makeRepresentation(pdl.get());
transitionToCommitted(cachedPage.get());
if (pdl && m_documentLoader) {
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
m_documentLoader->timing()->setHasSameOriginAsPreviousDocument(securityOrigin->canRequest(m_previousURL));
}
if (m_sentRedirectNotification)
clientRedirectCancelledOrFinished(false);
if (cachedPage && cachedPage->document()) {
#if PLATFORM(IOS)
m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(true);
#endif
prepareForCachedPageRestore();
cachedPage->restore(*m_frame.page());
dispatchDidCommitLoad();
#if PLATFORM(IOS)
m_frame.page()->chrome().setDispatchViewportDataDidChangeSuppressed(false);
m_frame.page()->chrome().dispatchViewportPropertiesDidChange(m_frame.page()->viewportArguments());
#endif
StringWithDirection title = m_documentLoader->title();
if (!title.isNull())
m_client.dispatchDidReceiveTitle(title);
checkCompleted();
} else
didOpenURL();
LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame.tree().uniqueName().string().utf8().data(),
m_frame.document() ? m_frame.document()->url().stringCenterEllipsizedToLength().utf8().data() : "");
if (m_loadType == FrameLoadType::Standard && m_documentLoader->isClientRedirect())
history().updateForClientRedirect();
if (m_loadingFromCachedPage) {
#if PLATFORM(IOS)
if (m_frame.document()->doctype() && m_frame.page())
m_frame.page()->chrome().didReceiveDocType(&m_frame);
#endif
m_frame.document()->documentDidResumeFromPageCache();
#if PLATFORM(IOS)
if (!m_client.forceLayoutOnRestoreFromPageCache())
m_frame.view()->forceLayout();
#else
m_frame.view()->forceLayout();
#endif
const ResponseVector& responses = m_documentLoader->responses();
size_t count = responses.size();
for (size_t i = 0; i < count; i++) {
const ResourceResponse& response = responses[i];
ResourceError error;
unsigned long identifier;
ResourceRequest request(response.url());
requestFromDelegate(request, identifier, error);
notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
}
checkLoadCompleteForThisFrame();
}
}
void FrameLoader::transitionToCommitted(CachedPage* cachedPage)
{
ASSERT(m_client.hasWebView());
ASSERT(m_state == FrameStateProvisional);
if (m_state != FrameStateProvisional)
return;
if (FrameView* view = m_frame.view()) {
if (ScrollAnimator* scrollAnimator = view->existingScrollAnimator())
scrollAnimator->cancelAnimations();
}
m_client.setCopiesOnScroll();
history().updateForCommit();
DocumentLoader* pdl = m_provisionalDocumentLoader.get();
if (m_documentLoader)
closeURL();
if (pdl != m_provisionalDocumentLoader)
return;
if (m_documentLoader)
m_documentLoader->stopLoadingSubresources();
if (m_documentLoader)
m_documentLoader->stopLoadingPlugIns();
setDocumentLoader(m_provisionalDocumentLoader.get());
setProvisionalDocumentLoader(0);
if (pdl != m_documentLoader) {
ASSERT(m_state == FrameStateComplete);
return;
}
setState(FrameStateCommittedPage);
#if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
if (m_frame.isMainFrame())
m_frame.page()->chrome().client().needTouchEvents(false);
#endif
DocumentLoader* dl = m_documentLoader.get();
switch (m_loadType) {
case FrameLoadType::Forward:
case FrameLoadType::Back:
case FrameLoadType::IndexedBackForward:
if (m_frame.page()) {
if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame.isMainFrame())
history().updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
history().updateForBackForwardNavigation();
if (history().currentItem() && !cachedPage)
m_pendingStateObject = history().currentItem()->stateObject();
if (cachedPage) {
DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
ASSERT(cachedDocumentLoader);
cachedDocumentLoader->setFrame(&m_frame);
m_client.transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
} else
m_client.transitionToCommittedForNewPage();
}
break;
case FrameLoadType::Reload:
case FrameLoadType::ReloadFromOrigin:
case FrameLoadType::Same:
case FrameLoadType::Replace:
history().updateForReload();
m_client.transitionToCommittedForNewPage();
break;
case FrameLoadType::Standard:
history().updateForStandardLoad();
if (m_frame.view())
m_frame.view()->setScrollbarsSuppressed(true);
m_client.transitionToCommittedForNewPage();
break;
case FrameLoadType::RedirectWithLockedBackForwardList:
history().updateForRedirectWithLockedBackForwardList();
m_client.transitionToCommittedForNewPage();
break;
default:
ASSERT_NOT_REACHED();
}
m_documentLoader->writer().setMIMEType(dl->responseMIMEType());
ASSERT(m_frame.view());
if (m_stateMachine.creatingInitialEmptyDocument())
return;
if (!m_stateMachine.committedFirstRealDocumentLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
}
void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
{
m_client.dispatchDidCancelClientRedirect();
if (!cancelWithLoadInProgress)
m_quickRedirectComing = false;
m_sentRedirectNotification = false;
}
void FrameLoader::clientRedirected(const URL& url, double seconds, double fireDate, LockBackForwardList lockBackForwardList)
{
m_client.dispatchWillPerformClientRedirect(url, seconds, fireDate);
m_sentRedirectNotification = true;
m_quickRedirectComing = (lockBackForwardList == LockBackForwardList::Yes || history().currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
}
bool FrameLoader::shouldReload(const URL& currentURL, const URL& destinationURL)
{
if (!destinationURL.hasFragmentIdentifier())
return true;
return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
}
void FrameLoader::closeOldDataSources()
{
for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
child->loader().closeOldDataSources();
if (m_documentLoader)
m_client.dispatchWillClose();
m_client.setMainFrameDocumentReady(false); }
void FrameLoader::prepareForCachedPageRestore()
{
ASSERT(!m_frame.tree().parent());
ASSERT(m_frame.page());
ASSERT(m_frame.isMainFrame());
m_frame.navigationScheduler().cancel();
closeURL();
if (m_frame.script().canExecuteScripts(NotAboutToExecuteScript)) {
DOMWindow* window = m_frame.document()->domWindow();
window->setStatus(String());
window->setDefaultStatus(String());
}
}
void FrameLoader::open(CachedFrameBase& cachedFrame)
{
m_isComplete = false;
m_didCallImplicitClose = true;
URL url = cachedFrame.url();
if (url.protocolIsInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
url.setPath("/");
started();
Document* document = cachedFrame.document();
ASSERT(document);
ASSERT(document->domWindow());
clear(document, true, true, cachedFrame.isMainFrame());
document->setInPageCache(false);
m_needsClear = true;
m_isComplete = false;
m_didCallImplicitClose = false;
m_outgoingReferrer = url.string();
FrameView* view = cachedFrame.view();
ASSERT(view);
view->setWasScrolledByUser(false);
if (m_frame.view())
view->setFrameRect(m_frame.view()->frameRect());
m_frame.setView(view);
m_frame.setDocument(document);
document->domWindow()->resumeFromPageCache();
updateFirstPartyForCookies();
cachedFrame.restore();
}
bool FrameLoader::isHostedByObjectElement() const
{
HTMLFrameOwnerElement* owner = m_frame.ownerElement();
return owner && owner->hasTagName(objectTag);
}
bool FrameLoader::isReplacing() const
{
return m_loadType == FrameLoadType::Replace;
}
void FrameLoader::setReplacing()
{
m_loadType = FrameLoadType::Replace;
}
bool FrameLoader::subframeIsLoading() const
{
for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling()) {
FrameLoader& childLoader = child->loader();
DocumentLoader* documentLoader = childLoader.documentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
documentLoader = childLoader.provisionalDocumentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
documentLoader = childLoader.policyDocumentLoader();
if (documentLoader)
return true;
}
return false;
}
void FrameLoader::willChangeTitle(DocumentLoader* loader)
{
m_client.willChangeTitle(loader);
}
FrameLoadType FrameLoader::loadType() const
{
return m_loadType;
}
CachePolicy FrameLoader::subresourceCachePolicy() const
{
if (m_isComplete)
return CachePolicyVerify;
if (m_loadType == FrameLoadType::ReloadFromOrigin)
return CachePolicyReload;
if (Frame* parentFrame = m_frame.tree().parent()) {
CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
if (parentCachePolicy != CachePolicyVerify)
return parentCachePolicy;
}
if (m_loadType == FrameLoadType::Reload)
return CachePolicyRevalidate;
const ResourceRequest& request(documentLoader()->request());
#if PLATFORM(COCOA)
if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
return CachePolicyRevalidate;
#endif
if (request.cachePolicy() == ReturnCacheDataElseLoad)
return CachePolicyHistoryBuffer;
return CachePolicyVerify;
}
void FrameLoader::checkLoadCompleteForThisFrame()
{
ASSERT(m_client.hasWebView());
switch (m_state) {
case FrameStateProvisional: {
if (m_delegateIsHandlingProvisionalLoadError)
return;
RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
if (!pdl)
return;
const ResourceError& error = pdl->mainDocumentError();
if (error.isNull())
return;
RefPtr<HistoryItem> item;
if (Page* page = m_frame.page())
if (isBackForwardLoadType(loadType()))
item = page->mainFrame().loader().history().currentItem();
bool shouldReset = !history().provisionalItem();
if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
m_delegateIsHandlingProvisionalLoadError = true;
m_client.dispatchDidFailProvisionalLoad(error);
m_delegateIsHandlingProvisionalLoadError = false;
ASSERT(!pdl->isLoading());
if (isReplacing() && !m_documentLoader.get())
setDocumentLoader(m_provisionalDocumentLoader.get());
if (pdl == m_provisionalDocumentLoader)
clearProvisionalLoad();
else if (activeDocumentLoader()) {
URL unreachableURL = activeDocumentLoader()->unreachableURL();
if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
shouldReset = false;
}
}
if (shouldReset && item)
if (Page* page = m_frame.page()) {
page->backForward().setCurrentItem(item.get());
m_frame.loader().client().updateGlobalHistoryItemForPage();
}
return;
}
case FrameStateCommittedPage: {
DocumentLoader* dl = m_documentLoader.get();
if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
return;
setState(FrameStateComplete);
m_client.forceLayoutForNonHTML();
if (m_frame.page()) {
if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadType::Reload || m_loadType == FrameLoadType::ReloadFromOrigin)
history().restoreScrollPositionAndViewState();
}
if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
return;
m_progressTracker->progressCompleted();
if (Page* page = m_frame.page()) {
if (m_frame.isMainFrame())
page->resetRelevantPaintedObjectCounter();
}
const ResourceError& error = dl->mainDocumentError();
AXObjectCache::AXLoadingEvent loadingEvent;
if (!error.isNull()) {
m_client.dispatchDidFailLoad(error);
loadingEvent = AXObjectCache::AXLoadingFailed;
} else {
m_client.dispatchDidFinishLoad();
loadingEvent = AXObjectCache::AXLoadingFinished;
}
if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache())
cache->frameLoadingEventNotification(&m_frame, loadingEvent);
return;
}
case FrameStateComplete:
m_loadType = FrameLoadType::Standard;
frameLoadCompleted();
return;
}
ASSERT_NOT_REACHED();
}
void FrameLoader::continueLoadAfterWillSubmitForm()
{
if (!m_provisionalDocumentLoader)
return;
prepareForLoadStart();
if (!m_provisionalDocumentLoader)
return;
DocumentLoader* activeDocLoader = activeDocumentLoader();
if (activeDocLoader && activeDocLoader->isLoadingMainResource())
return;
m_loadingFromCachedPage = false;
m_provisionalDocumentLoader->startLoadingMainResource();
}
static URL originatingURLFromBackForwardList(Page* page)
{
URL originalURL;
int backCount = page->backForward().backCount();
for (int backIndex = 0; backIndex <= backCount; backIndex++) {
HistoryItem* historyItem = page->backForward().itemAtIndex(-backIndex);
if (!historyItem)
continue;
originalURL = historyItem->originalURL();
if (!originalURL.isNull())
return originalURL;
}
return URL();
}
void FrameLoader::setOriginalURLForDownloadRequest(ResourceRequest& request)
{
URL originalURL;
if (!request.httpReferrer().isNull()) {
originalURL = originatingURLFromBackForwardList(m_frame.page());
}
if (originalURL.isNull())
originalURL = request.url();
if (!originalURL.protocol().isEmpty() && !originalURL.host().isEmpty()) {
unsigned port = originalURL.port();
String hostOnlyURLString;
if (port)
hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host(), ":", String::number(port));
else
hostOnlyURLString = makeString(originalURL.protocol(), "://", originalURL.host());
request.setFirstPartyForCookies(URL(URL(), hostOnlyURLString));
}
}
void FrameLoader::didLayout(LayoutMilestones milestones)
{
ASSERT(m_frame.isMainFrame());
m_client.dispatchDidLayout(milestones);
}
void FrameLoader::didFirstLayout()
{
#if PLATFORM(IOS)
if (&m_frame != &m_frame.page()->mainFrame())
return;
#endif
if (m_frame.page() && isBackForwardLoadType(m_loadType))
history().restoreScrollPositionAndViewState();
if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
}
void FrameLoader::frameLoadCompleted()
{
m_client.frameLoadCompleted();
history().updateForFrameLoadCompleted();
if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
}
void FrameLoader::detachChildren()
{
Vector<Ref<Frame>, 16> childrenToDetach;
childrenToDetach.reserveInitialCapacity(m_frame.tree().childCount());
for (Frame* child = m_frame.tree().lastChild(); child; child = child->tree().previousSibling())
childrenToDetach.uncheckedAppend(*child);
for (unsigned i = 0; i < childrenToDetach.size(); ++i)
childrenToDetach[i]->loader().detachFromParent();
}
void FrameLoader::closeAndRemoveChild(Frame* child)
{
child->tree().detachFromParent();
child->setView(0);
if (child->ownerElement() && child->page())
child->page()->decrementSubframeCount();
child->willDetachPage();
child->detachFromPage();
m_frame.tree().removeChild(child);
}
void FrameLoader::checkLoadComplete()
{
ASSERT(m_client.hasWebView());
m_shouldCallCheckLoadComplete = false;
if (!m_frame.page())
return;
Vector<Ref<Frame>, 16> frames;
for (Frame* frame = &m_frame.mainFrame(); frame; frame = frame->tree().traverseNext())
frames.append(*frame);
for (unsigned i = frames.size(); i; --i)
frames[i - 1]->loader().checkLoadCompleteForThisFrame();
}
int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
{
if (!recurse)
return m_frame.document()->cachedResourceLoader()->requestCount();
int count = 0;
for (Frame* frame = &m_frame; frame; frame = frame->tree().traverseNext(&m_frame))
count += frame->document()->cachedResourceLoader()->requestCount();
return count;
}
String FrameLoader::userAgent(const URL& url) const
{
return m_client.userAgent(url);
}
void FrameLoader::handledOnloadEvents()
{
m_client.dispatchDidHandleOnloadEvents();
if (documentLoader())
documentLoader()->handledOnloadEvents();
}
void FrameLoader::frameDetached()
{
stopAllLoaders();
m_frame.document()->stopActiveDOMObjects();
detachFromParent();
}
void FrameLoader::detachFromParent()
{
Ref<Frame> protect(m_frame);
closeURL();
history().saveScrollPositionAndViewStateToItem(history().currentItem());
detachChildren();
stopAllLoaders();
InspectorInstrumentation::frameDetachedFromParent(&m_frame);
detachViewsAndDocumentLoader();
m_progressTracker = nullptr;
if (Frame* parent = m_frame.tree().parent()) {
parent->loader().closeAndRemoveChild(&m_frame);
parent->loader().scheduleCheckCompleted();
} else {
m_frame.setView(0);
m_frame.willDetachPage();
m_frame.detachFromPage();
}
}
void FrameLoader::detachViewsAndDocumentLoader()
{
m_client.detachedFromParent2();
setDocumentLoader(0);
m_client.detachedFromParent3();
}
void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
{
addExtraFieldsToRequest(request, m_loadType, false);
}
void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
{
addExtraFieldsToRequest(request, m_loadType, true);
}
void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
{
if (request.firstPartyForCookies().isEmpty()) {
if (mainResource && m_frame.isMainFrame())
request.setFirstPartyForCookies(request.url());
else if (Document* document = m_frame.document())
request.setFirstPartyForCookies(document->firstPartyForCookies());
}
if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
return;
applyUserAgent(request);
if (!mainResource) {
if (request.isConditional())
request.setCachePolicy(ReloadIgnoringCacheData);
else if (documentLoader()->isLoadingInAPISense()) {
ResourceRequestCachePolicy mainDocumentOriginalCachePolicy = documentLoader()->originalRequest().cachePolicy();
ResourceRequestCachePolicy subresourceCachePolicy = (mainDocumentOriginalCachePolicy == ReturnCacheDataDontLoad) ? ReturnCacheDataElseLoad : mainDocumentOriginalCachePolicy;
request.setCachePolicy(subresourceCachePolicy);
} else
request.setCachePolicy(UseProtocolCachePolicy);
} else if (loadType == FrameLoadType::Reload || loadType == FrameLoadType::ReloadFromOrigin || request.isConditional())
request.setCachePolicy(ReloadIgnoringCacheData);
if (request.cachePolicy() == ReloadIgnoringCacheData) {
if (loadType == FrameLoadType::Reload)
request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
else if (loadType == FrameLoadType::ReloadFromOrigin) {
request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
request.setHTTPHeaderField(HTTPHeaderName::Pragma, "no-cache");
}
}
if (mainResource)
request.setHTTPAccept(defaultAcceptHeader);
addHTTPOriginIfNeeded(request, String());
if (request.responseContentDispositionEncodingFallbackArray().isEmpty()) {
request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_frame.document()->encoding(), m_frame.settings().defaultTextEncodingName());
}
}
void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
{
if (!request.httpOrigin().isEmpty())
return;
if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
return;
if (origin.isEmpty()) {
request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
return;
}
request.setHTTPOrigin(origin);
}
void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, LockHistory lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
{
RefPtr<FormState> formState = prpFormState;
const URL& url = inRequest.url();
RefPtr<FormData> formData = inRequest.httpBody();
const String& contentType = inRequest.httpContentType();
String origin = inRequest.httpOrigin();
ResourceRequest workingResourceRequest(url);
if (!referrer.isEmpty())
workingResourceRequest.setHTTPReferrer(referrer);
workingResourceRequest.setHTTPOrigin(origin);
workingResourceRequest.setHTTPMethod("POST");
workingResourceRequest.setHTTPBody(formData);
workingResourceRequest.setHTTPContentType(contentType);
addExtraFieldsToRequest(workingResourceRequest, loadType, true);
NavigationAction action(workingResourceRequest, loadType, true, event);
if (!frameName.isEmpty()) {
if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName)) {
targetFrame->loader().loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
return;
}
policyChecker().checkNewWindowPolicy(action, workingResourceRequest, formState.release(), frameName, [this](const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
});
return;
}
bool isRedirect = m_quickRedirectComing;
loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
if (isRedirect) {
m_quickRedirectComing = false;
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setIsClientRedirect(true);
}
}
unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
{
ASSERT(m_frame.document());
String referrer = SecurityPolicy::generateReferrerHeader(m_frame.document()->referrerPolicy(), request.url(), outgoingReferrer());
ResourceRequest initialRequest = request;
initialRequest.setTimeoutInterval(10);
if (!referrer.isEmpty())
initialRequest.setHTTPReferrer(referrer);
addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
initialRequest.setFirstPartyForCookies(m_frame.mainFrame().loader().documentLoader()->request().url());
addExtraFieldsToSubresourceRequest(initialRequest);
unsigned long identifier = 0;
ResourceRequest newRequest(initialRequest);
requestFromDelegate(newRequest, identifier, error);
if (error.isNull()) {
ASSERT(!newRequest.isNull());
if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, data);
documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
}
}
notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, request, response, data.data(), data.size(), -1, error);
return identifier;
}
const ResourceRequest& FrameLoader::originalRequest() const
{
return activeDocumentLoader()->originalRequestCopy();
}
void FrameLoader::receivedMainResourceError(const ResourceError& error)
{
Ref<Frame> protect(m_frame);
RefPtr<DocumentLoader> loader = activeDocumentLoader();
stop();
if (m_client.shouldFallBack(error))
handleFallbackContent();
if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
m_submittedFormURL = URL();
history().invalidateCurrentItemCachedPage();
if (m_sentRedirectNotification)
clientRedirectCancelledOrFinished(false);
}
checkCompleted();
if (m_frame.page())
checkLoadComplete();
}
void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
{
m_quickRedirectComing = false;
if (!shouldContinue)
return;
if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
m_provisionalDocumentLoader->stopLoading();
setProvisionalDocumentLoader(0);
}
bool isRedirect = m_quickRedirectComing || policyChecker().loadType() == FrameLoadType::RedirectWithLockedBackForwardList;
loadInSameDocument(request.url(), 0, !isRedirect);
}
bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const URL& url)
{
return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
&& loadType != FrameLoadType::Reload
&& loadType != FrameLoadType::ReloadFromOrigin
&& loadType != FrameLoadType::Same
&& !shouldReload(m_frame.document()->url(), url)
&& !m_frame.document()->isFrameSet();
}
void FrameLoader::scrollToFragmentWithParentBoundary(const URL& url)
{
FrameView* view = m_frame.view();
if (!view)
return;
RefPtr<Frame> 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)
return true;
if (!page->chrome().canRunBeforeUnloadConfirmPanel())
return true;
Vector<Ref<Frame>, 16> targetFrames;
targetFrames.append(m_frame);
for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().traverseNext(&m_frame))
targetFrames.append(*child);
bool shouldClose = false;
{
NavigationDisablerForBeforeUnload navigationDisabler;
size_t i;
for (i = 0; i < targetFrames.size(); i++) {
if (!targetFrames[i]->tree().isDescendantOf(&m_frame))
continue;
if (!targetFrames[i]->loader().handleBeforeUnloadEvent(page->chrome(), this))
break;
}
if (i == targetFrames.size())
shouldClose = true;
}
if (!shouldClose)
m_submittedFormURL = URL();
m_currentNavigationHasShownBeforeUnloadConfirmPanel = false;
return shouldClose;
}
bool FrameLoader::handleBeforeUnloadEvent(Chrome& chrome, FrameLoader* frameLoaderBeingNavigated)
{
DOMWindow* domWindow = m_frame.document()->domWindow();
if (!domWindow)
return true;
RefPtr<Document> document = m_frame.document();
if (!document->body())
return true;
RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
Page* page = m_frame.page();
page->incrementFrameHandlingBeforeUnloadEventCount();
domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
page->decrementFrameHandlingBeforeUnloadEventCount();
m_pageDismissalEventBeingDispatched = NoDismissal;
if (!beforeUnloadEvent->defaultPrevented())
document->defaultEventHandler(beforeUnloadEvent.get());
if (beforeUnloadEvent->returnValue().isNull())
return true;
if (frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel) {
document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show multiple beforeunload confirmation dialogs for the same navigation."));
return true;
}
if (frameLoaderBeingNavigated != this) {
Frame* parentFrame = m_frame.tree().parent();
while (parentFrame) {
Document* parentDocument = parentFrame->document();
if (!parentDocument)
return true;
if (!m_frame.document() || !m_frame.document()->securityOrigin()->canAccess(parentDocument->securityOrigin())) {
document->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("Blocked attempt to show beforeunload confirmation dialog on behalf of a frame with different security origin. Protocols, domains, and ports must match."));
return true;
}
if (&parentFrame->loader() == frameLoaderBeingNavigated)
break;
parentFrame = parentFrame->tree().parent();
}
ASSERT(parentFrame);
ASSERT(&parentFrame->loader() == frameLoaderBeingNavigated);
}
frameLoaderBeingNavigated->m_currentNavigationHasShownBeforeUnloadConfirmPanel = true;
String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
return chrome.runBeforeUnloadConfirmPanel(text, &m_frame);
}
void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
{
ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
bool isTargetItem = history().provisionalItem() ? history().provisionalItem()->isTargetItem() : false;
bool canContinue = shouldContinue && shouldClose();
if (!canContinue) {
if (m_quickRedirectComing)
clientRedirectCancelledOrFinished(false);
setPolicyDocumentLoader(0);
if ((isTargetItem || m_frame.isMainFrame()) && isBackForwardLoadType(policyChecker().loadType())) {
if (Page* page = m_frame.page()) {
if (HistoryItem* resetItem = m_frame.mainFrame().loader().history().currentItem()) {
page->backForward().setCurrentItem(resetItem);
m_frame.loader().client().updateGlobalHistoryItemForPage();
}
}
}
return;
}
FrameLoadType type = policyChecker().loadType();
stopAllLoaders(ShouldNotClearProvisionalItem);
if (!m_frame.page())
return;
#if ENABLE(INSPECTOR)
if (Page* page = m_frame.page()) {
if (m_frame.isMainFrame())
page->inspectorController().resume();
}
#endif
setProvisionalDocumentLoader(m_policyDocumentLoader.get());
m_loadType = type;
setState(FrameStateProvisional);
setPolicyDocumentLoader(0);
if (isBackForwardLoadType(type) && history().provisionalItem()->isInPageCache()) {
loadProvisionalItemFromCachedPage();
return;
}
if (!formState) {
continueLoadAfterWillSubmitForm();
return;
}
m_client.dispatchWillSubmitForm(formState, [this](PolicyAction action) {
policyChecker().continueLoadAfterWillSubmitForm(action);
});
}
void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
{
if (!shouldContinue)
return;
Ref<Frame> frame(m_frame);
RefPtr<Frame> mainFrame = m_client.dispatchCreatePage(action);
if (!mainFrame)
return;
if (frameName != "_blank")
mainFrame->tree().setName(frameName);
mainFrame->page()->setOpenedByDOM();
mainFrame->loader().m_client.dispatchShow();
if (!m_suppressOpenerInNewFrame) {
mainFrame->loader().setOpener(&frame.get());
mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
}
mainFrame->loader().loadWithNavigationAction(request, NavigationAction(request), LockHistory::No, FrameLoadType::Standard, formState);
}
void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
{
ASSERT(!request.isNull());
identifier = 0;
if (Page* page = m_frame.page()) {
identifier = page->progress().createUniqueIdentifier();
notifier().assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
}
ResourceRequest newRequest(request);
notifier().dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
if (newRequest.isNull())
error = cancelledError(request);
else
error = ResourceError();
request = newRequest;
}
void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource, ResourceRequest& newRequest)
{
Page* page = m_frame.page();
if (!page)
return;
if (!resource->shouldSendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
return;
if (resource->type() == CachedResource::MainResource)
return;
if (!page->areMemoryCacheClientCallsEnabled()) {
InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->resourceRequest());
m_documentLoader->didTellClientAboutLoad(resource->url());
return;
}
if (m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), newRequest, resource->response(), resource->encodedSize())) {
InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
m_documentLoader->didTellClientAboutLoad(resource->url());
return;
}
unsigned long identifier;
ResourceError error;
requestFromDelegate(newRequest, identifier, error);
InspectorInstrumentation::markResourceAsCached(page, identifier);
notifier().sendRemainingDelegateMessages(m_documentLoader.get(), identifier, newRequest, resource->response(), 0, resource->encodedSize(), 0, error);
}
void FrameLoader::applyUserAgent(ResourceRequest& request)
{
String userAgent = this->userAgent(request.url());
ASSERT(!userAgent.isNull());
request.setHTTPUserAgent(userAgent);
}
bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const URL& url, unsigned long requestIdentifier)
{
Frame& topFrame = m_frame.tree().top();
if (&m_frame == &topFrame)
return false;
XFrameOptionsDisposition disposition = parseXFrameOptionsHeader(content);
switch (disposition) {
case XFrameOptionsSameOrigin: {
RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
if (!origin->isSameSchemeHostPort(topFrame.document()->securityOrigin()))
return true;
for (Frame* frame = m_frame.tree().parent(); frame; frame = frame->tree().parent()) {
if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin()))
break;
}
return false;
}
case XFrameOptionsDeny:
return true;
case XFrameOptionsAllowAll:
return false;
case XFrameOptionsConflict:
m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Multiple 'X-Frame-Options' headers with conflicting values ('" + content + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.", requestIdentifier);
return true;
case XFrameOptionsInvalid:
m_frame.document()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + content + "' is not a recognized directive. The header will be ignored.", requestIdentifier);
return false;
case XFrameOptionsNone:
return false;
}
ASSERT_NOT_REACHED();
return false;
}
void FrameLoader::loadProvisionalItemFromCachedPage()
{
DocumentLoader* provisionalLoader = provisionalDocumentLoader();
LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().stringCenterEllipsizedToLength().utf8().data());
prepareForLoadStart();
m_loadingFromCachedPage = true;
ASSERT(provisionalLoader->timing()->navigationStart());
provisionalLoader->resetTiming();
provisionalLoader->timing()->markNavigationStart();
provisionalLoader->setCommitted(true);
commitProvisionalLoad();
}
bool FrameLoader::shouldTreatURLAsSameAsCurrent(const URL& url) const
{
if (!history().currentItem())
return false;
return url == history().currentItem()->url() || url == history().currentItem()->originalURL();
}
bool FrameLoader::shouldTreatURLAsSrcdocDocument(const URL& url) const
{
if (!equalIgnoringCase(url.string(), "about:srcdoc"))
return false;
HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement();
if (!ownerElement)
return false;
if (!ownerElement->hasTagName(iframeTag))
return false;
return ownerElement->fastHasAttribute(srcdocAttr);
}
Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
{
Frame* frame = m_frame.tree().find(name);
if (!activeDocument)
activeDocument = m_frame.document();
if (!activeDocument->canNavigate(frame))
return 0;
return frame;
}
void FrameLoader::loadSameDocumentItem(HistoryItem* item)
{
ASSERT(item->documentSequenceNumber() == history().currentItem()->documentSequenceNumber());
history().saveScrollPositionAndViewStateToItem(history().currentItem());
if (FrameView* view = m_frame.view())
view->setWasScrolledByUser(false);
history().setCurrentItem(item);
loadInSameDocument(item->url(), item->stateObject(), false);
history().restoreScrollPositionAndViewState();
}
void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType, FormSubmissionCacheLoadPolicy cacheLoadPolicy)
{
history().setProvisionalItem(item);
if (CachedPage* cachedPage = pageCache()->get(item)) {
loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
return;
}
URL itemURL = item->url();
URL itemOriginalURL = item->originalURL();
URL currentURL;
if (documentLoader())
currentURL = documentLoader()->url();
RefPtr<FormData> formData = item->formData();
ResourceRequest request(itemURL);
if (!item->referrer().isNull())
request.setHTTPReferrer(item->referrer());
NavigationAction action;
if (formData) {
formData->generateFiles(m_frame.document());
request.setHTTPMethod("POST");
request.setHTTPBody(formData);
request.setHTTPContentType(item->formContentType());
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
addHTTPOriginIfNeeded(request, securityOrigin->toString());
addExtraFieldsToRequest(request, loadType, true);
if (cacheLoadPolicy == MayAttemptCacheOnlyLoadForFormSubmissionItem) {
request.setCachePolicy(ReturnCacheDataDontLoad);
action = NavigationAction(request, loadType, false);
} else {
request.setCachePolicy(ReturnCacheDataElseLoad);
action = NavigationAction(request, NavigationTypeFormResubmitted);
}
} else {
switch (loadType) {
case FrameLoadType::Reload:
case FrameLoadType::ReloadFromOrigin:
request.setCachePolicy(ReloadIgnoringCacheData);
break;
case FrameLoadType::Back:
case FrameLoadType::Forward:
case FrameLoadType::IndexedBackForward:
if (m_stateMachine.committedFirstRealDocumentLoad())
request.setCachePolicy(ReturnCacheDataElseLoad);
break;
case FrameLoadType::Standard:
case FrameLoadType::RedirectWithLockedBackForwardList:
break;
case FrameLoadType::Same:
default:
ASSERT_NOT_REACHED();
}
addExtraFieldsToRequest(request, loadType, true);
ResourceRequest requestForOriginalURL(request);
requestForOriginalURL.setURL(itemOriginalURL);
action = NavigationAction(requestForOriginalURL, loadType, false);
}
loadWithNavigationAction(request, action, LockHistory::No, loadType, 0);
}
void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
{
m_requestedHistoryItem = item;
HistoryItem* currentItem = history().currentItem();
bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
if (sameDocumentNavigation)
loadSameDocumentItem(item);
else
loadDifferentDocumentItem(item, loadType, MayAttemptCacheOnlyLoadForFormSubmissionItem);
}
void FrameLoader::retryAfterFailedCacheOnlyMainResourceLoad()
{
ASSERT(m_state == FrameStateProvisional);
ASSERT(!m_loadingFromCachedPage);
ASSERT(isBackForwardLoadType(m_loadType));
ASSERT(history().provisionalItem()->formData());
ASSERT(history().provisionalItem() == m_requestedHistoryItem.get());
FrameLoadType loadType = m_loadType;
HistoryItem* item = history().provisionalItem();
stopAllLoaders(ShouldNotClearProvisionalItem);
loadDifferentDocumentItem(item, loadType, MayNotAttemptCacheOnlyLoadForFormSubmissionItem);
}
ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
{
ResourceError error = m_client.cancelledError(request);
error.setIsCancellation(true);
return error;
}
#if PLATFORM(IOS)
RetainPtr<CFDictionaryRef> FrameLoader::connectionProperties(ResourceLoader* loader)
{
return m_client.connectionProperties(loader->documentLoader(), loader->identifier());
}
#endif
String FrameLoader::referrer() const
{
return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
}
void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
{
if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript))
return;
Vector<Ref<DOMWrapperWorld>> worlds;
ScriptController::getAllWorlds(worlds);
for (size_t i = 0; i < worlds.size(); ++i)
dispatchDidClearWindowObjectInWorld(worlds[i].get());
}
void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
{
if (!m_frame.script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame.script().existingWindowShell(world))
return;
m_client.dispatchDidClearWindowObjectInWorld(world);
#if ENABLE(INSPECTOR)
if (Page* page = m_frame.page())
page->inspectorController().didClearWindowObjectInWorld(&m_frame, world);
#endif
InspectorInstrumentation::didClearWindowObjectInWorld(&m_frame, world);
}
void FrameLoader::dispatchGlobalObjectAvailableInAllWorlds()
{
Vector<Ref<DOMWrapperWorld>> worlds;
ScriptController::getAllWorlds(worlds);
for (size_t i = 0; i < worlds.size(); ++i)
m_client.dispatchGlobalObjectAvailable(worlds[i].get());
}
SandboxFlags FrameLoader::effectiveSandboxFlags() const
{
SandboxFlags flags = m_forcedSandboxFlags;
if (Frame* parentFrame = m_frame.tree().parent())
flags |= parentFrame->document()->sandboxFlags();
if (HTMLFrameOwnerElement* ownerElement = m_frame.ownerElement())
flags |= ownerElement->sandboxFlags();
return flags;
}
void FrameLoader::didChangeTitle(DocumentLoader* loader)
{
m_client.didChangeTitle(loader);
if (loader == m_documentLoader) {
history().setCurrentItemTitle(loader->title());
m_client.setTitle(loader->title(), loader->urlForHistory());
m_client.setMainFrameDocumentReady(true); m_client.dispatchDidReceiveTitle(loader->title());
}
#if ENABLE(REMOTE_INSPECTOR)
if (m_frame.isMainFrame())
m_frame.page()->remoteInspectorInformationDidChange();
#endif
}
void FrameLoader::didChangeIcons(IconType type)
{
m_client.dispatchDidChangeIcons(type);
}
void FrameLoader::dispatchDidCommitLoad()
{
if (m_stateMachine.creatingInitialEmptyDocument())
return;
m_client.dispatchDidCommitLoad();
if (m_frame.isMainFrame()) {
m_frame.page()->resetSeenPlugins();
m_frame.page()->resetSeenMediaEngines();
}
InspectorInstrumentation::didCommitLoad(&m_frame, m_documentLoader.get());
#if ENABLE(REMOTE_INSPECTOR)
if (m_frame.isMainFrame())
m_frame.page()->remoteInspectorInformationDidChange();
#endif
}
void FrameLoader::tellClientAboutPastMemoryCacheLoads()
{
ASSERT(m_frame.page());
ASSERT(m_frame.page()->areMemoryCacheClientCallsEnabled());
if (!m_documentLoader)
return;
Vector<ResourceRequest> pastLoads;
m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
size_t size = pastLoads.size();
for (size_t i = 0; i < size; ++i) {
CachedResource* resource = memoryCache()->resourceForRequest(pastLoads[i], m_frame.page()->sessionID());
if (!resource)
continue;
ResourceRequest request(resource->url());
m_client.dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
}
}
NetworkingContext* FrameLoader::networkingContext() const
{
return m_networkingContext.get();
}
void FrameLoader::loadProgressingStatusChanged()
{
if (auto* view = m_frame.mainFrame().view())
view->loadProgressingStatusChanged();
}
void FrameLoader::forcePageTransitionIfNeeded()
{
m_client.forcePageTransitionIfNeeded();
}
bool FrameLoaderClient::hasHTMLView() const
{
return true;
}
PassRefPtr<Frame> createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
{
ASSERT(!features.dialog || request.frameName().isEmpty());
created = false;
if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
if (RefPtr<Frame> frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
if (request.frameName() != "_self") {
if (Page* page = frame->page())
page->chrome().focus();
}
return frame.release();
}
}
if (isDocumentSandboxed(openerFrame, SandboxPopups)) {
openerFrame->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked opening '" + request.resourceRequest().url().stringCenterEllipsizedToLength() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
return nullptr;
}
FrameLoadRequest requestWithReferrer = request;
String referrer = SecurityPolicy::generateReferrerHeader(openerFrame->document()->referrerPolicy(), request.resourceRequest().url(), openerFrame->loader().outgoingReferrer());
if (!referrer.isEmpty())
requestWithReferrer.resourceRequest().setHTTPReferrer(referrer);
FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader().outgoingOrigin());
Page* oldPage = openerFrame->page();
if (!oldPage)
return nullptr;
Page* page = oldPage->chrome().createWindow(openerFrame, requestWithReferrer, features, NavigationAction(requestWithReferrer.resourceRequest()));
if (!page)
return nullptr;
RefPtr<Frame> frame = &page->mainFrame();
frame->loader().forceSandboxFlags(openerFrame->document()->sandboxFlags());
if (request.frameName() != "_blank")
frame->tree().setName(request.frameName());
page->chrome().setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
if (!frame->page())
return nullptr;
page->chrome().setStatusbarVisible(features.statusBarVisible);
if (!frame->page())
return nullptr;
page->chrome().setScrollbarsVisible(features.scrollbarsVisible);
if (!frame->page())
return nullptr;
page->chrome().setMenubarVisible(features.menuBarVisible);
if (!frame->page())
return nullptr;
page->chrome().setResizable(features.resizable);
#if !PLATFORM(IOS)
FloatSize viewportSize = page->chrome().pageRect().size();
FloatRect windowRect = page->chrome().windowRect();
if (features.xSet)
windowRect.setX(features.x);
if (features.ySet)
windowRect.setY(features.y);
if (features.widthSet && features.width)
windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
if (features.heightSet && features.height)
windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));
FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
if (!frame->page())
return nullptr;
page->chrome().setWindowRect(newWindowRect);
#else
ViewportArguments arguments;
if (features.widthSet && features.width)
arguments.width = features.width;
if (features.heightSet && features.height)
arguments.height = features.height;
frame->setViewportArguments(arguments);
#endif
if (!frame->page())
return nullptr;
page->chrome().show();
created = true;
return frame.release();
}
}