-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
WKWebView.mm
4086 lines (3426 loc) · 142 KB
/
WKWebView.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014-2023 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "WKWebViewInternal.h"
#import "APIDataTask.h"
#import "APIFormClient.h"
#import "APIFrameTreeNode.h"
#import "APIPageConfiguration.h"
#import "APISecurityOrigin.h"
#import "APISerializedScriptValue.h"
#import "CocoaImage.h"
#import "CompletionHandlerCallChecker.h"
#import "ContentAsStringIncludesChildFrames.h"
#import "DiagnosticLoggingClient.h"
#import "FindClient.h"
#import "FullscreenClient.h"
#import "GlobalFindInPageState.h"
#import "IconLoadingDelegate.h"
#import "ImageAnalysisUtilities.h"
#import "LegacySessionStateCoding.h"
#import "Logging.h"
#import "MediaPlaybackState.h"
#import "MediaUtilities.h"
#import "NavigationState.h"
#import "ObjCObjectGraph.h"
#import "PageClient.h"
#import "ProvisionalPageProxy.h"
#import "QuickLookThumbnailLoader.h"
#import "RemoteLayerTreeScrollingPerformanceData.h"
#import "RemoteObjectRegistry.h"
#import "RemoteObjectRegistryMessages.h"
#import "ResourceLoadDelegate.h"
#import "SafeBrowsingWarning.h"
#import "SessionStateCoding.h"
#import "UIDelegate.h"
#import "VideoFullscreenManagerProxy.h"
#import "ViewGestureController.h"
#import "WKBackForwardListInternal.h"
#import "WKBackForwardListItemInternal.h"
#import "WKBrowsingContextHandleInternal.h"
#import "WKContentWorldInternal.h"
#import "WKDownloadInternal.h"
#import "WKErrorInternal.h"
#import "WKFindConfiguration.h"
#import "WKFindResultInternal.h"
#import "WKFrameInfoPrivate.h"
#import "WKHistoryDelegatePrivate.h"
#import "WKLayoutMode.h"
#import "WKNSData.h"
#import "WKNSURLExtras.h"
#import "WKNavigationDelegate.h"
#import "WKNavigationInternal.h"
#import "WKPDFConfiguration.h"
#import "WKPreferencesInternal.h"
#import "WKProcessPoolInternal.h"
#import "WKSafeBrowsingWarning.h"
#import "WKSecurityOriginInternal.h"
#import "WKSharedAPICast.h"
#import "WKSnapshotConfigurationPrivate.h"
#import "WKUIDelegate.h"
#import "WKUIDelegatePrivate.h"
#import "WKUserContentControllerInternal.h"
#import "WKWebViewConfigurationInternal.h"
#import "WKWebViewContentProvider.h"
#import "WKWebViewMac.h"
#import "WKWebpagePreferencesInternal.h"
#import "WKWebsiteDataStoreInternal.h"
#import "WebBackForwardList.h"
#import "WebFrameProxy.h"
#import "WebFullScreenManagerProxy.h"
#import "WebPageGroup.h"
#import "WebPageInspectorController.h"
#import "WebPageProxy.h"
#import "WebPreferences.h"
#import "WebProcessPool.h"
#import "WebProcessProxy.h"
#import "WebURLSchemeHandlerCocoa.h"
#import "WebViewImpl.h"
#import "_WKActivatedElementInfoInternal.h"
#import "_WKAppHighlightDelegate.h"
#import "_WKAppHighlightInternal.h"
#import "_WKDataTaskInternal.h"
#import "_WKDiagnosticLoggingDelegate.h"
#import "_WKFindDelegate.h"
#import "_WKFrameHandleInternal.h"
#import "_WKFrameTreeNodeInternal.h"
#import "_WKFullscreenDelegate.h"
#import "_WKHitTestResultInternal.h"
#import "_WKInputDelegate.h"
#import "_WKInspectorInternal.h"
#import "_WKRemoteObjectRegistryInternal.h"
#import "_WKSessionStateInternal.h"
#import "_WKTextInputContextInternal.h"
#import "_WKTextManipulationConfiguration.h"
#import "_WKTextManipulationDelegate.h"
#import "_WKTextManipulationExclusionRule.h"
#import "_WKTextManipulationItem.h"
#import "_WKTextManipulationToken.h"
#import "_WKVisitedLinkStoreInternal.h"
#import <WebCore/AppHighlight.h>
#import <WebCore/AttributedString.h>
#import <WebCore/ColorCocoa.h>
#import <WebCore/ColorSerialization.h>
#import <WebCore/ContentExtensionsBackend.h>
#import <WebCore/ElementContext.h>
#import <WebCore/JSDOMBinding.h>
#import <WebCore/JSDOMExceptionHandling.h>
#import <WebCore/LegacySchemeRegistry.h>
#import <WebCore/MIMETypeRegistry.h>
#import <WebCore/Pagination.h>
#import <WebCore/Permissions.h>
#import <WebCore/PlatformScreen.h>
#import <WebCore/RunJavaScriptParameters.h>
#import <WebCore/RuntimeApplicationChecks.h>
#import <WebCore/Settings.h>
#import <WebCore/SharedBuffer.h>
#import <WebCore/StringUtilities.h>
#import <WebCore/TextManipulationController.h>
#import <WebCore/TextManipulationItem.h>
#import <WebCore/ViewportArguments.h>
#import <WebCore/WebCoreObjCExtras.h>
#import <WebCore/WebViewVisualIdentificationOverlay.h>
#import <WebCore/WritingMode.h>
#import <wtf/BlockPtr.h>
#import <wtf/CallbackAggregator.h>
#import <wtf/HashMap.h>
#import <wtf/MathExtras.h>
#import <wtf/NeverDestroyed.h>
#import <wtf/RetainPtr.h>
#import <wtf/SystemTracing.h>
#import <wtf/UUID.h>
#import <wtf/cocoa/RuntimeApplicationChecksCocoa.h>
#import <wtf/cocoa/VectorCocoa.h>
#import <wtf/spi/darwin/dyldSPI.h>
#import <wtf/text/StringToIntegerConversion.h>
#import <wtf/text/TextStream.h>
#if ENABLE(APPLICATION_MANIFEST)
#import "_WKApplicationManifestInternal.h"
#endif
#if ENABLE(DATA_DETECTION)
#import "WKDataDetectorTypesInternal.h"
#endif
#if ENABLE(WK_WEB_EXTENSIONS)
#import "_WKWebExtensionControllerInternal.h"
#endif
#if PLATFORM(IOS_FAMILY)
#import "RemoteLayerTreeDrawingAreaProxy.h"
#import "RemoteScrollingCoordinatorProxy.h"
#import "UIKitSPI.h"
#import "WKContentViewInteraction.h"
#import "WKScrollView.h"
#import "WKWebViewContentProviderRegistry.h"
#import "WKWebViewIOS.h"
#import "WKWebViewPrivateForTestingIOS.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <UIKit/UIApplication.h>
#import <pal/spi/cf/CFNotificationCenterSPI.h>
#import <pal/spi/cocoa/QuartzCoreSPI.h>
#import <pal/spi/ios/GraphicsServicesSPI.h>
#import <wtf/cocoa/Entitlements.h>
#define WKWEBVIEW_RELEASE_LOG(...) RELEASE_LOG(ViewState, __VA_ARGS__)
#endif // PLATFORM(IOS_FAMILY)
#if PLATFORM(MAC)
#import "AppKitSPI.h"
#import "WKTextFinderClient.h"
#import "WKViewInternal.h"
#import <WebCore/ColorMac.h>
#endif
#if PLATFORM(WATCHOS)
static const BOOL defaultAllowsViewportShrinkToFit = YES;
static const BOOL defaultFastClickingEnabled = YES;
#elif PLATFORM(IOS_FAMILY)
static const BOOL defaultAllowsViewportShrinkToFit = NO;
static const BOOL defaultFastClickingEnabled = NO;
#endif
#define THROW_IF_SUSPENDED if (UNLIKELY(_page && _page->isSuspended())) \
[NSException raise:NSInternalInconsistencyException format:@"The WKWebView is suspended"]
RetainPtr<NSError> nsErrorFromExceptionDetails(const WebCore::ExceptionDetails& details)
{
auto userInfo = adoptNS([[NSMutableDictionary alloc] init]);
WKErrorCode errorCode;
switch (details.type) {
case WebCore::ExceptionDetails::Type::InvalidTargetFrame:
errorCode = WKErrorJavaScriptInvalidFrameTarget;
break;
case WebCore::ExceptionDetails::Type::Script:
errorCode = WKErrorJavaScriptExceptionOccurred;
break;
case WebCore::ExceptionDetails::Type::AppBoundDomain:
errorCode = WKErrorJavaScriptAppBoundDomain;
break;
}
[userInfo setObject:localizedDescriptionForErrorCode(errorCode) forKey:NSLocalizedDescriptionKey];
[userInfo setObject:details.message forKey:_WKJavaScriptExceptionMessageErrorKey];
[userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
[userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
if (!details.sourceURL.isEmpty())
[userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
return adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:errorCode userInfo:userInfo.get()]);
}
@implementation WKWebView
- (instancetype)initWithFrame:(CGRect)frame
{
return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
}
- (BOOL)_isValid
{
return _page && _page->hasRunningProcess();
}
#if PLATFORM(IOS_FAMILY)
static bool shouldAllowPictureInPictureMediaPlayback()
{
static bool shouldAllowPictureInPictureMediaPlayback = linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::PictureInPictureMediaPlayback);
return shouldAllowPictureInPictureMediaPlayback;
}
static bool shouldAllowSettingAnyXHRHeaderFromFileURLs()
{
static bool shouldAllowSettingAnyXHRHeaderFromFileURLs = (WebCore::IOSApplication::isCardiogram() || WebCore::IOSApplication::isNike()) && !linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::DisallowsSettingAnyXHRHeaderFromFileURLs);
return shouldAllowSettingAnyXHRHeaderFromFileURLs;
}
#endif // PLATFORM(IOS_FAMILY)
static bool shouldRequireUserGestureToLoadVideo()
{
#if PLATFORM(IOS_FAMILY)
static bool shouldRequireUserGestureToLoadVideo = linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::RequiresUserGestureToLoadVideo);
return shouldRequireUserGestureToLoadVideo;
#else
return false;
#endif
}
static bool shouldRestrictBaseURLSchemes()
{
static bool shouldRestrictBaseURLSchemes = linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::RestrictsBaseURLSchemes);
return shouldRestrictBaseURLSchemes;
}
#if PLATFORM(MAC)
static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
{
switch (policy) {
case WKUserInterfaceDirectionPolicyContent:
return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
case WKUserInterfaceDirectionPolicySystem:
return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
}
return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
}
static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
{
switch (direction) {
case NSUserInterfaceLayoutDirectionLeftToRight:
return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
case NSUserInterfaceLayoutDirectionRightToLeft:
return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
}
return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
}
#endif // PLATFORM(MAC)
static void validate(WKWebViewConfiguration *configuration)
{
if (!configuration.processPool)
[NSException raise:NSInvalidArgumentException format:@"configuration.processPool is nil"];
if (!configuration.preferences)
[NSException raise:NSInvalidArgumentException format:@"configuration.preferences is nil"];
if (!configuration.userContentController)
[NSException raise:NSInvalidArgumentException format:@"configuration.userContentController is nil"];
if (!configuration.websiteDataStore)
[NSException raise:NSInvalidArgumentException format:@"configuration.websiteDataStore is nil"];
if (!configuration._visitedLinkStore)
[NSException raise:NSInvalidArgumentException format:@"configuration._visitedLinkStore is nil"];
#if PLATFORM(IOS_FAMILY)
if (!configuration._contentProviderRegistry)
[NSException raise:NSInvalidArgumentException format:@"configuration._contentProviderRegistry is nil"];
#endif
}
#if PLATFORM(IOS_FAMILY)
static void hardwareKeyboardAvailabilityChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
{
ASSERT(observer);
RetainPtr webView { (__bridge WKWebView *)observer };
if (!webView)
return;
[webView->_contentView _hardwareKeyboardAvailabilityChanged];
webView->_page->hardwareKeyboardAvailabilityChanged(GSEventIsHardwareKeyboardAttached());
}
#endif
- (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
{
if (!configuration)
[NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
if (!configuration.websiteDataStore)
[NSException raise:NSInvalidArgumentException format:@"Configuration websiteDataStore cannot be nil"];
_configuration = adoptNS([configuration copy]);
if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
WKProcessPool *processPool = [_configuration processPool];
WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
if (processPool && processPool != relatedWebViewProcessPool)
[NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
if ([relatedWebView->_configuration websiteDataStore] != [_configuration websiteDataStore] && linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::ExceptionsForRelatedWebViewsUsingDifferentDataStores))
[NSException raise:NSInvalidArgumentException format:@"Related web view %@ has data store %@ but configuration specifies a different data store %@", relatedWebView, [relatedWebView->_configuration websiteDataStore], [_configuration websiteDataStore]];
[_configuration setProcessPool:relatedWebViewProcessPool];
}
validate(_configuration.get());
WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
auto pageConfiguration = [configuration copyPageConfiguration];
pageConfiguration->setProcessPool(&processPool);
[self _setupPageConfiguration:pageConfiguration];
_usePlatformFindUI = YES;
#if PLATFORM(IOS_FAMILY)
_obscuredInsetEdgesAffectedBySafeArea = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
_allowsViewportShrinkToFit = defaultAllowsViewportShrinkToFit;
_allowsLinkPreview = linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::LinkPreviewEnabledByDefault);
_findInteractionEnabled = NO;
_needsToPresentLockdownModeMessage = YES;
auto fastClickingEnabled = []() {
if (NSNumber *enabledValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitFastClickingDisabled"])
return enabledValue.boolValue;
return defaultFastClickingEnabled;
};
_fastClickingIsDisabled = fastClickingEnabled();
_dragInteractionPolicy = _WKDragInteractionPolicyDefault;
_contentView = adoptNS([[WKContentView alloc] initWithFrame:self.bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
_page = [_contentView page];
[[_configuration _contentProviderRegistry] addPage:*_page];
[self _setupScrollAndContentViews];
if (!self.opaque || !pageConfiguration->drawsBackground())
[self _setOpaqueInternal:NO];
else
[self _updateScrollViewBackground];
[self _frameOrBoundsMayHaveChanged];
[self _registerForNotifications];
_page->contentSizeCategoryDidChange([self _contentSizeCategory]);
auto notificationName = adoptNS([[NSString alloc] initWithCString:kGSEventHardwareKeyboardAvailabilityChangedNotification encoding:NSUTF8StringEncoding]);
auto notificationBehavior = static_cast<CFNotificationSuspensionBehavior>(CFNotificationSuspensionBehaviorCoalesce | _CFNotificationObserverIsObjC);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), hardwareKeyboardAvailabilityChangedCallback, (__bridge CFStringRef)notificationName.get(), nullptr, notificationBehavior);
#endif // PLATFORM(IOS_FAMILY)
#if ENABLE(META_VIEWPORT)
_page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
#endif
#if PLATFORM(MAC)
_impl = makeUnique<WebKit::WebViewImpl>(self, self, processPool, pageConfiguration.copyRef());
_page = &_impl->page();
_impl->setAutomaticallyAdjustsContentInsets(true);
#endif
if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
_page->setApplicationNameForUserAgent(applicationNameForUserAgent);
_page->setApplicationNameForDesktopUserAgent(configuration._applicationNameForDesktopUserAgent);
_navigationState = makeUnique<WebKit::NavigationState>(self);
_page->setNavigationClient(_navigationState->createNavigationClient());
_uiDelegate = makeUnique<WebKit::UIDelegate>(self);
_page->setFindClient(makeUnique<WebKit::FindClient>(self));
_page->setDiagnosticLoggingClient(makeUnique<WebKit::DiagnosticLoggingClient>(self));
_iconLoadingDelegate = makeUnique<WebKit::IconLoadingDelegate>(self);
_resourceLoadDelegate = makeUnique<WebKit::ResourceLoadDelegate>(self);
for (auto& pair : pageConfiguration->urlSchemeHandlers())
_page->setURLSchemeHandlerForScheme(pair.value.get(), pair.key);
_page->setCocoaView(self);
[WebViewVisualIdentificationOverlay installForWebViewIfNeeded:self kind:@"WKWebView" deprecated:NO];
#if PLATFORM(IOS_FAMILY)
auto timeNow = MonotonicTime::now();
_timeOfRequestForVisibleContentRectUpdate = timeNow;
_timeOfLastVisibleContentRectUpdate = timeNow;
_timeOfFirstVisibleContentRectUpdateWithPendingCommit = timeNow;
#endif
}
- (void)_setupPageConfiguration:(Ref<API::PageConfiguration>&)pageConfiguration
{
pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
if (WKWebView *relatedWebView = [_configuration _relatedWebView])
pageConfiguration->setRelatedPage(relatedWebView->_page.get());
if (WKWebView *webViewToCloneSessionStorageFrom = [_configuration _webViewToCloneSessionStorageFrom])
pageConfiguration->setPageToCloneSessionStorageFrom(webViewToCloneSessionStorageFrom->_page.get());
pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
pageConfiguration->setDefaultWebsitePolicies([_configuration defaultWebpagePreferences]->_websitePolicies.get());
#if ENABLE(WK_WEB_EXTENSIONS)
if (auto *controller = _configuration.get()._strongWebExtensionController)
pageConfiguration->setWebExtensionController(&controller._webExtensionController);
if (auto *controller = _configuration.get()._weakWebExtensionController)
pageConfiguration->setWeakWebExtensionController(&controller._webExtensionController);
#endif
#if PLATFORM(MAC)
if (auto pageGroup = WebKit::toImpl([_configuration _pageGroup]))
pageConfiguration->setPageGroup(pageGroup);
else
#endif
{
NSString *groupIdentifier = [_configuration _groupIdentifier];
if (groupIdentifier.length)
pageConfiguration->setPageGroup(WebKit::WebPageGroup::create(groupIdentifier).ptr());
}
pageConfiguration->setAdditionalSupportedImageTypes(makeVector<String>([_configuration _additionalSupportedImageTypes]));
pageConfiguration->preferences()->setSuppressesIncrementalRendering(!![_configuration suppressesIncrementalRendering]);
pageConfiguration->preferences()->setShouldRespectImageOrientation(!![_configuration _respectsImageOrientation]);
#if !PLATFORM(MAC)
// FIXME: rdar://99156546. Remove this and WKWebViewConfiguration._printsBackgrounds once all iOS clients adopt the new API.
if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::DefaultsToExcludingBackgroundsWhenPrinting))
pageConfiguration->preferences()->setShouldPrintBackgrounds(!![_configuration _printsBackgrounds]);
#endif
pageConfiguration->preferences()->setIncrementalRenderingSuppressionTimeout([_configuration _incrementalRenderingSuppressionTimeout]);
pageConfiguration->preferences()->setJavaScriptMarkupEnabled(!![_configuration _allowsJavaScriptMarkup]);
pageConfiguration->preferences()->setShouldConvertPositionStyleOnCopy(!![_configuration _convertsPositionStyleOnCopy]);
pageConfiguration->preferences()->setHTTPEquivEnabled(!![_configuration _allowsMetaRefresh]);
pageConfiguration->preferences()->setAllowUniversalAccessFromFileURLs(!![_configuration _allowUniversalAccessFromFileURLs]);
pageConfiguration->preferences()->setAllowTopNavigationToDataURLs(!![_configuration _allowTopNavigationToDataURLs]);
pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
pageConfiguration->setDrawsBackground([_configuration _drawsBackground]);
pageConfiguration->setControlledByAutomation([_configuration _isControlledByAutomation]);
pageConfiguration->preferences()->setIncompleteImageBorderEnabled(!![_configuration _incompleteImageBorderEnabled]);
pageConfiguration->preferences()->setShouldDeferAsynchronousScriptsUntilAfterDocumentLoadOrFirstPaint(!![_configuration _shouldDeferAsynchronousScriptsUntilAfterDocumentLoad]);
pageConfiguration->preferences()->setShouldRestrictBaseURLSchemes(shouldRestrictBaseURLSchemes());
#if PLATFORM(MAC)
pageConfiguration->preferences()->setShowsURLsInToolTipsEnabled(!![_configuration _showsURLsInToolTips]);
pageConfiguration->preferences()->setServiceControlsEnabled(!![_configuration _serviceControlsEnabled]);
pageConfiguration->preferences()->setImageControlsEnabled(!![_configuration _imageControlsEnabled]);
pageConfiguration->preferences()->setContextMenuQRCodeDetectionEnabled(!![_configuration _contextMenuQRCodeDetectionEnabled]);
pageConfiguration->preferences()->setUserInterfaceDirectionPolicy(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy]));
// We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
// Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
// [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
pageConfiguration->preferences()->setSystemLayoutDirection(convertSystemLayoutDirection(self.userInterfaceLayoutDirection));
#endif
#if PLATFORM(IOS_FAMILY)
pageConfiguration->preferences()->setAllowsInlineMediaPlayback(!![_configuration allowsInlineMediaPlayback]);
pageConfiguration->preferences()->setAllowsInlineMediaPlaybackAfterFullscreen(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]);
pageConfiguration->preferences()->setInlineMediaPlaybackRequiresPlaysInlineAttribute(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]);
pageConfiguration->preferences()->setAllowsPictureInPictureMediaPlayback(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
pageConfiguration->preferences()->setUserInterfaceDirectionPolicy(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content));
pageConfiguration->preferences()->setSystemLayoutDirection(static_cast<uint32_t>(WebCore::TextDirection::LTR));
pageConfiguration->preferences()->setAllowSettingAnyXHRHeaderFromFileURLs(shouldAllowSettingAnyXHRHeaderFromFileURLs());
pageConfiguration->preferences()->setShouldDecidePolicyBeforeLoadingQuickLookPreview(!![_configuration _shouldDecidePolicyBeforeLoadingQuickLookPreview]);
#if ENABLE(DEVICE_ORIENTATION)
pageConfiguration->preferences()->setDeviceOrientationPermissionAPIEnabled(linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::SupportsDeviceOrientationAndMotionPermissionAPI));
#endif
#if USE(SYSTEM_PREVIEW)
pageConfiguration->preferences()->setSystemPreviewEnabled(!![_configuration _systemPreviewEnabled]);
#endif
#endif // PLATFORM(IOS_FAMILY)
WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
pageConfiguration->preferences()->setRequiresUserGestureForVideoPlayback((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo);
pageConfiguration->preferences()->setRequiresUserGestureForAudioPlayback(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio));
pageConfiguration->preferences()->setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
pageConfiguration->preferences()->setMainContentUserGestureOverrideEnabled(!![_configuration _mainContentUserGestureOverrideEnabled]);
pageConfiguration->preferences()->setInvisibleAutoplayNotPermitted(!![_configuration _invisibleAutoplayNotPermitted]);
pageConfiguration->preferences()->setMediaDataLoadsAutomatically(!![_configuration _mediaDataLoadsAutomatically]);
pageConfiguration->preferences()->setAttachmentElementEnabled(!![_configuration _attachmentElementEnabled]);
pageConfiguration->preferences()->setAttachmentWideLayoutEnabled(!![_configuration _attachmentWideLayoutEnabled]);
#if ENABLE(DATA_DETECTION) && PLATFORM(IOS_FAMILY)
pageConfiguration->preferences()->setDataDetectorTypes(fromWKDataDetectorTypes([_configuration dataDetectorTypes]).toRaw());
#endif
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
pageConfiguration->preferences()->setAllowsAirPlayForMediaPlayback(!![_configuration allowsAirPlayForMediaPlayback]);
#endif
#if ENABLE(APPLE_PAY)
pageConfiguration->preferences()->setApplePayEnabled(!![_configuration _applePayEnabled]);
#endif
pageConfiguration->preferences()->setNeedsStorageAccessFromFileURLsQuirk(!![_configuration _needsStorageAccessFromFileURLsQuirk]);
pageConfiguration->preferences()->setMediaContentTypesRequiringHardwareSupport(String([_configuration _mediaContentTypesRequiringHardwareSupport]));
pageConfiguration->preferences()->setAllowMediaContentTypesRequiringHardwareSupportAsFallback(!![_configuration _allowMediaContentTypesRequiringHardwareSupportAsFallback]);
if (!pageConfiguration->preferences()->mediaDevicesEnabled())
pageConfiguration->preferences()->setMediaDevicesEnabled(!![_configuration _mediaCaptureEnabled]);
pageConfiguration->preferences()->setColorFilterEnabled(!![_configuration _colorFilterEnabled]);
pageConfiguration->preferences()->setUndoManagerAPIEnabled(!![_configuration _undoManagerAPIEnabled]);
#if ENABLE(APP_HIGHLIGHTS)
pageConfiguration->preferences()->setAppHighlightsEnabled(!![_configuration _appHighlightsEnabled]);
#endif
#if ENABLE(LEGACY_ENCRYPTED_MEDIA)
pageConfiguration->preferences()->setLegacyEncryptedMediaAPIEnabled(!![_configuration _legacyEncryptedMediaAPIEnabled]);
#endif
#if PLATFORM(IOS_FAMILY) && ENABLE(SERVICE_WORKER)
bool hasServiceWorkerEntitlement = (WTF::processHasEntitlement("com.apple.developer.WebKit.ServiceWorkers"_s) || WTF::processHasEntitlement("com.apple.developer.web-browser"_s)) && ![_configuration preferences]._serviceWorkerEntitlementDisabledForTesting;
if (!hasServiceWorkerEntitlement && ![_configuration limitsNavigationsToAppBoundDomains])
pageConfiguration->preferences()->setServiceWorkersEnabled(false);
pageConfiguration->preferences()->setServiceWorkerEntitlementDisabledForTesting(!![_configuration preferences]._serviceWorkerEntitlementDisabledForTesting);
#endif
pageConfiguration->preferences()->setSampledPageTopColorMaxDifference([_configuration _sampledPageTopColorMaxDifference]);
pageConfiguration->preferences()->setSampledPageTopColorMinHeight([_configuration _sampledPageTopColorMinHeight]);
if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::SiteSpecificQuirksAreEnabledByDefault))
pageConfiguration->preferences()->setNeedsSiteSpecificQuirks(false);
#if PLATFORM(IOS_FAMILY)
pageConfiguration->preferences()->setAlternateFormControlDesignEnabled(WebKit::defaultAlternateFormControlDesignEnabled());
pageConfiguration->preferences()->setVideoFullscreenRequiresElementFullscreen(WebKit::defaultVideoFullscreenRequiresElementFullscreen());
#endif
pageConfiguration->preferences()->setMarkedTextInputEnabled(!![_configuration _markedTextInputEnabled]);
}
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
{
if (!(self = [super initWithFrame:frame]))
return nil;
[self _initializeWithConfiguration:configuration];
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
if (!(self = [super initWithCoder:coder]))
return nil;
WKWebViewConfiguration *configuration = [coder decodeObjectOfClass:[WKWebViewConfiguration class] forKey:@"configuration"];
[self _initializeWithConfiguration:configuration];
self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
self.customUserAgent = [coder decodeObjectOfClass:[NSString class] forKey:@"customUserAgent"];
self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
#if PLATFORM(MAC)
self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
self.magnification = [coder decodeDoubleForKey:@"magnification"];
#endif
#if PLATFORM(IOS) || PLATFORM(MACCATALYST)
self.findInteractionEnabled = [coder decodeBoolForKey:@"findInteractionEnabled"];
#endif
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[super encodeWithCoder:coder];
[coder encodeObject:_configuration.get() forKey:@"configuration"];
[coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
[coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
[coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
#if PLATFORM(MAC)
[coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
[coder encodeDouble:self.magnification forKey:@"magnification"];
#endif
#if PLATFORM(IOS) || PLATFORM(MACCATALYST)
[coder encodeBool:self.isFindInteractionEnabled forKey:@"findInteractionEnabled"];
#endif
}
- (void)dealloc
{
if (WebCoreObjCScheduleDeallocateOnMainRunLoop(WKWebView.class, self))
return;
#if PLATFORM(MAC)
[_textFinderClient willDestroyView:self];
#endif
#if PLATFORM(IOS_FAMILY)
[_contentView _webViewDestroyed];
if (_page && _remoteObjectRegistry)
_page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->identifier());
#endif
if (_page)
_page->close();
#if PLATFORM(IOS_FAMILY)
[_remoteObjectRegistry _invalidate];
[[_configuration _contentProviderRegistry] removePage:*_page];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_scrollView setInternalDelegate:nil];
auto notificationName = adoptNS([[NSString alloc] initWithCString:kGSEventHardwareKeyboardAvailabilityChangedNotification encoding:NSUTF8StringEncoding]);
CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), (__bridge CFStringRef)notificationName.get(), nullptr);
#endif
#if HAVE(UIKIT_RESIZABLE_WINDOWS)
[self _invalidateResizeAssertions];
#endif
[super dealloc];
}
- (id)valueForUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"serverTrust"])
return (__bridge id)[self serverTrust];
return [super valueForUndefinedKey:key];
}
#pragma mark - macOS/iOS API
- (WKWebViewConfiguration *)configuration
{
return adoptNS([_configuration copy]).autorelease();
}
- (WKBackForwardList *)backForwardList
{
return wrapper(_page->backForwardList());
}
- (id <WKNavigationDelegate>)navigationDelegate
{
return _navigationState->navigationDelegate().autorelease();
}
- (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
{
_page->setNavigationClient(_navigationState->createNavigationClient());
_navigationState->setNavigationDelegate(navigationDelegate);
}
- (id <WKUIDelegate>)UIDelegate
{
return _uiDelegate->delegate().autorelease();
}
- (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
{
_uiDelegate->setDelegate(UIDelegate);
#if ENABLE(CONTEXT_MENUS)
_page->setContextMenuClient(_uiDelegate->createContextMenuClient());
#endif
_page->setUIClient(_uiDelegate->createUIClient());
}
- (id <_WKIconLoadingDelegate>)_iconLoadingDelegate
{
return _iconLoadingDelegate->delegate().autorelease();
}
- (void)_setIconLoadingDelegate:(id<_WKIconLoadingDelegate>)iconLoadingDelegate
{
_page->setIconLoadingClient(_iconLoadingDelegate->createIconLoadingClient());
_iconLoadingDelegate->setDelegate(iconLoadingDelegate);
}
- (id <_WKResourceLoadDelegate>)_resourceLoadDelegate
{
return _resourceLoadDelegate->delegate().autorelease();
}
- (void)_setResourceLoadDelegate:(id<_WKResourceLoadDelegate>)delegate
{
if (delegate) {
_page->setResourceLoadClient(_resourceLoadDelegate->createResourceLoadClient());
_resourceLoadDelegate->setDelegate(delegate);
} else {
_page->setResourceLoadClient(nullptr);
_resourceLoadDelegate->setDelegate(nil);
}
}
- (WKNavigation *)loadRequest:(NSURLRequest *)request
{
THROW_IF_SUSPENDED;
if (_page->isServiceWorkerPage())
[NSException raise:NSInternalInconsistencyException format:@"The WKWebView was used to load a service worker"];
return wrapper(_page->loadRequest(request));
}
- (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
{
THROW_IF_SUSPENDED;
if (_page->isServiceWorkerPage())
[NSException raise:NSInternalInconsistencyException format:@"The WKWebView was used to load a service worker"];
if (![URL isFileURL])
[NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
if (![readAccessURL isFileURL])
[NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
return wrapper(_page->loadFile(URL.absoluteString, readAccessURL.absoluteString));
}
- (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
{
THROW_IF_SUSPENDED;
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
}
- (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
{
THROW_IF_SUSPENDED;
if (_page->isServiceWorkerPage())
[NSException raise:NSInternalInconsistencyException format:@"The WKWebView was used to load a service worker"];
return wrapper(_page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, characterEncodingName, baseURL.absoluteString));
}
- (void)startDownloadUsingRequest:(NSURLRequest *)request completionHandler:(void(^)(WKDownload *))completionHandler
{
THROW_IF_SUSPENDED;
_page->downloadRequest(request, [completionHandler = makeBlockPtr(completionHandler)] (auto* download) {
if (download)
completionHandler(wrapper(download));
else
ASSERT_NOT_REACHED();
});
}
- (void)resumeDownloadFromResumeData:(NSData *)resumeData completionHandler:(void(^)(WKDownload *))completionHandler
{
THROW_IF_SUSPENDED;
auto unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingFromData:resumeData error:nil]);
[unarchiver setDecodingFailurePolicy:NSDecodingFailurePolicyRaiseException];
NSDictionary *dictionary = [unarchiver decodeObjectOfClasses:[NSSet setWithObjects:[NSDictionary class], [NSArray class], [NSString class], [NSNumber class], [NSData class], [NSURL class], [NSURLRequest class], nil] forKey:@"NSKeyedArchiveRootObjectKey"];
[unarchiver finishDecoding];
NSString *path = [dictionary objectForKey:@"NSURLSessionResumeInfoLocalPath"];
if (!path)
[NSException raise:NSInvalidArgumentException format:@"Invalid resume data"];
_page->resumeDownload(API::Data::createWithoutCopying(resumeData), path, [completionHandler = makeBlockPtr(completionHandler)] (auto* download) {
if (download)
completionHandler(wrapper(download));
else
ASSERT_NOT_REACHED();
});
}
- (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
{
THROW_IF_SUSPENDED;
return wrapper(_page->goToBackForwardItem(item._item));
}
- (NSString *)title
{
return _page->pageLoadState().title();
}
- (NSURL *)URL
{
return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
}
- (NSURL *)_resourceDirectoryURL
{
return _page->currentResourceDirectoryURL();
}
- (BOOL)isLoading
{
return _page->pageLoadState().isLoading();
}
- (double)estimatedProgress
{
return _page->pageLoadState().estimatedProgress();
}
- (BOOL)hasOnlySecureContent
{
return _page->pageLoadState().hasOnlySecureContent();
}
- (SecTrustRef)serverTrust
{
return _page->pageLoadState().certificateInfo().trust().get();
}
- (BOOL)canGoBack
{
return _page->pageLoadState().canGoBack();
}
- (BOOL)canGoForward
{
return _page->pageLoadState().canGoForward();
}
- (WKNavigation *)goBack
{
THROW_IF_SUSPENDED;
if (self._safeBrowsingWarning)
return [self reload];
return wrapper(_page->goBack());
}
- (WKNavigation *)goForward
{
THROW_IF_SUSPENDED;
return wrapper(_page->goForward());
}
- (WKNavigation *)reload
{
THROW_IF_SUSPENDED;
OptionSet<WebCore::ReloadOption> reloadOptions;
if (linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::ExpiredOnlyReloadBehavior))
reloadOptions.add(WebCore::ReloadOption::ExpiredOnly);
return wrapper(_page->reload(reloadOptions));
}
- (WKNavigation *)reloadFromOrigin
{
THROW_IF_SUSPENDED;
return wrapper(_page->reload(WebCore::ReloadOption::FromOrigin));
}
- (void)stopLoading
{
THROW_IF_SUSPENDED;
_page->stopLoading();
}
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
{
THROW_IF_SUSPENDED;
[self _evaluateJavaScript:javaScriptString asAsyncFunction:NO withSourceURL:nil withArguments:nil forceUserGesture:YES inFrame:nil inWorld:WKContentWorld.pageWorld completionHandler:completionHandler];
}
- (void)evaluateJavaScript:(NSString *)javaScriptString inFrame:(WKFrameInfo *)frame inContentWorld:(WKContentWorld *)contentWorld completionHandler:(void (^)(id, NSError *))completionHandler
{
THROW_IF_SUSPENDED;
[self _evaluateJavaScript:javaScriptString asAsyncFunction:NO withSourceURL:nil withArguments:nil forceUserGesture:YES inFrame:frame inWorld:contentWorld completionHandler:completionHandler];
}
- (void)callAsyncJavaScript:(NSString *)javaScriptString arguments:(NSDictionary<NSString *, id> *)arguments inFrame:(WKFrameInfo *)frame inContentWorld:(WKContentWorld *)contentWorld completionHandler:(void (^)(id, NSError *error))completionHandler
{
THROW_IF_SUSPENDED;
[self _evaluateJavaScript:javaScriptString asAsyncFunction:YES withSourceURL:nil withArguments:arguments forceUserGesture:YES inFrame:frame inWorld:contentWorld completionHandler:completionHandler];
}
static bool validateArgument(id argument)
{
if ([argument isKindOfClass:[NSString class]] || [argument isKindOfClass:[NSNumber class]] || [argument isKindOfClass:[NSDate class]] || [argument isKindOfClass:[NSNull class]])
return true;
if ([argument isKindOfClass:[NSArray class]]) {
__block BOOL valid = true;
[argument enumerateObjectsUsingBlock:^(id object, NSUInteger, BOOL *stop) {
if (!validateArgument(object)) {
valid = false;
*stop = YES;
}
}];
return valid;
}
if ([argument isKindOfClass:[NSDictionary class]]) {
__block bool valid = true;
[argument enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
if (!validateArgument(key) || !validateArgument(value)) {
valid = false;
*stop = YES;
}
}];
return valid;
}
return false;
}
- (void)closeAllMediaPresentations
{
[self closeAllMediaPresentationsWithCompletionHandler:^{ }];
}
- (void)closeAllMediaPresentations:(void (^)(void))completionHandler
{
[self closeAllMediaPresentationsWithCompletionHandler:completionHandler];
}
- (void)closeAllMediaPresentationsWithCompletionHandler:(void (^)(void))completionHandler
{
THROW_IF_SUSPENDED;
auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
#if ENABLE(FULLSCREEN_API)
if (auto videoFullscreenManager = _page->videoFullscreenManager()) {
videoFullscreenManager->forEachSession([callbackAggregator] (auto& model, auto& interface) mutable {
model.requestCloseAllMediaPresentations(false, [callbackAggregator] { });
});
}
if (auto fullScreenManager = _page->fullScreenManager(); fullScreenManager && fullScreenManager->isFullScreen())
fullScreenManager->closeWithCallback([callbackAggregator] { });
#endif
}
- (void)pauseAllMediaPlayback:(void (^)(void))completionHandler
{
[self pauseAllMediaPlaybackWithCompletionHandler:completionHandler];
}