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