Use OptionSet for layout milestones
[WebKit-https.git] / Source / WebKit / WebProcess / WebCoreSupport / WebFrameLoaderClient.cpp
1 /*
2  * Copyright (C) 2010-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebFrameLoaderClient.h"
28
29 #include "AuthenticationManager.h"
30 #include "DataReference.h"
31 #include "DrawingArea.h"
32 #include "FindController.h"
33 #include "FormDataReference.h"
34 #include "FrameInfoData.h"
35 #include "InjectedBundle.h"
36 #include "InjectedBundleDOMWindowExtension.h"
37 #include "InjectedBundleNavigationAction.h"
38 #include "Logging.h"
39 #include "NavigationActionData.h"
40 #include "NetworkConnectionToWebProcessMessages.h"
41 #include "NetworkProcessConnection.h"
42 #include "PluginView.h"
43 #include "UserData.h"
44 #include "WKBundleAPICast.h"
45 #include "WebAutomationSessionProxy.h"
46 #include "WebBackForwardListProxy.h"
47 #include "WebCoreArgumentCoders.h"
48 #include "WebDocumentLoader.h"
49 #include "WebErrors.h"
50 #include "WebEvent.h"
51 #include "WebFrame.h"
52 #include "WebFrameNetworkingContext.h"
53 #include "WebFullScreenManager.h"
54 #include "WebNavigationDataStore.h"
55 #include "WebPage.h"
56 #include "WebPageGroupProxy.h"
57 #include "WebPageProxyMessages.h"
58 #include "WebProcess.h"
59 #include "WebProcessPoolMessages.h"
60 #include "WebsitePoliciesData.h"
61 #include <JavaScriptCore/APICast.h>
62 #include <JavaScriptCore/JSObject.h>
63 #include <WebCore/CachedFrame.h>
64 #include <WebCore/CertificateInfo.h>
65 #include <WebCore/Chrome.h>
66 #include <WebCore/DOMWrapperWorld.h>
67 #include <WebCore/DocumentLoader.h>
68 #include <WebCore/FormState.h>
69 #include <WebCore/Frame.h>
70 #include <WebCore/FrameLoadRequest.h>
71 #include <WebCore/FrameLoader.h>
72 #include <WebCore/FrameView.h>
73 #include <WebCore/HTMLAppletElement.h>
74 #include <WebCore/HTMLFormElement.h>
75 #include <WebCore/HistoryController.h>
76 #include <WebCore/HistoryItem.h>
77 #include <WebCore/MIMETypeRegistry.h>
78 #include <WebCore/MouseEvent.h>
79 #include <WebCore/NotImplemented.h>
80 #include <WebCore/Page.h>
81 #include <WebCore/PluginData.h>
82 #include <WebCore/PluginDocument.h>
83 #include <WebCore/PolicyChecker.h>
84 #include <WebCore/ProgressTracker.h>
85 #include <WebCore/ResourceError.h>
86 #include <WebCore/ResourceRequest.h>
87 #include <WebCore/ScriptController.h>
88 #include <WebCore/SecurityOriginData.h>
89 #include <WebCore/Settings.h>
90 #include <WebCore/SubframeLoader.h>
91 #include <WebCore/UIEventWithKeyState.h>
92 #include <WebCore/Widget.h>
93 #include <WebCore/WindowFeatures.h>
94 #include <wtf/NeverDestroyed.h>
95 #include <wtf/ProcessID.h>
96 #include <wtf/ProcessPrivilege.h>
97
98 namespace WebKit {
99 using namespace WebCore;
100
101 WebFrameLoaderClient::WebFrameLoaderClient()
102     : m_frame(0)
103     , m_hasSentResponseToPluginView(false)
104     , m_didCompletePageTransition(false)
105     , m_frameHasCustomContentProvider(false)
106     , m_frameCameFromPageCache(false)
107 {
108 }
109
110 WebFrameLoaderClient::~WebFrameLoaderClient()
111 {
112 }
113
114 std::optional<uint64_t> WebFrameLoaderClient::pageID() const
115 {
116     if (m_frame && m_frame->page())
117         return m_frame->page()->pageID();
118
119     return std::nullopt;
120 }
121
122 std::optional<uint64_t> WebFrameLoaderClient::frameID() const
123 {
124     if (m_frame)
125         return m_frame->frameID();
126
127     return std::nullopt;
128 }
129
130 PAL::SessionID WebFrameLoaderClient::sessionID() const
131 {
132     return m_frame && m_frame->page() ? m_frame->page()->sessionID() : PAL::SessionID::defaultSessionID();
133 }
134
135 void WebFrameLoaderClient::frameLoaderDestroyed()
136 {
137     m_frame->invalidate();
138
139     // Balances explicit ref() in WebFrame::create().
140     m_frame->deref();
141 }
142
143 bool WebFrameLoaderClient::hasHTMLView() const
144 {
145     return !m_frameHasCustomContentProvider;
146 }
147
148 bool WebFrameLoaderClient::hasWebView() const
149 {
150     return m_frame->page();
151 }
152
153 void WebFrameLoaderClient::makeRepresentation(DocumentLoader*)
154 {
155     notImplemented();
156 }
157
158 void WebFrameLoaderClient::forceLayoutForNonHTML()
159 {
160     notImplemented();
161 }
162
163 void WebFrameLoaderClient::setCopiesOnScroll()
164 {
165     notImplemented();
166 }
167
168 void WebFrameLoaderClient::detachedFromParent2()
169 {
170     WebPage* webPage = m_frame->page();
171     if (!webPage)
172         return;
173
174 #if ENABLE(RESOURCE_LOAD_STATISTICS)
175     if (m_hasFrameSpecificStorageAccess) {
176         WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForFrame(sessionID(), frameID().value(), pageID().value()), 0);
177         m_hasFrameSpecificStorageAccess = false;
178     }
179 #endif
180
181     RefPtr<API::Object> userData;
182
183     // Notify the bundle client.
184     webPage->injectedBundleLoaderClient().didRemoveFrameFromHierarchy(*webPage, *m_frame, userData);
185 }
186
187 void WebFrameLoaderClient::detachedFromParent3()
188 {
189     notImplemented();
190 }
191
192 void WebFrameLoaderClient::assignIdentifierToInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request)
193 {
194     WebPage* webPage = m_frame->page();
195     if (!webPage)
196         return;
197
198     bool pageIsProvisionallyLoading = false;
199     if (FrameLoader* frameLoader = loader->frameLoader())
200         pageIsProvisionallyLoading = frameLoader->provisionalDocumentLoader() == loader;
201
202     webPage->injectedBundleResourceLoadClient().didInitiateLoadForResource(*webPage, *m_frame, identifier, request, pageIsProvisionallyLoading);
203     webPage->addResourceRequest(identifier, request);
204 }
205
206 void WebFrameLoaderClient::dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse)
207 {
208     WebPage* webPage = m_frame->page();
209     if (!webPage)
210         return;
211
212     // The API can return a completely new request. We should ensure that at least the requester
213     // is kept, so that if this is a main resource load it's still considered as such.
214     auto requester = request.requester();
215     webPage->injectedBundleResourceLoadClient().willSendRequestForFrame(*webPage, *m_frame, identifier, request, redirectResponse);
216     if (!request.isNull())
217         request.setRequester(requester);
218 }
219
220 bool WebFrameLoaderClient::shouldUseCredentialStorage(DocumentLoader*, unsigned long identifier)
221 {
222     WebPage* webPage = m_frame->page();
223     if (!webPage)
224         return true;
225
226     return webPage->injectedBundleResourceLoadClient().shouldUseCredentialStorage(*webPage, *m_frame, identifier);
227 }
228
229 void WebFrameLoaderClient::dispatchDidReceiveAuthenticationChallenge(DocumentLoader*, unsigned long, const AuthenticationChallenge&)
230 {
231     ASSERT_NOT_REACHED();
232 }
233
234 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
235 bool WebFrameLoaderClient::canAuthenticateAgainstProtectionSpace(DocumentLoader*, unsigned long, const ProtectionSpace& protectionSpace)
236 {
237     // The WebKit 2 Networking process asks the UIProcess directly, so the WebContent process should never receive this callback.
238     ASSERT_NOT_REACHED();
239     return false;
240 }
241 #endif
242
243 void WebFrameLoaderClient::dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse& response)
244 {
245     WebPage* webPage = m_frame->page();
246     if (!webPage)
247         return;
248
249     webPage->injectedBundleResourceLoadClient().didReceiveResponseForResource(*webPage, *m_frame, identifier, response);
250 }
251
252 void WebFrameLoaderClient::dispatchDidReceiveContentLength(DocumentLoader*, unsigned long identifier, int dataLength)
253 {
254     WebPage* webPage = m_frame->page();
255     if (!webPage)
256         return;
257
258     webPage->injectedBundleResourceLoadClient().didReceiveContentLengthForResource(*webPage, *m_frame, identifier, dataLength);
259 }
260
261 #if ENABLE(DATA_DETECTION)
262 void WebFrameLoaderClient::dispatchDidFinishDataDetection(NSArray *detectionResults)
263 {
264     WebPage* webPage = m_frame->page();
265     if (!webPage)
266         return;
267     webPage->setDataDetectionResults(detectionResults);
268 }
269 #endif
270
271 void WebFrameLoaderClient::dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier)
272 {
273     WebPage* webPage = m_frame->page();
274     if (!webPage)
275         return;
276
277     webPage->injectedBundleResourceLoadClient().didFinishLoadForResource(*webPage, *m_frame, identifier);
278     webPage->removeResourceRequest(identifier);
279 }
280
281 void WebFrameLoaderClient::dispatchDidFailLoading(DocumentLoader*, unsigned long identifier, const ResourceError& error)
282 {
283     WebPage* webPage = m_frame->page();
284     if (!webPage)
285         return;
286
287     webPage->injectedBundleResourceLoadClient().didFailLoadForResource(*webPage, *m_frame, identifier, error);
288     webPage->removeResourceRequest(identifier);
289 }
290
291 bool WebFrameLoaderClient::dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int /*length*/)
292 {
293     notImplemented();
294     return false;
295 }
296
297 void WebFrameLoaderClient::dispatchDidDispatchOnloadEvents()
298 {
299     WebPage* webPage = m_frame->page();
300     if (!webPage)
301         return;
302
303     // Notify the bundle client.
304     webPage->injectedBundleLoaderClient().didHandleOnloadEventsForFrame(*webPage, *m_frame);
305 }
306
307 void WebFrameLoaderClient::dispatchDidReceiveServerRedirectForProvisionalLoad()
308 {
309     WebPage* webPage = m_frame->page();
310     if (!webPage)
311         return;
312
313     WebDocumentLoader& documentLoader = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().provisionalDocumentLoader());
314     RefPtr<API::Object> userData;
315
316     LOG(Loading, "WebProcess %i - dispatchDidReceiveServerRedirectForProvisionalLoad to request url %s", getCurrentProcessID(), documentLoader.request().url().string().utf8().data());
317
318     // Notify the bundle client.
319     webPage->injectedBundleLoaderClient().didReceiveServerRedirectForProvisionalLoadForFrame(*webPage, *m_frame, userData);
320
321     // Notify the UIProcess.
322     webPage->send(Messages::WebPageProxy::DidReceiveServerRedirectForProvisionalLoadForFrame(m_frame->frameID(), documentLoader.navigationID(), documentLoader.request(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
323 }
324
325 void WebFrameLoaderClient::dispatchDidChangeProvisionalURL()
326 {
327     WebPage* webPage = m_frame->page();
328     if (!webPage)
329         return;
330
331     WebDocumentLoader& documentLoader = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().provisionalDocumentLoader());
332     webPage->send(Messages::WebPageProxy::DidChangeProvisionalURLForFrame(m_frame->frameID(), documentLoader.navigationID(), documentLoader.url()));
333 }
334
335 void WebFrameLoaderClient::dispatchDidCancelClientRedirect()
336 {
337     WebPage* webPage = m_frame->page();
338     if (!webPage)
339         return;
340
341     // Notify the bundle client.
342     webPage->injectedBundleLoaderClient().didCancelClientRedirectForFrame(*webPage, *m_frame);
343
344     // Notify the UIProcess.
345     webPage->send(Messages::WebPageProxy::DidCancelClientRedirectForFrame(m_frame->frameID()));
346 }
347
348 void WebFrameLoaderClient::dispatchWillPerformClientRedirect(const URL& url, double interval, WallTime fireDate, LockBackForwardList lockBackForwardList)
349 {
350     WebPage* webPage = m_frame->page();
351     if (!webPage)
352         return;
353
354     // Notify the bundle client.
355     webPage->injectedBundleLoaderClient().willPerformClientRedirectForFrame(*webPage, *m_frame, url, interval, fireDate);
356
357     // Notify the UIProcess.
358     webPage->send(Messages::WebPageProxy::WillPerformClientRedirectForFrame(m_frame->frameID(), url.string(), interval, lockBackForwardList));
359 }
360
361 void WebFrameLoaderClient::dispatchDidChangeLocationWithinPage()
362 {
363     WebPage* webPage = m_frame->page();
364     if (!webPage)
365         return;
366
367     RefPtr<API::Object> userData;
368
369     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
370
371     // Notify the bundle client.
372     webPage->injectedBundleLoaderClient().didSameDocumentNavigationForFrame(*webPage, *m_frame, SameDocumentNavigationAnchorNavigation, userData);
373
374     // Notify the UIProcess.
375     webPage->send(Messages::WebPageProxy::DidSameDocumentNavigationForFrame(m_frame->frameID(), navigationID, SameDocumentNavigationAnchorNavigation, m_frame->coreFrame()->document()->url(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
376 }
377
378 void WebFrameLoaderClient::dispatchDidChangeMainDocument()
379 {
380     WebPage* webPage = m_frame->page();
381     if (!webPage)
382         return;
383
384     webPage->send(Messages::WebPageProxy::DidChangeMainDocument(m_frame->frameID()));
385 }
386
387 void WebFrameLoaderClient::dispatchWillChangeDocument(const URL& currentUrl, const URL& newUrl)
388 {
389 #if ENABLE(RESOURCE_LOAD_STATISTICS)
390     if (m_frame->isMainFrame())
391         return;
392
393     WebPage* webPage = m_frame->page();
394     if (!webPage)
395         return;
396
397     if (m_hasFrameSpecificStorageAccess && !WebCore::registrableDomainsAreEqual(currentUrl, newUrl)) {
398         WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForFrame(sessionID(), frameID().value(), pageID().value()), 0);
399         m_hasFrameSpecificStorageAccess = false;
400     }
401 #endif
402 }
403
404 void WebFrameLoaderClient::dispatchDidPushStateWithinPage()
405 {
406     WebPage* webPage = m_frame->page();
407     if (!webPage)
408         return;
409
410     RefPtr<API::Object> userData;
411
412     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
413
414     // Notify the bundle client.
415     webPage->injectedBundleLoaderClient().didSameDocumentNavigationForFrame(*webPage, *m_frame, SameDocumentNavigationSessionStatePush, userData);
416
417     // Notify the UIProcess.
418     webPage->send(Messages::WebPageProxy::DidSameDocumentNavigationForFrame(m_frame->frameID(), navigationID, SameDocumentNavigationSessionStatePush, m_frame->coreFrame()->document()->url(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
419 }
420
421 void WebFrameLoaderClient::dispatchDidReplaceStateWithinPage()
422 {
423     WebPage* webPage = m_frame->page();
424     if (!webPage)
425         return;
426
427     RefPtr<API::Object> userData;
428
429     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
430
431     // Notify the bundle client.
432     webPage->injectedBundleLoaderClient().didSameDocumentNavigationForFrame(*webPage, *m_frame, SameDocumentNavigationSessionStateReplace, userData);
433
434     // Notify the UIProcess.
435     webPage->send(Messages::WebPageProxy::DidSameDocumentNavigationForFrame(m_frame->frameID(), navigationID, SameDocumentNavigationSessionStateReplace, m_frame->coreFrame()->document()->url(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
436 }
437
438 void WebFrameLoaderClient::dispatchDidPopStateWithinPage()
439 {
440     WebPage* webPage = m_frame->page();
441     if (!webPage)
442         return;
443
444     RefPtr<API::Object> userData;
445
446     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
447
448     // Notify the bundle client.
449     webPage->injectedBundleLoaderClient().didSameDocumentNavigationForFrame(*webPage, *m_frame, SameDocumentNavigationSessionStatePop, userData);
450
451     // Notify the UIProcess.
452     webPage->send(Messages::WebPageProxy::DidSameDocumentNavigationForFrame(m_frame->frameID(), navigationID, SameDocumentNavigationSessionStatePop, m_frame->coreFrame()->document()->url(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
453 }
454
455 void WebFrameLoaderClient::dispatchWillClose()
456 {
457     notImplemented();
458 }
459
460 void WebFrameLoaderClient::dispatchDidStartProvisionalLoad()
461 {
462     WebPage* webPage = m_frame->page();
463     if (!webPage)
464         return;
465
466 #if ENABLE(FULLSCREEN_API)
467     Element* documentElement = m_frame->coreFrame()->document()->documentElement();
468     if (documentElement && documentElement->containsFullScreenElement())
469         webPage->fullScreenManager()->exitFullScreenForElement(webPage->fullScreenManager()->element());
470 #endif
471
472     webPage->findController().hideFindUI();
473     webPage->sandboxExtensionTracker().didStartProvisionalLoad(m_frame);
474
475     WebDocumentLoader& provisionalLoader = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().provisionalDocumentLoader());
476     auto& url = provisionalLoader.url();
477     RefPtr<API::Object> userData;
478
479     // Notify the bundle client.
480     webPage->injectedBundleLoaderClient().didStartProvisionalLoadForFrame(*webPage, *m_frame, userData);
481
482     auto& unreachableURL = provisionalLoader.unreachableURL();
483
484     // Notify the UIProcess.
485     webPage->send(Messages::WebPageProxy::DidStartProvisionalLoadForFrame(m_frame->frameID(), provisionalLoader.navigationID(), url, unreachableURL, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
486 }
487
488 static constexpr unsigned maxTitleLength = 1000; // Closest power of 10 above the W3C recommendation for Title length.
489
490 void WebFrameLoaderClient::dispatchDidReceiveTitle(const StringWithDirection& title)
491 {
492     WebPage* webPage = m_frame->page();
493     if (!webPage)
494         return;
495
496     auto truncatedTitle = truncateFromEnd(title, maxTitleLength);
497     
498     RefPtr<API::Object> userData;
499
500     // Notify the bundle client.
501     // FIXME: Use direction of title.
502     webPage->injectedBundleLoaderClient().didReceiveTitleForFrame(*webPage, truncatedTitle.string, *m_frame, userData);
503
504     // Notify the UIProcess.
505     webPage->send(Messages::WebPageProxy::DidReceiveTitleForFrame(m_frame->frameID(), truncatedTitle.string, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
506 }
507
508 void WebFrameLoaderClient::dispatchDidCommitLoad(std::optional<HasInsecureContent> hasInsecureContent)
509 {
510     WebPage* webPage = m_frame->page();
511     if (!webPage)
512         return;
513
514     WebDocumentLoader& documentLoader = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader());
515     RefPtr<API::Object> userData;
516
517     // Notify the bundle client.
518     webPage->injectedBundleLoaderClient().didCommitLoadForFrame(*webPage, *m_frame, userData);
519
520     webPage->sandboxExtensionTracker().didCommitProvisionalLoad(m_frame);
521
522     // Notify the UIProcess.
523     webPage->send(Messages::WebPageProxy::DidCommitLoadForFrame(m_frame->frameID(), documentLoader.navigationID(), documentLoader.response().mimeType(), m_frameHasCustomContentProvider, static_cast<uint32_t>(m_frame->coreFrame()->loader().loadType()), valueOrCompute(documentLoader.response().certificateInfo(), [] { return CertificateInfo(); }), m_frame->coreFrame()->document()->isPluginDocument(), hasInsecureContent, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
524     webPage->didCommitLoad(m_frame);
525 }
526
527 void WebFrameLoaderClient::dispatchDidFailProvisionalLoad(const ResourceError& error)
528 {
529     WebPage* webPage = m_frame->page();
530     if (!webPage)
531         return;
532
533     RefPtr<API::Object> userData;
534
535     // Notify the bundle client.
536     webPage->injectedBundleLoaderClient().didFailProvisionalLoadWithErrorForFrame(*webPage, *m_frame, error, userData);
537
538     webPage->sandboxExtensionTracker().didFailProvisionalLoad(m_frame);
539
540     // FIXME: This is gross. This is necessary because if the client calls WKBundlePageStopLoading() from within the didFailProvisionalLoadWithErrorForFrame
541     // injected bundle client call, that will cause the provisional DocumentLoader to be disconnected from the Frame, and didDistroyNavigation message
542     // to be sent to the UIProcess (and the destruction of the DocumentLoader). If that happens, and we had captured the navigationID before injected bundle 
543     // client call, the DidFailProvisionalLoadForFrame would send a navigationID of a destroyed Navigation, and the UIProcess would not be able to find it
544     // in its table.
545     //
546     // A better solution to this problem would be find a clean way to postpone the disconnection of the DocumentLoader from the Frame until
547     // the entire FrameLoaderClient function was complete.
548     uint64_t navigationID = 0;
549     if (auto documentLoader = m_frame->coreFrame()->loader().provisionalDocumentLoader())
550         navigationID = static_cast<WebDocumentLoader*>(documentLoader)->navigationID();
551
552     // Notify the UIProcess.
553     WebCore::Frame* coreFrame = m_frame ? m_frame->coreFrame() : nullptr;
554     webPage->send(Messages::WebPageProxy::DidFailProvisionalLoadForFrame(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), navigationID, m_frame->coreFrame()->loader().provisionalLoadErrorBeingHandledURL(), error, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
555
556     // If we have a load listener, notify it.
557     if (WebFrame::LoadListener* loadListener = m_frame->loadListener())
558         loadListener->didFailLoad(m_frame, error.isCancellation());
559 }
560
561 void WebFrameLoaderClient::dispatchDidFailLoad(const ResourceError& error)
562 {
563     WebPage* webPage = m_frame->page();
564     if (!webPage)
565         return;
566
567     RefPtr<API::Object> userData;
568
569     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
570
571     // Notify the bundle client.
572     webPage->injectedBundleLoaderClient().didFailLoadWithErrorForFrame(*webPage, *m_frame, error, userData);
573
574     // Notify the UIProcess.
575     webPage->send(Messages::WebPageProxy::DidFailLoadForFrame(m_frame->frameID(), navigationID, error, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
576
577     // If we have a load listener, notify it.
578     if (WebFrame::LoadListener* loadListener = m_frame->loadListener())
579         loadListener->didFailLoad(m_frame, error.isCancellation());
580 }
581
582 void WebFrameLoaderClient::dispatchDidFinishDocumentLoad()
583 {
584     WebPage* webPage = m_frame->page();
585     if (!webPage)
586         return;
587
588     RefPtr<API::Object> userData;
589
590     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
591
592     // Notify the bundle client.
593     webPage->injectedBundleLoaderClient().didFinishDocumentLoadForFrame(*webPage, *m_frame, userData);
594
595     // Notify the UIProcess.
596     webPage->send(Messages::WebPageProxy::DidFinishDocumentLoadForFrame(m_frame->frameID(), navigationID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
597 }
598
599 void WebFrameLoaderClient::dispatchDidFinishLoad()
600 {
601     WebPage* webPage = m_frame->page();
602     if (!webPage)
603         return;
604
605     RefPtr<API::Object> userData;
606
607     auto navigationID = static_cast<WebDocumentLoader&>(*m_frame->coreFrame()->loader().documentLoader()).navigationID();
608
609     // Notify the bundle client.
610     webPage->injectedBundleLoaderClient().didFinishLoadForFrame(*webPage, *m_frame, userData);
611
612     // Notify the UIProcess.
613     webPage->send(Messages::WebPageProxy::DidFinishLoadForFrame(m_frame->frameID(), navigationID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
614
615     // If we have a load listener, notify it.
616     if (WebFrame::LoadListener* loadListener = m_frame->loadListener())
617         loadListener->didFinishLoad(m_frame);
618
619     webPage->didFinishLoad(m_frame);
620 }
621
622 void WebFrameLoaderClient::forcePageTransitionIfNeeded()
623 {
624     if (m_didCompletePageTransition)
625         return;
626
627     WebPage* webPage = m_frame->page();
628     if (!webPage)
629         return;
630
631     webPage->didCompletePageTransition();
632     m_didCompletePageTransition = true;
633 }
634
635 void WebFrameLoaderClient::dispatchDidReachLayoutMilestone(OptionSet<WebCore::LayoutMilestone> milestones)
636 {
637     WebPage* webPage = m_frame->page();
638     if (!webPage)
639         return;
640
641     RefPtr<API::Object> userData;
642
643     if (milestones & DidFirstLayout) {
644         // FIXME: We should consider removing the old didFirstLayout API since this is doing double duty with the
645         // new didLayout API.
646         webPage->injectedBundleLoaderClient().didFirstLayoutForFrame(*webPage, *m_frame, userData);
647         webPage->send(Messages::WebPageProxy::DidFirstLayoutForFrame(m_frame->frameID(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
648
649 #if PLATFORM(MAC)
650         // FIXME: Do this on DidFirstVisuallyNonEmptyLayout when Mac Safari is able to handle it (<rdar://problem/17580021>)
651         if (m_frame->isMainFrame() && !m_didCompletePageTransition && !webPage->corePage()->settings().suppressesIncrementalRendering()) {
652             webPage->didCompletePageTransition();
653             m_didCompletePageTransition = true;
654         }
655 #endif
656
657 #if USE(COORDINATED_GRAPHICS)
658         // Make sure viewport properties are dispatched on the main frame by the time the first layout happens.
659         ASSERT(!webPage->useFixedLayout() || m_frame != m_frame->page()->mainWebFrame() || m_frame->coreFrame()->document()->didDispatchViewportPropertiesChanged());
660 #endif
661     }
662
663     // Send this after DidFirstLayout-specific calls since some clients expect to get those messages first.
664     webPage->dispatchDidReachLayoutMilestone(milestones);
665
666     if (milestones & DidFirstVisuallyNonEmptyLayout) {
667         if (m_frame->isMainFrame() && !m_didCompletePageTransition && !webPage->corePage()->settings().suppressesIncrementalRendering()) {
668             webPage->didCompletePageTransition();
669             m_didCompletePageTransition = true;
670         }
671
672         // FIXME: We should consider removing the old didFirstVisuallyNonEmptyLayoutForFrame API since this is doing
673         // double duty with the new didLayout API.
674         webPage->injectedBundleLoaderClient().didFirstVisuallyNonEmptyLayoutForFrame(*webPage, *m_frame, userData);
675         webPage->send(Messages::WebPageProxy::DidFirstVisuallyNonEmptyLayoutForFrame(m_frame->frameID(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
676     }
677 }
678
679 void WebFrameLoaderClient::dispatchDidLayout()
680 {
681     WebPage* webPage = m_frame->page();
682     if (!webPage)
683         return;
684
685     // Notify the bundle client.
686     webPage->injectedBundleLoaderClient().didLayoutForFrame(*webPage, *m_frame);
687
688     webPage->recomputeShortCircuitHorizontalWheelEventsState();
689
690 #if PLATFORM(IOS_FAMILY)
691     webPage->updateSelectionAppearance();
692 #endif
693
694     // NOTE: Unlike the other layout notifications, this does not notify the
695     // the UIProcess for every call.
696
697     if (m_frame == m_frame->page()->mainWebFrame()) {
698         // FIXME: Remove at the soonest possible time.
699         webPage->send(Messages::WebPageProxy::SetRenderTreeSize(webPage->renderTreeSize()));
700         webPage->mainFrameDidLayout();
701     }
702 }
703
704 Frame* WebFrameLoaderClient::dispatchCreatePage(const NavigationAction& navigationAction)
705 {
706     WebPage* webPage = m_frame->page();
707     if (!webPage)
708         return nullptr;
709
710     // Just call through to the chrome client.
711     FrameLoadRequest frameLoadRequest { *m_frame->coreFrame()->document(), m_frame->coreFrame()->document()->securityOrigin(), navigationAction.resourceRequest(), { }, LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, navigationAction.shouldOpenExternalURLsPolicy(), InitiatedByMainFrame::Unknown };
712     Page* newPage = webPage->corePage()->chrome().createWindow(*m_frame->coreFrame(), frameLoadRequest, { }, navigationAction);
713     if (!newPage)
714         return nullptr;
715     
716     return &newPage->mainFrame();
717 }
718
719 void WebFrameLoaderClient::dispatchShow()
720 {
721     WebPage* webPage = m_frame->page();
722     if (!webPage)
723         return;
724
725     webPage->show();
726 }
727
728 void WebFrameLoaderClient::dispatchDecidePolicyForResponse(const ResourceResponse& response, const ResourceRequest& request, FramePolicyFunction&& function)
729 {
730     WebPage* webPage = m_frame ? m_frame->page() : nullptr;
731     if (!webPage) {
732         function(PolicyAction::Ignore);
733         return;
734     }
735
736     if (!request.url().string()) {
737         function(PolicyAction::Use);
738         return;
739     }
740
741     RefPtr<API::Object> userData;
742
743     // Notify the bundle client.
744     WKBundlePagePolicyAction policy = webPage->injectedBundlePolicyClient().decidePolicyForResponse(webPage, m_frame, response, request, userData);
745     if (policy == WKBundlePagePolicyActionUse) {
746         function(PolicyAction::Use);
747         return;
748     }
749
750     bool canShowResponse = webPage->canShowResponse(response);
751
752     WebCore::Frame* coreFrame = m_frame->coreFrame();
753     auto* policyDocumentLoader = coreFrame ? coreFrame->loader().provisionalDocumentLoader() : nullptr;
754     auto navigationID = policyDocumentLoader ? static_cast<WebDocumentLoader&>(*policyDocumentLoader).navigationID() : 0;
755     
756     Ref<WebFrame> protector(*m_frame);
757     uint64_t listenerID = m_frame->setUpPolicyListener(WTFMove(function), WebFrame::ForNavigationAction::No);
758     if (!webPage->send(Messages::WebPageProxy::DecidePolicyForResponse(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), navigationID, response, request, canShowResponse, listenerID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get()))))
759         m_frame->didReceivePolicyDecision(listenerID, PolicyAction::Ignore, 0, { }, { });
760 }
761
762 void WebFrameLoaderClient::dispatchDecidePolicyForNewWindowAction(const NavigationAction& navigationAction, const ResourceRequest& request, FormState* formState, const String& frameName, FramePolicyFunction&& function)
763 {
764     WebPage* webPage = m_frame ? m_frame->page() : nullptr;
765     if (!webPage) {
766         function(PolicyAction::Ignore);
767         return;
768     }
769
770     RefPtr<API::Object> userData;
771
772     RefPtr<InjectedBundleNavigationAction> action = InjectedBundleNavigationAction::create(m_frame, navigationAction, formState);
773
774     // Notify the bundle client.
775     WKBundlePagePolicyAction policy = webPage->injectedBundlePolicyClient().decidePolicyForNewWindowAction(webPage, m_frame, action.get(), request, frameName, userData);
776     if (policy == WKBundlePagePolicyActionUse) {
777         function(PolicyAction::Use);
778         return;
779     }
780
781     uint64_t listenerID = m_frame->setUpPolicyListener(WTFMove(function), WebFrame::ForNavigationAction::No);
782
783     NavigationActionData navigationActionData;
784     navigationActionData.navigationType = action->navigationType();
785     navigationActionData.modifiers = action->modifiers();
786     navigationActionData.mouseButton = action->mouseButton();
787     navigationActionData.syntheticClickType = action->syntheticClickType();
788     navigationActionData.clickLocationInRootViewCoordinates = action->clickLocationInRootViewCoordinates();
789     navigationActionData.userGestureTokenIdentifier = WebProcess::singleton().userGestureTokenIdentifier(navigationAction.userGestureToken());
790     navigationActionData.canHandleRequest = webPage->canHandleRequest(request);
791     navigationActionData.shouldOpenExternalURLsPolicy = navigationAction.shouldOpenExternalURLsPolicy();
792     navigationActionData.downloadAttribute = navigationAction.downloadAttribute();
793
794     WebCore::Frame* coreFrame = m_frame ? m_frame->coreFrame() : nullptr;
795     webPage->send(Messages::WebPageProxy::DecidePolicyForNewWindowAction(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), navigationActionData, request, frameName, listenerID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
796 }
797
798 void WebFrameLoaderClient::applyToDocumentLoader(WebsitePoliciesData&& websitePolicies)
799 {
800     if (!m_frame)
801         return;
802     auto* coreFrame = m_frame->coreFrame();
803     if (!coreFrame)
804         return;
805     WebDocumentLoader* documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().policyDocumentLoader());
806     if (!documentLoader)
807         documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().provisionalDocumentLoader());
808     if (!documentLoader)
809         documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().documentLoader());
810     if (!documentLoader)
811         return;
812
813     WebsitePoliciesData::applyToDocumentLoader(WTFMove(websitePolicies), *documentLoader);
814 }
815
816 void WebFrameLoaderClient::dispatchDecidePolicyForNavigationAction(const NavigationAction& navigationAction, const ResourceRequest& request, const ResourceResponse& redirectResponse, FormState* formState, PolicyDecisionMode policyDecisionMode, ShouldSkipSafeBrowsingCheck shouldSkipSafeBrowsingCheck, FramePolicyFunction&& function)
817 {
818     WebPage* webPage = m_frame ? m_frame->page() : nullptr;
819     if (!webPage) {
820         function(PolicyAction::Ignore);
821         return;
822     }
823
824     LOG(Loading, "WebProcess %i - dispatchDecidePolicyForNavigationAction to request url %s", getCurrentProcessID(), request.url().string().utf8().data());
825
826     // Always ignore requests with empty URLs. 
827     if (request.isEmpty()) {
828         function(PolicyAction::Ignore);
829         return;
830     }
831
832     RefPtr<API::Object> userData;
833
834     Ref<InjectedBundleNavigationAction> action = InjectedBundleNavigationAction::create(m_frame, navigationAction, formState);
835
836     // Notify the bundle client.
837     WKBundlePagePolicyAction policy = webPage->injectedBundlePolicyClient().decidePolicyForNavigationAction(webPage, m_frame, action.ptr(), request, userData);
838     if (policy == WKBundlePagePolicyActionUse) {
839         function(PolicyAction::Use);
840         return;
841     }
842     
843     uint64_t listenerID = m_frame->setUpPolicyListener(WTFMove(function), WebFrame::ForNavigationAction::Yes);
844
845     ASSERT(navigationAction.requester());
846     auto requester = navigationAction.requester().value();
847
848     FrameInfoData originatingFrameInfoData;
849     originatingFrameInfoData.isMainFrame = navigationAction.initiatedByMainFrame() == InitiatedByMainFrame::Yes;
850     originatingFrameInfoData.request = ResourceRequest { requester.url() };
851     originatingFrameInfoData.securityOrigin = requester.securityOrigin().data();
852     if (requester.frameID() && WebProcess::singleton().webFrame(requester.frameID()))
853         originatingFrameInfoData.frameID = requester.frameID();
854
855     uint64_t originatingPageID = requester.pageID() && WebProcess::singleton().webPage(requester.pageID()) ? requester.pageID() : 0;
856
857     NavigationActionData navigationActionData;
858     navigationActionData.navigationType = action->navigationType();
859     navigationActionData.modifiers = action->modifiers();
860     navigationActionData.mouseButton = action->mouseButton();
861     navigationActionData.syntheticClickType = action->syntheticClickType();
862     navigationActionData.clickLocationInRootViewCoordinates = action->clickLocationInRootViewCoordinates();
863     navigationActionData.userGestureTokenIdentifier = WebProcess::singleton().userGestureTokenIdentifier(navigationAction.userGestureToken());
864     navigationActionData.canHandleRequest = webPage->canHandleRequest(request);
865     navigationActionData.shouldOpenExternalURLsPolicy = navigationAction.shouldOpenExternalURLsPolicy();
866     navigationActionData.downloadAttribute = navigationAction.downloadAttribute();
867     navigationActionData.isRedirect = !redirectResponse.isNull();
868     navigationActionData.treatAsSameOriginNavigation = navigationAction.treatAsSameOriginNavigation();
869     navigationActionData.hasOpenedFrames = navigationAction.hasOpenedFrames();
870     navigationActionData.openedViaWindowOpenWithOpener = navigationAction.openedViaWindowOpenWithOpener();
871     navigationActionData.opener = navigationAction.opener();
872     if (auto& requester = navigationAction.requester())
873         navigationActionData.requesterOrigin = requester->securityOrigin().data();
874     navigationActionData.targetBackForwardItemIdentifier = navigationAction.targetBackForwardItemIdentifier();
875     navigationActionData.lockHistory = navigationAction.lockHistory();
876     navigationActionData.lockBackForwardList = navigationAction.lockBackForwardList();
877
878     WebCore::Frame* coreFrame = m_frame->coreFrame();
879     if (!coreFrame)
880         return function(PolicyAction::Ignore);
881     WebDocumentLoader* documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().policyDocumentLoader());
882     if (!documentLoader) {
883         // FIXME: When we receive a redirect after the navigation policy has been decided for the initial request,
884         // the provisional load's DocumentLoader needs to receive navigation policy decisions. We need a better model for this state.
885         documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().provisionalDocumentLoader());
886     }
887     if (!documentLoader)
888         documentLoader = static_cast<WebDocumentLoader*>(coreFrame->loader().documentLoader());
889
890     navigationActionData.clientRedirectSourceForHistory = documentLoader->clientRedirectSourceForHistory();
891
892     // Notify the UIProcess.
893     Ref<WebFrame> protect(*m_frame);
894
895     if (policyDecisionMode == PolicyDecisionMode::Synchronous) {
896         uint64_t newNavigationID;
897         PolicyAction policyAction;
898         DownloadID downloadID;
899         std::optional<WebsitePoliciesData> websitePolicies;
900
901         if (!webPage->sendSync(Messages::WebPageProxy::DecidePolicyForNavigationActionSync(m_frame->frameID(), m_frame->isMainFrame(), SecurityOriginData::fromFrame(coreFrame), documentLoader->navigationID(), navigationActionData, originatingFrameInfoData, originatingPageID, navigationAction.resourceRequest(), request, IPC::FormDataReference { request.httpBody() }, redirectResponse, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get()), shouldSkipSafeBrowsingCheck), Messages::WebPageProxy::DecidePolicyForNavigationActionSync::Reply(policyAction, newNavigationID, downloadID, websitePolicies))) {
902             m_frame->didReceivePolicyDecision(listenerID, PolicyAction::Ignore, 0, { }, { });
903             return;
904         }
905
906         m_frame->didReceivePolicyDecision(listenerID, policyAction, 0, downloadID, { });
907         return;
908     }
909
910     ASSERT(policyDecisionMode == PolicyDecisionMode::Asynchronous);
911     if (!webPage->send(Messages::WebPageProxy::DecidePolicyForNavigationActionAsync(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), documentLoader->navigationID(), navigationActionData, originatingFrameInfoData, originatingPageID, navigationAction.resourceRequest(), request, IPC::FormDataReference { request.httpBody() }, redirectResponse, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get()), shouldSkipSafeBrowsingCheck, listenerID)))
912         m_frame->didReceivePolicyDecision(listenerID, PolicyAction::Ignore, 0, { }, { });
913 }
914
915 void WebFrameLoaderClient::cancelPolicyCheck()
916 {
917     m_frame->invalidatePolicyListener();
918 }
919
920 void WebFrameLoaderClient::dispatchUnableToImplementPolicy(const ResourceError& error)
921 {
922     WebPage* webPage = m_frame->page();
923     if (!webPage)
924         return;
925
926     RefPtr<API::Object> userData;
927
928     // Notify the bundle client.
929     webPage->injectedBundlePolicyClient().unableToImplementPolicy(webPage, m_frame, error, userData);
930
931     // Notify the UIProcess.
932     webPage->send(Messages::WebPageProxy::UnableToImplementPolicy(m_frame->frameID(), error, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
933 }
934
935 void WebFrameLoaderClient::dispatchWillSendSubmitEvent(Ref<FormState>&& formState)
936 {
937     auto* webPage = m_frame->page();
938     if (!webPage)
939         return;
940
941     auto& form = formState->form();
942
943     ASSERT(formState->sourceDocument().frame());
944     auto* sourceFrame = WebFrame::fromCoreFrame(*formState->sourceDocument().frame());
945     ASSERT(sourceFrame);
946
947     webPage->injectedBundleFormClient().willSendSubmitEvent(webPage, &form, m_frame, sourceFrame, formState->textFieldValues());
948 }
949
950 void WebFrameLoaderClient::dispatchWillSubmitForm(FormState& formState, CompletionHandler<void()>&& completionHandler)
951 {
952     WebPage* webPage = m_frame->page();
953     if (!webPage) {
954         completionHandler();
955         return;
956     }
957
958     auto& form = formState.form();
959
960     auto* sourceCoreFrame = formState.sourceDocument().frame();
961     RELEASE_ASSERT(sourceCoreFrame);
962     auto* sourceFrame = WebFrame::fromCoreFrame(*sourceCoreFrame);
963     ASSERT(sourceFrame);
964
965     auto& values = formState.textFieldValues();
966
967     RefPtr<API::Object> userData;
968     webPage->injectedBundleFormClient().willSubmitForm(webPage, &form, m_frame, sourceFrame, values, userData);
969
970     uint64_t listenerID = m_frame->setUpWillSubmitFormListener(WTFMove(completionHandler));
971
972     webPage->send(Messages::WebPageProxy::WillSubmitForm(m_frame->frameID(), sourceFrame->frameID(), values, listenerID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
973 }
974
975 void WebFrameLoaderClient::revertToProvisionalState(DocumentLoader*)
976 {
977     notImplemented();
978 }
979
980 void WebFrameLoaderClient::setMainDocumentError(DocumentLoader*, const ResourceError& error)
981 {
982     if (!m_pluginView)
983         return;
984     
985     m_pluginView->manualLoadDidFail(error);
986     m_pluginView = nullptr;
987     m_hasSentResponseToPluginView = false;
988 }
989
990 void WebFrameLoaderClient::setMainFrameDocumentReady(bool)
991 {
992     notImplemented();
993 }
994
995 void WebFrameLoaderClient::startDownload(const ResourceRequest& request, const String& suggestedName)
996 {
997     m_frame->startDownload(request, suggestedName);
998 }
999
1000 void WebFrameLoaderClient::willChangeTitle(DocumentLoader*)
1001 {
1002     notImplemented();
1003 }
1004
1005 void WebFrameLoaderClient::didChangeTitle(DocumentLoader*)
1006 {
1007     notImplemented();
1008 }
1009
1010 void WebFrameLoaderClient::willReplaceMultipartContent()
1011 {
1012     WebPage* webPage = m_frame->page();
1013     if (!webPage)
1014         return;
1015     webPage->willReplaceMultipartContent(*m_frame);
1016 }
1017
1018 void WebFrameLoaderClient::didReplaceMultipartContent()
1019 {
1020     WebPage* webPage = m_frame->page();
1021     if (!webPage)
1022         return;
1023     webPage->didReplaceMultipartContent(*m_frame);
1024 }
1025
1026 void WebFrameLoaderClient::committedLoad(DocumentLoader* loader, const char* data, int length)
1027 {
1028     if (!m_pluginView)
1029         loader->commitData(data, length);
1030
1031     // If the document is a stand-alone media document, now is the right time to cancel the WebKit load.
1032     // FIXME: This code should be shared across all ports. <http://webkit.org/b/48762>.
1033     if (m_frame->coreFrame()->document()->isMediaDocument())
1034         loader->cancelMainResourceLoad(pluginWillHandleLoadError(loader->response()));
1035
1036     // Calling commitData did not create the plug-in view.
1037     if (!m_pluginView)
1038         return;
1039
1040     if (!m_hasSentResponseToPluginView) {
1041         m_pluginView->manualLoadDidReceiveResponse(loader->response());
1042         // manualLoadDidReceiveResponse sets up a new stream to the plug-in. on a full-page plug-in, a failure in
1043         // setting up this stream can cause the main document load to be cancelled, setting m_pluginView
1044         // to null
1045         if (!m_pluginView)
1046             return;
1047         m_hasSentResponseToPluginView = true;
1048     }
1049     m_pluginView->manualLoadDidReceiveData(data, length);
1050 }
1051
1052 void WebFrameLoaderClient::finishedLoading(DocumentLoader* loader)
1053 {
1054     if (!m_pluginView) {
1055         if (m_frameHasCustomContentProvider) {
1056             WebPage* webPage = m_frame->page();
1057             if (!webPage)
1058                 return;
1059
1060             RefPtr<SharedBuffer> mainResourceData = loader->mainResourceData();
1061             IPC::DataReference dataReference(reinterpret_cast<const uint8_t*>(mainResourceData ? mainResourceData->data() : 0), mainResourceData ? mainResourceData->size() : 0);
1062             webPage->send(Messages::WebPageProxy::DidFinishLoadingDataForCustomContentProvider(loader->response().suggestedFilename(), dataReference));
1063         }
1064
1065         return;
1066     }
1067
1068     // If we just received an empty response without any data, we won't have sent a response to the plug-in view.
1069     // Make sure to do this before calling manualLoadDidFinishLoading.
1070     if (!m_hasSentResponseToPluginView) {
1071         m_pluginView->manualLoadDidReceiveResponse(loader->response());
1072
1073         // Protect against the above call nulling out the plug-in (by trying to cancel the load for example).
1074         if (!m_pluginView)
1075             return;
1076     }
1077
1078     m_pluginView->manualLoadDidFinishLoading();
1079     m_pluginView = nullptr;
1080     m_hasSentResponseToPluginView = false;
1081 }
1082
1083 void WebFrameLoaderClient::updateGlobalHistory()
1084 {
1085     WebPage* webPage = m_frame->page();
1086     if (!webPage)
1087         return;
1088
1089     DocumentLoader* loader = m_frame->coreFrame()->loader().documentLoader();
1090
1091     WebNavigationDataStore data;
1092     data.url = loader->url().string();
1093     // FIXME: Use direction of title.
1094     data.title = loader->title().string;
1095     data.originalRequest = loader->originalRequestCopy();
1096     data.response = loader->response();
1097
1098     webPage->send(Messages::WebPageProxy::DidNavigateWithNavigationData(data, m_frame->frameID()));
1099 }
1100
1101 void WebFrameLoaderClient::updateGlobalHistoryRedirectLinks()
1102 {
1103     WebPage* webPage = m_frame->page();
1104     if (!webPage)
1105         return;
1106
1107     DocumentLoader* loader = m_frame->coreFrame()->loader().documentLoader();
1108     ASSERT(loader->unreachableURL().isEmpty());
1109
1110     // Client redirect
1111     if (!loader->clientRedirectSourceForHistory().isNull()) {
1112         webPage->send(Messages::WebPageProxy::DidPerformClientRedirect(
1113             loader->clientRedirectSourceForHistory(), loader->clientRedirectDestinationForHistory(), m_frame->frameID()));
1114     }
1115
1116     // Server redirect
1117     if (!loader->serverRedirectSourceForHistory().isNull()) {
1118         webPage->send(Messages::WebPageProxy::DidPerformServerRedirect(
1119             loader->serverRedirectSourceForHistory(), loader->serverRedirectDestinationForHistory(), m_frame->frameID()));
1120     }
1121 }
1122
1123 bool WebFrameLoaderClient::shouldGoToHistoryItem(HistoryItem& item) const
1124 {
1125     WebPage* webPage = m_frame->page();
1126     if (!webPage)
1127         return false;
1128     webPage->send(Messages::WebPageProxy::WillGoToBackForwardListItem(item.identifier(), item.isInPageCache()));
1129     return true;
1130 }
1131
1132 void WebFrameLoaderClient::didDisplayInsecureContent()
1133 {
1134     WebPage* webPage = m_frame->page();
1135     if (!webPage)
1136         return;
1137
1138     RefPtr<API::Object> userData;
1139
1140     webPage->injectedBundleLoaderClient().didDisplayInsecureContentForFrame(*webPage, *m_frame, userData);
1141
1142     webPage->send(Messages::WebPageProxy::DidDisplayInsecureContentForFrame(m_frame->frameID(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
1143 }
1144
1145 void WebFrameLoaderClient::didRunInsecureContent(SecurityOrigin&, const URL&)
1146 {
1147     WebPage* webPage = m_frame->page();
1148     if (!webPage)
1149         return;
1150
1151     RefPtr<API::Object> userData;
1152
1153     webPage->injectedBundleLoaderClient().didRunInsecureContentForFrame(*webPage, *m_frame, userData);
1154
1155     webPage->send(Messages::WebPageProxy::DidRunInsecureContentForFrame(m_frame->frameID(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
1156 }
1157
1158 void WebFrameLoaderClient::didDetectXSS(const URL&, bool)
1159 {
1160     WebPage* webPage = m_frame->page();
1161     if (!webPage)
1162         return;
1163
1164     RefPtr<API::Object> userData;
1165
1166     webPage->injectedBundleLoaderClient().didDetectXSSForFrame(*webPage, *m_frame, userData);
1167
1168     webPage->send(Messages::WebPageProxy::DidDetectXSSForFrame(m_frame->frameID(), UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
1169 }
1170
1171 ResourceError WebFrameLoaderClient::cancelledError(const ResourceRequest& request)
1172 {
1173     return WebKit::cancelledError(request);
1174 }
1175
1176 ResourceError WebFrameLoaderClient::blockedError(const ResourceRequest& request)
1177 {
1178     return WebKit::blockedError(request);
1179 }
1180
1181 ResourceError WebFrameLoaderClient::blockedByContentBlockerError(const ResourceRequest& request)
1182 {
1183     return WebKit::blockedByContentBlockerError(request);
1184 }
1185
1186 ResourceError WebFrameLoaderClient::cannotShowURLError(const ResourceRequest& request)
1187 {
1188     return WebKit::cannotShowURLError(request);
1189 }
1190
1191 ResourceError WebFrameLoaderClient::interruptedForPolicyChangeError(const ResourceRequest& request)
1192 {
1193     return WebKit::interruptedForPolicyChangeError(request);
1194 }
1195
1196 #if ENABLE(CONTENT_FILTERING)
1197 ResourceError WebFrameLoaderClient::blockedByContentFilterError(const ResourceRequest& request)
1198 {
1199     return WebKit::blockedByContentFilterError(request);
1200 }
1201 #endif
1202
1203 ResourceError WebFrameLoaderClient::cannotShowMIMETypeError(const ResourceResponse& response)
1204 {
1205     return WebKit::cannotShowMIMETypeError(response);
1206 }
1207
1208 ResourceError WebFrameLoaderClient::fileDoesNotExistError(const ResourceResponse& response)
1209 {
1210     return WebKit::fileDoesNotExistError(response);
1211 }
1212
1213 ResourceError WebFrameLoaderClient::pluginWillHandleLoadError(const ResourceResponse& response)
1214 {
1215     return WebKit::pluginWillHandleLoadError(response);
1216 }
1217
1218 bool WebFrameLoaderClient::shouldFallBack(const ResourceError& error)
1219 {
1220     static NeverDestroyed<const ResourceError> cancelledError(this->cancelledError(ResourceRequest()));
1221     static NeverDestroyed<const ResourceError> pluginWillHandleLoadError(this->pluginWillHandleLoadError(ResourceResponse()));
1222
1223     if (error.errorCode() == cancelledError.get().errorCode() && error.domain() == cancelledError.get().domain())
1224         return false;
1225
1226     if (error.errorCode() == pluginWillHandleLoadError.get().errorCode() && error.domain() == pluginWillHandleLoadError.get().domain())
1227         return false;
1228
1229     return true;
1230 }
1231
1232 bool WebFrameLoaderClient::canHandleRequest(const ResourceRequest&) const
1233 {
1234     notImplemented();
1235     return true;
1236 }
1237
1238 bool WebFrameLoaderClient::canShowMIMEType(const String& /*MIMEType*/) const
1239 {
1240     notImplemented();
1241     return true;
1242 }
1243
1244 bool WebFrameLoaderClient::canShowMIMETypeAsHTML(const String& /*MIMEType*/) const
1245 {
1246     return true;
1247 }
1248
1249 bool WebFrameLoaderClient::representationExistsForURLScheme(const String& /*URLScheme*/) const
1250 {
1251     notImplemented();
1252     return false;
1253 }
1254
1255 String WebFrameLoaderClient::generatedMIMETypeForURLScheme(const String& /*URLScheme*/) const
1256 {
1257     notImplemented();
1258     return String();
1259 }
1260
1261 void WebFrameLoaderClient::frameLoadCompleted()
1262 {
1263     // Note: Can be called multiple times.
1264     WebPage* webPage = m_frame->page();
1265     if (!webPage)
1266         return;
1267
1268     if (m_frame->isMainFrame() && !m_didCompletePageTransition) {
1269         webPage->didCompletePageTransition();
1270         m_didCompletePageTransition = true;
1271     }
1272 }
1273
1274 void WebFrameLoaderClient::saveViewStateToItem(HistoryItem& historyItem)
1275 {
1276 #if PLATFORM(IOS_FAMILY)
1277     if (m_frame->isMainFrame())
1278         m_frame->page()->savePageState(historyItem);
1279 #else
1280     UNUSED_PARAM(historyItem);
1281 #endif
1282 }
1283
1284 void WebFrameLoaderClient::restoreViewState()
1285 {
1286 #if PLATFORM(IOS_FAMILY)
1287     Frame& frame = *m_frame->coreFrame();
1288     HistoryItem* currentItem = frame.loader().history().currentItem();
1289     if (FrameView* view = frame.view()) {
1290         if (m_frame->isMainFrame())
1291             m_frame->page()->restorePageState(*currentItem);
1292         else if (!view->wasScrolledByUser())
1293             view->setScrollPosition(currentItem->scrollPosition());
1294     }
1295 #else
1296     // Inform the UI process of the scale factor.
1297     double scaleFactor = m_frame->coreFrame()->loader().history().currentItem()->pageScaleFactor();
1298
1299     // A scale factor of 0 means the history item has the default scale factor, thus we do not need to update it.
1300     if (scaleFactor)
1301         m_frame->page()->send(Messages::WebPageProxy::PageScaleFactorDidChange(scaleFactor));
1302
1303     // FIXME: This should not be necessary. WebCore should be correctly invalidating
1304     // the view on restores from the back/forward cache.
1305     if (m_frame->page() && m_frame == m_frame->page()->mainWebFrame())
1306         m_frame->page()->drawingArea()->setNeedsDisplay();
1307 #endif
1308 }
1309
1310 void WebFrameLoaderClient::provisionalLoadStarted()
1311 {
1312     WebPage* webPage = m_frame->page();
1313     if (!webPage)
1314         return;
1315
1316     if (m_frame->isMainFrame()) {
1317         webPage->didStartPageTransition();
1318         m_didCompletePageTransition = false;
1319     }
1320 }
1321
1322 void WebFrameLoaderClient::didFinishLoad()
1323 {
1324     // If we have a load listener, notify it.
1325     if (WebFrame::LoadListener* loadListener = m_frame->loadListener())
1326         loadListener->didFinishLoad(m_frame);
1327 }
1328
1329 void WebFrameLoaderClient::prepareForDataSourceReplacement()
1330 {
1331     notImplemented();
1332 }
1333
1334 Ref<DocumentLoader> WebFrameLoaderClient::createDocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
1335 {
1336     return m_frame->page()->createDocumentLoader(*m_frame->coreFrame(), request, substituteData);
1337 }
1338
1339 void WebFrameLoaderClient::updateCachedDocumentLoader(WebCore::DocumentLoader& loader)
1340 {
1341     m_frame->page()->updateCachedDocumentLoader(static_cast<WebDocumentLoader&>(loader), *m_frame->coreFrame());
1342 }
1343
1344 void WebFrameLoaderClient::setTitle(const StringWithDirection& title, const URL& url)
1345 {
1346     WebPage* webPage = m_frame->page();
1347     if (!webPage)
1348         return;
1349
1350     // FIXME: Use direction of title.
1351     webPage->send(Messages::WebPageProxy::DidUpdateHistoryTitle(title.string, url.string(), m_frame->frameID()));
1352 }
1353
1354 String WebFrameLoaderClient::userAgent(const URL& url)
1355 {
1356     WebPage* webPage = m_frame->page();
1357     if (!webPage)
1358         return String();
1359
1360     return webPage->userAgent(m_frame, url);
1361 }
1362
1363 String WebFrameLoaderClient::overrideContentSecurityPolicy() const
1364 {
1365     WebPage* webPage = m_frame->page();
1366     if (!webPage)
1367         return String();
1368
1369     return webPage->overrideContentSecurityPolicy();
1370 }
1371
1372 void WebFrameLoaderClient::savePlatformDataToCachedFrame(CachedFrame* cachedFrame)
1373 {
1374     WebPage* webPage = m_frame->page();
1375     if (!webPage)
1376         return;
1377
1378     HasInsecureContent hasInsecureContent;
1379     if (webPage->sendSync(Messages::WebPageProxy::HasInsecureContent(), Messages::WebPageProxy::HasInsecureContent::Reply(hasInsecureContent)))
1380         cachedFrame->setHasInsecureContent(hasInsecureContent);
1381 }
1382
1383 void WebFrameLoaderClient::transitionToCommittedFromCachedFrame(CachedFrame*)
1384 {
1385     const ResourceResponse& response = m_frame->coreFrame()->loader().documentLoader()->response();
1386     m_frameHasCustomContentProvider = m_frame->isMainFrame() && m_frame->page()->shouldUseCustomContentProviderForResponse(response);
1387     m_frameCameFromPageCache = true;
1388 }
1389
1390 void WebFrameLoaderClient::transitionToCommittedForNewPage()
1391 {
1392     WebPage* webPage = m_frame->page();
1393
1394     Color backgroundColor = webPage->drawsBackground() ? Color::white : Color::transparent;
1395     bool isMainFrame = m_frame->isMainFrame();
1396     bool isTransparent = !webPage->drawsBackground();
1397     bool shouldUseFixedLayout = isMainFrame && webPage->useFixedLayout();
1398     bool shouldDisableScrolling = isMainFrame && !webPage->mainFrameIsScrollable();
1399     bool shouldHideScrollbars = shouldDisableScrolling;
1400     IntRect fixedVisibleContentRect;
1401
1402 #if USE(COORDINATED_GRAPHICS)
1403     if (m_frame->coreFrame()->view())
1404         fixedVisibleContentRect = m_frame->coreFrame()->view()->fixedVisibleContentRect();
1405     if (shouldUseFixedLayout)
1406         shouldHideScrollbars = true;
1407 #endif
1408
1409     const ResourceResponse& response = m_frame->coreFrame()->loader().documentLoader()->response();
1410     m_frameHasCustomContentProvider = isMainFrame && webPage->shouldUseCustomContentProviderForResponse(response);
1411     m_frameCameFromPageCache = false;
1412
1413     ScrollbarMode defaultScrollbarMode = shouldHideScrollbars ? ScrollbarAlwaysOff : ScrollbarAuto;
1414
1415     ScrollbarMode horizontalScrollbarMode = webPage->alwaysShowsHorizontalScroller() ? ScrollbarAlwaysOn : defaultScrollbarMode;
1416     ScrollbarMode verticalScrollbarMode = webPage->alwaysShowsVerticalScroller() ? ScrollbarAlwaysOn : defaultScrollbarMode;
1417
1418     bool horizontalLock = shouldHideScrollbars || webPage->alwaysShowsHorizontalScroller();
1419     bool verticalLock = shouldHideScrollbars || webPage->alwaysShowsVerticalScroller();
1420
1421     m_frame->coreFrame()->createView(webPage->size(), backgroundColor, isTransparent,
1422         webPage->fixedLayoutSize(), fixedVisibleContentRect, shouldUseFixedLayout,
1423         horizontalScrollbarMode, horizontalLock, verticalScrollbarMode, verticalLock);
1424
1425     if (int viewLayoutWidth = webPage->viewLayoutSize().width()) {
1426         int viewLayoutHeight = std::max(webPage->viewLayoutSize().height(), 1);
1427         int maximumSize = std::numeric_limits<int>::max();
1428         m_frame->coreFrame()->view()->enableAutoSizeMode(true, IntSize(viewLayoutWidth, viewLayoutHeight), IntSize(maximumSize, maximumSize));
1429
1430         if (webPage->autoSizingShouldExpandToViewHeight())
1431             m_frame->coreFrame()->view()->setAutoSizeFixedMinimumHeight(webPage->size().height());
1432     }
1433
1434     if (auto viewportSizeForViewportUnits = webPage->viewportSizeForCSSViewportUnits())
1435         m_frame->coreFrame()->view()->setViewportSizeForCSSViewportUnits(*viewportSizeForViewportUnits);
1436     m_frame->coreFrame()->view()->setProhibitsScrolling(shouldDisableScrolling);
1437     m_frame->coreFrame()->view()->setVisualUpdatesAllowedByClient(!webPage->shouldExtendIncrementalRenderingSuppression());
1438 #if PLATFORM(COCOA)
1439     m_frame->coreFrame()->view()->setViewExposedRect(webPage->drawingArea()->viewExposedRect());
1440 #endif
1441 #if PLATFORM(IOS_FAMILY)
1442     m_frame->coreFrame()->view()->setDelegatesScrolling(true);
1443 #endif
1444
1445     if (webPage->scrollPinningBehavior() != DoNotPin)
1446         m_frame->coreFrame()->view()->setScrollPinningBehavior(webPage->scrollPinningBehavior());
1447
1448 #if USE(COORDINATED_GRAPHICS)
1449     if (shouldUseFixedLayout) {
1450         m_frame->coreFrame()->view()->setDelegatesScrolling(shouldUseFixedLayout);
1451         m_frame->coreFrame()->view()->setPaintsEntireContents(shouldUseFixedLayout);
1452         return;
1453     }
1454 #endif
1455 }
1456
1457 void WebFrameLoaderClient::didSaveToPageCache()
1458 {
1459     WebPage* webPage = m_frame->page();
1460     if (!webPage)
1461         return;
1462
1463     if (m_frame->isMainFrame())
1464         webPage->send(Messages::WebPageProxy::DidSaveToPageCache());
1465 }
1466
1467 void WebFrameLoaderClient::didRestoreFromPageCache()
1468 {
1469     m_frameCameFromPageCache = true;
1470 }
1471
1472 void WebFrameLoaderClient::dispatchDidBecomeFrameset(bool value)
1473 {
1474     WebPage* webPage = m_frame->page();
1475     if (!webPage)
1476         return;
1477
1478     webPage->send(Messages::WebPageProxy::FrameDidBecomeFrameSet(m_frame->frameID(), value));
1479 }
1480
1481 bool WebFrameLoaderClient::canCachePage() const
1482 {
1483     // We cannot cache frames that have custom representations because they are
1484     // rendered in the UIProcess.
1485     return !m_frameHasCustomContentProvider;
1486 }
1487
1488 void WebFrameLoaderClient::convertMainResourceLoadToDownload(DocumentLoader *documentLoader, PAL::SessionID sessionID, const ResourceRequest& request, const ResourceResponse& response)
1489 {
1490     m_frame->convertMainResourceLoadToDownload(documentLoader, sessionID, request, response);
1491 }
1492
1493 RefPtr<Frame> WebFrameLoaderClient::createFrame(const URL& url, const String& name, HTMLFrameOwnerElement& ownerElement,
1494     const String& referrer)
1495 {
1496     auto* webPage = m_frame->page();
1497
1498     auto subframe = WebFrame::createSubframe(webPage, name, &ownerElement);
1499     auto* coreSubframe = subframe->coreFrame();
1500     if (!coreSubframe)
1501         return nullptr;
1502
1503     // The creation of the frame may have run arbitrary JavaScript that removed it from the page already.
1504     if (!coreSubframe->page())
1505         return nullptr;
1506
1507     m_frame->coreFrame()->loader().loadURLIntoChildFrame(url, referrer, coreSubframe);
1508
1509     // The frame's onload handler may have removed it from the document.
1510     if (!subframe->coreFrame())
1511         return nullptr;
1512     ASSERT(subframe->coreFrame() == coreSubframe);
1513     if (!coreSubframe->tree().parent())
1514         return nullptr;
1515
1516     return coreSubframe;
1517 }
1518
1519 RefPtr<Widget> WebFrameLoaderClient::createPlugin(const IntSize&, HTMLPlugInElement& pluginElement, const URL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually)
1520 {
1521     ASSERT(paramNames.size() == paramValues.size());
1522     ASSERT(m_frame->page());
1523
1524     Plugin::Parameters parameters;
1525     parameters.url = url;
1526     parameters.names = paramNames;
1527     parameters.values = paramValues;
1528     parameters.mimeType = mimeType;
1529     parameters.isFullFramePlugin = loadManually;
1530     parameters.shouldUseManualLoader = parameters.isFullFramePlugin && !m_frameCameFromPageCache;
1531 #if PLATFORM(COCOA)
1532     parameters.layerHostingMode = m_frame->page()->layerHostingMode();
1533 #endif
1534
1535 #if ENABLE(NETSCAPE_PLUGIN_API)
1536     auto plugin = m_frame->page()->createPlugin(m_frame, &pluginElement, parameters, parameters.mimeType);
1537     if (!plugin)
1538         return nullptr;
1539
1540     return PluginView::create(pluginElement, plugin.releaseNonNull(), parameters);
1541 #else
1542     UNUSED_PARAM(pluginElement);
1543     return nullptr;
1544 #endif
1545 }
1546
1547 void WebFrameLoaderClient::recreatePlugin(Widget* widget)
1548 {
1549 #if ENABLE(NETSCAPE_PLUGIN_API)
1550     ASSERT(widget);
1551     ASSERT(widget->isPluginViewBase());
1552     ASSERT(m_frame->page());
1553
1554     auto& pluginView = static_cast<PluginView&>(*widget);
1555     String newMIMEType;
1556     auto plugin = m_frame->page()->createPlugin(m_frame, pluginView.pluginElement(), pluginView.initialParameters(), newMIMEType);
1557     pluginView.recreateAndInitialize(plugin.releaseNonNull());
1558 #else
1559     UNUSED_PARAM(widget);
1560 #endif
1561 }
1562
1563 void WebFrameLoaderClient::redirectDataToPlugin(Widget& pluginWidget)
1564 {
1565     m_pluginView = static_cast<PluginView*>(&pluginWidget);
1566 }
1567
1568 #if ENABLE(WEBGL)
1569
1570 WebCore::WebGLLoadPolicy WebFrameLoaderClient::webGLPolicyForURL(const URL& url) const
1571 {
1572     if (auto* webPage = m_frame->page())
1573         return webPage->webGLPolicyForURL(m_frame, url);
1574
1575     return WebGLAllowCreation;
1576 }
1577
1578 WebCore::WebGLLoadPolicy WebFrameLoaderClient::resolveWebGLPolicyForURL(const URL& url) const
1579 {
1580     if (auto* webPage = m_frame->page())
1581         return webPage->resolveWebGLPolicyForURL(m_frame, url);
1582
1583     return WebGLAllowCreation;
1584 }
1585
1586 #endif
1587
1588 RefPtr<Widget> WebFrameLoaderClient::createJavaAppletWidget(const IntSize& pluginSize, HTMLAppletElement& appletElement, const URL&, const Vector<String>& paramNames, const Vector<String>& paramValues)
1589 {
1590 #if ENABLE(NETSCAPE_PLUGIN_API)
1591     auto plugin = createPlugin(pluginSize, appletElement, URL(), paramNames, paramValues, appletElement.serviceType(), false);
1592     if (!plugin) {
1593         if (auto* webPage = m_frame->page()) {
1594             auto frameURLString = m_frame->coreFrame()->loader().documentLoader()->responseURL().string();
1595             auto pageURLString = webPage->corePage()->mainFrame().loader().documentLoader()->responseURL().string();
1596             webPage->send(Messages::WebPageProxy::DidFailToInitializePlugin(appletElement.serviceType(), frameURLString, pageURLString));
1597         }
1598     }
1599     return plugin;
1600 #else
1601     UNUSED_PARAM(pluginSize);
1602     UNUSED_PARAM(appletElement);
1603     UNUSED_PARAM(paramNames);
1604     UNUSED_PARAM(paramValues);
1605     return nullptr;
1606 #endif
1607 }
1608
1609 static bool pluginSupportsExtension(const PluginData& pluginData, const String& extension)
1610 {
1611     ASSERT(extension.convertToASCIILowercase() == extension);
1612     Vector<MimeClassInfo> mimes;
1613     Vector<size_t> mimePluginIndices;
1614     pluginData.getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices);
1615     for (auto& mimeClassInfo : mimes) {
1616         if (mimeClassInfo.extensions.contains(extension))
1617             return true;
1618     }
1619     return false;
1620 }
1621
1622 ObjectContentType WebFrameLoaderClient::objectContentType(const URL& url, const String& mimeTypeIn)
1623 {
1624     // FIXME: This should eventually be merged with WebCore::FrameLoader::defaultObjectContentType.
1625
1626     String mimeType = mimeTypeIn;
1627     if (mimeType.isEmpty()) {
1628         String path = url.path();
1629         auto dotPosition = path.reverseFind('.');
1630         if (dotPosition == notFound)
1631             return ObjectContentType::Frame;
1632         String extension = path.substring(dotPosition + 1).convertToASCIILowercase();
1633
1634         // Try to guess the MIME type from the extension.
1635         mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
1636         if (mimeType.isEmpty()) {
1637             // Check if there's a plug-in around that can handle the extension.
1638             if (WebPage* webPage = m_frame->page()) {
1639                 if (pluginSupportsExtension(webPage->corePage()->pluginData(), extension))
1640                     return ObjectContentType::PlugIn;
1641             }
1642             return ObjectContentType::Frame;
1643         }
1644     }
1645
1646     if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
1647         return ObjectContentType::Image;
1648
1649     if (WebPage* webPage = m_frame->page()) {
1650         auto allowedPluginTypes = webFrame()->coreFrame()->loader().subframeLoader().allowPlugins()
1651             ? PluginData::AllPlugins : PluginData::OnlyApplicationPlugins;
1652         if (webPage->corePage()->pluginData().supportsMimeType(mimeType, allowedPluginTypes))
1653             return ObjectContentType::PlugIn;
1654     }
1655
1656     if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
1657         return ObjectContentType::Frame;
1658
1659 #if PLATFORM(IOS_FAMILY)
1660     // iOS can render PDF in <object>/<embed> via PDFDocumentImage.
1661     if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType))
1662         return ObjectContentType::Image;
1663 #endif
1664
1665     return ObjectContentType::None;
1666 }
1667
1668 String WebFrameLoaderClient::overrideMediaType() const
1669 {
1670     notImplemented();
1671     return String();
1672 }
1673
1674 void WebFrameLoaderClient::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld& world)
1675 {
1676     WebPage* webPage = m_frame->page();
1677     if (!webPage)
1678         return;
1679
1680     webPage->injectedBundleLoaderClient().didClearWindowObjectForFrame(*webPage, *m_frame, world);
1681
1682
1683     WebAutomationSessionProxy* automationSessionProxy = WebProcess::singleton().automationSessionProxy();
1684     if (automationSessionProxy && world.isNormal())
1685         automationSessionProxy->didClearWindowObjectForFrame(*m_frame);
1686
1687 #if HAVE(ACCESSIBILITY) && PLATFORM(GTK)
1688     // Ensure the accessibility hierarchy is updated.
1689     webPage->updateAccessibilityTree();
1690 #endif
1691 }
1692
1693 void WebFrameLoaderClient::dispatchGlobalObjectAvailable(DOMWrapperWorld& world)
1694 {
1695     WebPage* webPage = m_frame->page();
1696     if (!webPage)
1697         return;
1698     
1699     webPage->injectedBundleLoaderClient().globalObjectIsAvailableForFrame(*webPage, *m_frame, world);
1700 }
1701
1702 void WebFrameLoaderClient::willInjectUserScript(DOMWrapperWorld& world)
1703 {
1704     WebPage* webPage = m_frame->page();
1705     if (!webPage)
1706         return;
1707
1708     webPage->injectedBundleLoaderClient().willInjectUserScriptForFrame(*webPage, *m_frame, world);
1709 }
1710
1711 void WebFrameLoaderClient::dispatchWillDisconnectDOMWindowExtensionFromGlobalObject(WebCore::DOMWindowExtension* extension)
1712 {
1713     WebPage* webPage = m_frame->page();
1714     if (!webPage)
1715         return;
1716         
1717     webPage->injectedBundleLoaderClient().willDisconnectDOMWindowExtensionFromGlobalObject(*webPage, extension);
1718 }
1719
1720 void WebFrameLoaderClient::dispatchDidReconnectDOMWindowExtensionToGlobalObject(WebCore::DOMWindowExtension* extension)
1721 {
1722     WebPage* webPage = m_frame->page();
1723     if (!webPage)
1724         return;
1725         
1726     webPage->injectedBundleLoaderClient().didReconnectDOMWindowExtensionToGlobalObject(*webPage, extension);
1727 }
1728
1729 void WebFrameLoaderClient::dispatchWillDestroyGlobalObjectForDOMWindowExtension(WebCore::DOMWindowExtension* extension)
1730 {
1731     WebPage* webPage = m_frame->page();
1732     if (!webPage)
1733         return;
1734         
1735     webPage->injectedBundleLoaderClient().willDestroyGlobalObjectForDOMWindowExtension(*webPage, extension);
1736 }
1737
1738 #if PLATFORM(COCOA)
1739     
1740 RemoteAXObjectRef WebFrameLoaderClient::accessibilityRemoteObject() 
1741 {
1742     WebPage* webPage = m_frame->page();
1743     if (!webPage)
1744         return 0;
1745     
1746     return webPage->accessibilityRemoteObject();
1747 }
1748     
1749 void WebFrameLoaderClient::willCacheResponse(DocumentLoader*, unsigned long identifier, NSCachedURLResponse* response, CompletionHandler<void(NSCachedURLResponse *)>&& completionHandler) const
1750 {
1751     WebPage* webPage = m_frame->page();
1752     if (!webPage)
1753         return completionHandler(response);
1754
1755     return completionHandler(webPage->injectedBundleResourceLoadClient().shouldCacheResponse(*webPage, *m_frame, identifier) ? response : nil);
1756 }
1757
1758 NSDictionary *WebFrameLoaderClient::dataDetectionContext()
1759 {
1760     WebPage* webPage = m_frame->page();
1761     if (!webPage)
1762         return nil;
1763
1764     return webPage->dataDetectionContext();
1765 }
1766
1767 #endif // PLATFORM(COCOA)
1768
1769 bool WebFrameLoaderClient::shouldAlwaysUsePluginDocument(const String& /*mimeType*/) const
1770 {
1771     notImplemented();
1772     return false;
1773 }
1774
1775 void WebFrameLoaderClient::didChangeScrollOffset()
1776 {
1777     WebPage* webPage = m_frame->page();
1778     if (!webPage)
1779         return;
1780
1781     webPage->didChangeScrollOffsetForFrame(m_frame->coreFrame());
1782 }
1783
1784 bool WebFrameLoaderClient::allowScript(bool enabledPerSettings)
1785 {
1786     if (!enabledPerSettings)
1787         return false;
1788
1789     auto* pluginView = WebPage::pluginViewForFrame(m_frame->coreFrame());
1790     return !pluginView || !pluginView->shouldAllowScripting();
1791 }
1792
1793 bool WebFrameLoaderClient::shouldForceUniversalAccessFromLocalURL(const WebCore::URL& url)
1794 {
1795     WebPage* webPage = m_frame->page();
1796     if (!webPage)
1797         return false;
1798
1799     return webPage->injectedBundleLoaderClient().shouldForceUniversalAccessFromLocalURL(*webPage, url);
1800 }
1801
1802 Ref<FrameNetworkingContext> WebFrameLoaderClient::createNetworkingContext()
1803 {
1804     ASSERT(!hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
1805     return WebFrameNetworkingContext::create(m_frame);
1806 }
1807
1808 #if ENABLE(CONTENT_FILTERING)
1809
1810 void WebFrameLoaderClient::contentFilterDidBlockLoad(WebCore::ContentFilterUnblockHandler unblockHandler)
1811 {
1812     if (!unblockHandler.needsUIProcess()) {
1813         m_frame->coreFrame()->loader().policyChecker().setContentFilterUnblockHandler(WTFMove(unblockHandler));
1814         return;
1815     }
1816
1817     if (WebPage* webPage { m_frame->page() })
1818         webPage->send(Messages::WebPageProxy::ContentFilterDidBlockLoadForFrame(unblockHandler, m_frame->frameID()));
1819 }
1820
1821 #endif
1822
1823 void WebFrameLoaderClient::prefetchDNS(const String& hostname)
1824 {
1825     WebProcess::singleton().prefetchDNS(hostname);
1826 }
1827
1828 void WebFrameLoaderClient::didRestoreScrollPosition()
1829 {
1830     WebPage* webPage = m_frame->page();
1831     if (!webPage)
1832         return;
1833
1834     webPage->didRestoreScrollPosition();
1835 }
1836
1837 void WebFrameLoaderClient::getLoadDecisionForIcons(const Vector<std::pair<WebCore::LinkIcon&, uint64_t>>& icons)
1838 {
1839     auto* webPage = m_frame->page();
1840     if (!webPage)
1841         return;
1842
1843     for (auto& icon : icons)
1844         webPage->send(Messages::WebPageProxy::GetLoadDecisionForIcon(icon.first, CallbackID::fromInteger(icon.second)));
1845 }
1846
1847 void WebFrameLoaderClient::finishedLoadingIcon(uint64_t callbackIdentifier, SharedBuffer* data)
1848 {
1849     auto callbackID = CallbackID::fromInteger(callbackIdentifier);
1850     if (WebPage* webPage { m_frame->page() }) {
1851         if (data)
1852             webPage->send(Messages::WebPageProxy::FinishedLoadingIcon(callbackID, { reinterpret_cast<const uint8_t*>(data->data()), data->size() }));
1853         else
1854             webPage->send(Messages::WebPageProxy::FinishedLoadingIcon(callbackID, { nullptr, 0 }));
1855     }
1856 }
1857
1858 void WebFrameLoaderClient::didCreateWindow(DOMWindow& window)
1859 {
1860     auto* webPage = m_frame->page();
1861     if (!webPage)
1862         return;
1863
1864     webPage->send(Messages::WebPageProxy::DidCreateWindow(m_frame->frameID(), window.identifier()));
1865 }
1866
1867 #if ENABLE(APPLICATION_MANIFEST)
1868 void WebFrameLoaderClient::finishedLoadingApplicationManifest(uint64_t callbackIdentifier, const std::optional<WebCore::ApplicationManifest>& manifest)
1869 {
1870     WebPage* webPage = m_frame->page();
1871     if (!webPage)
1872         return;
1873
1874     webPage->didFinishLoadingApplicationManifest(callbackIdentifier, manifest);
1875 }
1876 #endif // ENABLE(APPLICATION_MANIFEST)
1877
1878 } // namespace WebKit