Remove support for legacy Notifications
[WebKit-https.git] / Source / WebKit2 / WebProcess / InjectedBundle / InjectedBundle.cpp
1 /*
2  * Copyright (C) 2010-2016 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 "InjectedBundle.h"
28
29 #include "APIArray.h"
30 #include "APIData.h"
31 #include "InjectedBundleScriptWorld.h"
32 #include "NotificationPermissionRequestManager.h"
33 #include "SessionTracker.h"
34 #include "UserData.h"
35 #include "WKAPICast.h"
36 #include "WKBundleAPICast.h"
37 #include "WebConnectionToUIProcess.h"
38 #include "WebCookieManager.h"
39 #include "WebCoreArgumentCoders.h"
40 #include "WebFrame.h"
41 #include "WebFrameNetworkingContext.h"
42 #include "WebPage.h"
43 #include "WebPageGroupProxy.h"
44 #include "WebPreferencesKeys.h"
45 #include "WebPreferencesStore.h"
46 #include "WebProcess.h"
47 #include "WebProcessCreationParameters.h"
48 #include "WebProcessMessages.h"
49 #include "WebProcessPoolMessages.h"
50 #include "WebUserContentController.h"
51 #include <JavaScriptCore/APICast.h>
52 #include <JavaScriptCore/Exception.h>
53 #include <JavaScriptCore/JSLock.h>
54 #include <WebCore/ApplicationCache.h>
55 #include <WebCore/ApplicationCacheStorage.h>
56 #include <WebCore/CommonVM.h>
57 #include <WebCore/FrameLoader.h>
58 #include <WebCore/FrameView.h>
59 #include <WebCore/GCController.h>
60 #include <WebCore/GeolocationClient.h>
61 #include <WebCore/GeolocationController.h>
62 #include <WebCore/GeolocationPosition.h>
63 #include <WebCore/JSDOMConvertBufferSource.h>
64 #include <WebCore/JSDOMExceptionHandling.h>
65 #include <WebCore/JSDOMWindow.h>
66 #include <WebCore/JSNotification.h>
67 #include <WebCore/MainFrame.h>
68 #include <WebCore/Page.h>
69 #include <WebCore/PageGroup.h>
70 #include <WebCore/PrintContext.h>
71 #include <WebCore/ResourceHandle.h>
72 #include <WebCore/RuntimeEnabledFeatures.h>
73 #include <WebCore/ScriptController.h>
74 #include <WebCore/SecurityOrigin.h>
75 #include <WebCore/SecurityPolicy.h>
76 #include <WebCore/SessionID.h>
77 #include <WebCore/Settings.h>
78 #include <WebCore/UserGestureIndicator.h>
79 #include <WebCore/UserScript.h>
80 #include <WebCore/UserStyleSheet.h>
81
82 #if ENABLE(NOTIFICATIONS)
83 #include "WebNotificationManager.h"
84 #endif
85
86 using namespace WebCore;
87 using namespace JSC;
88
89 namespace WebKit {
90
91 PassRefPtr<InjectedBundle> InjectedBundle::create(const WebProcessCreationParameters& parameters, API::Object* initializationUserData)
92 {
93     auto bundle = adoptRef(*new InjectedBundle(parameters));
94
95     bundle->m_sandboxExtension = SandboxExtension::create(parameters.injectedBundlePathExtensionHandle);
96     if (!bundle->initialize(parameters, initializationUserData))
97         return nullptr;
98
99     return WTFMove(bundle);
100 }
101
102 InjectedBundle::InjectedBundle(const WebProcessCreationParameters& parameters)
103     : m_path(parameters.injectedBundlePath)
104     , m_platformBundle(0)
105 {
106 }
107
108 InjectedBundle::~InjectedBundle()
109 {
110 }
111
112 void InjectedBundle::initializeClient(const WKBundleClientBase* client)
113 {
114     m_client.initialize(client);
115 }
116
117 void InjectedBundle::postMessage(const String& messageName, API::Object* messageBody)
118 {
119     auto& webProcess = WebProcess::singleton();
120     webProcess.parentProcessConnection()->send(Messages::WebProcessPool::HandleMessage(messageName, UserData(webProcess.transformObjectsToHandles(messageBody))), 0);
121 }
122
123 void InjectedBundle::postSynchronousMessage(const String& messageName, API::Object* messageBody, RefPtr<API::Object>& returnData)
124 {
125     UserData returnUserData;
126
127     auto& webProcess = WebProcess::singleton();
128     if (!webProcess.parentProcessConnection()->sendSync(Messages::WebProcessPool::HandleSynchronousMessage(messageName, UserData(webProcess.transformObjectsToHandles(messageBody))), Messages::WebProcessPool::HandleSynchronousMessage::Reply(returnUserData), 0))
129         returnData = nullptr;
130     else
131         returnData = webProcess.transformHandlesToObjects(returnUserData.object());
132 }
133
134 WebConnection* InjectedBundle::webConnectionToUIProcess() const
135 {
136     return WebProcess::singleton().webConnectionToUIProcess();
137 }
138
139 void InjectedBundle::overrideBoolPreferenceForTestRunner(WebPageGroupProxy* pageGroup, const String& preference, bool enabled)
140 {
141     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
142
143     if (preference == "WebKitTabToLinksPreferenceKey") {
144         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::tabsToLinksKey(), enabled);
145         for (auto* page : pages)
146             WebPage::fromCorePage(page)->setTabToLinksEnabled(enabled);
147     }
148
149     if (preference == "WebKit2AsynchronousPluginInitializationEnabled") {
150         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey(), enabled);
151         for (auto* page : pages)
152             WebPage::fromCorePage(page)->setAsynchronousPluginInitializationEnabled(enabled);
153     }
154
155     if (preference == "WebKit2AsynchronousPluginInitializationEnabledForAllPlugins") {
156         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey(), enabled);
157         for (auto* page : pages)
158             WebPage::fromCorePage(page)->setAsynchronousPluginInitializationEnabledForAllPlugins(enabled);
159     }
160
161     if (preference == "WebKit2ArtificialPluginInitializationDelayEnabled") {
162         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey(), enabled);
163         for (auto* page : pages)
164             WebPage::fromCorePage(page)->setArtificialPluginInitializationDelayEnabled(enabled);
165     }
166
167 #if ENABLE(SERVICE_CONTROLS)
168     if (preference == "WebKitImageControlsEnabled") {
169         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey(), enabled);
170         for (auto* page : pages)
171             page->settings().setImageControlsEnabled(enabled);
172         return;
173     }
174 #endif
175
176 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
177     if (preference == "WebKitCSSAnimationTriggersEnabled")
178         RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(enabled);
179 #endif
180
181 #if ENABLE(WEB_ANIMATIONS)
182     if (preference == "WebKitWebAnimationsEnabled")
183         RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(enabled);
184 #endif
185
186 #if ENABLE(STREAMS_API)
187     if (preference == "WebKitReadableByteStreamAPIEnabled")
188         RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled(enabled);
189     if (preference == "WebKitWritableStreamAPIEnabled")
190         RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled(enabled);
191 #endif
192
193     if (preference == "WebKitCSSGridLayoutEnabled")
194         RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled(enabled);
195
196     if (preference == "WebKitInteractiveFormValidationEnabled")
197         RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled(enabled);
198
199 #if ENABLE(WEBGL2)
200     if (preference == "WebKitWebGL2Enabled")
201         RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(enabled);
202 #endif
203
204 #if ENABLE(WEBGPU)
205     if (preference == "WebKitWebGPUEnabled")
206         RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled(enabled);
207 #endif
208
209     if (preference == "WebKitModernMediaControlsEnabled")
210         RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled(enabled);
211
212 #if ENABLE(ENCRYPTED_MEDIA)
213     if (preference == "WebKitEncryptedMediaAPIEnabled")
214         RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(enabled);
215 #endif
216
217 #if ENABLE(SUBTLE_CRYPTO)
218     if (preference == "WebKitSubtleCryptoEnabled")
219         RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled(enabled);
220 #endif
221
222 #if ENABLE(MEDIA_STREAM)
223     if (preference == "WebKitMediaDevicesEnabled")
224         RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(enabled);
225 #endif
226
227 #if ENABLE(WEB_RTC)
228     if (preference == "WebKitWebRTCLegacyAPIEnabled")
229         RuntimeEnabledFeatures::sharedFeatures().setWebRTCLegacyAPIEnabled(enabled);
230 #endif
231
232     // Map the names used in LayoutTests with the names used in WebCore::Settings and WebPreferencesStore.
233 #define FOR_EACH_OVERRIDE_BOOL_PREFERENCE(macro) \
234     macro(WebKitAcceleratedCompositingEnabled, AcceleratedCompositingEnabled, acceleratedCompositingEnabled) \
235     macro(WebKitCanvasUsesAcceleratedDrawing, CanvasUsesAcceleratedDrawing, canvasUsesAcceleratedDrawing) \
236     macro(WebKitFrameFlatteningEnabled, FrameFlatteningEnabled, frameFlatteningEnabled) \
237     macro(WebKitJavaEnabled, JavaEnabled, javaEnabled) \
238     macro(WebKitJavaScriptEnabled, ScriptEnabled, javaScriptEnabled) \
239     macro(WebKitLoadSiteIconsKey, LoadsSiteIconsIgnoringImageLoadingSetting, loadsSiteIconsIgnoringImageLoadingPreference) \
240     macro(WebKitOfflineWebApplicationCacheEnabled, OfflineWebApplicationCacheEnabled, offlineWebApplicationCacheEnabled) \
241     macro(WebKitPageCacheSupportsPluginsPreferenceKey, PageCacheSupportsPlugins, pageCacheSupportsPlugins) \
242     macro(WebKitPluginsEnabled, PluginsEnabled, pluginsEnabled) \
243     macro(WebKitUsesPageCachePreferenceKey, UsesPageCache, usesPageCache) \
244     macro(WebKitWebAudioEnabled, WebAudioEnabled, webAudioEnabled) \
245     macro(WebKitWebGLEnabled, WebGLEnabled, webGLEnabled) \
246     macro(WebKitXSSAuditorEnabled, XSSAuditorEnabled, xssAuditorEnabled) \
247     macro(WebKitShouldRespectImageOrientation, ShouldRespectImageOrientation, shouldRespectImageOrientation) \
248     macro(WebKitEnableCaretBrowsing, CaretBrowsingEnabled, caretBrowsingEnabled) \
249     macro(WebKitDisplayImagesKey, LoadsImagesAutomatically, loadsImagesAutomatically) \
250     macro(WebKitHTTPEquivEnabled, HttpEquivEnabled, httpEquivEnabled) \
251     macro(WebKitVisualViewportEnabled, VisualViewportEnabled, visualViewportEnabled) \
252     macro(WebKitLargeImageAsyncDecodingEnabled, LargeImageAsyncDecodingEnabled, largeImageAsyncDecodingEnabled) \
253     macro(WebKitAnimatedImageAsyncDecodingEnabled, AnimatedImageAsyncDecodingEnabled, animatedImageAsyncDecodingEnabled) \
254     \
255
256 #define OVERRIDE_PREFERENCE_AND_SET_IN_EXISTING_PAGES(TestRunnerName, SettingsName, WebPreferencesName) \
257     if (preference == #TestRunnerName) { \
258         WebPreferencesStore::overrideBoolValueForKey(WebPreferencesKey::WebPreferencesName##Key(), enabled); \
259         for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter) \
260             (*iter)->settings().set##SettingsName(enabled); \
261         return; \
262     }
263
264     FOR_EACH_OVERRIDE_BOOL_PREFERENCE(OVERRIDE_PREFERENCE_AND_SET_IN_EXISTING_PAGES)
265
266     OVERRIDE_PREFERENCE_AND_SET_IN_EXISTING_PAGES(WebKitHiddenPageDOMTimerThrottlingEnabled, HiddenPageDOMTimerThrottlingEnabled, hiddenPageDOMTimerThrottlingEnabled)
267
268 #undef OVERRIDE_PREFERENCE_AND_SET_IN_EXISTING_PAGES
269 #undef FOR_EACH_OVERRIDE_BOOL_PREFERENCE
270 }
271
272 void InjectedBundle::setAllowUniversalAccessFromFileURLs(WebPageGroupProxy* pageGroup, bool enabled)
273 {
274     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
275     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
276         (*iter)->settings().setAllowUniversalAccessFromFileURLs(enabled);
277 }
278
279 void InjectedBundle::setAllowFileAccessFromFileURLs(WebPageGroupProxy* pageGroup, bool enabled)
280 {
281     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
282     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
283         (*iter)->settings().setAllowFileAccessFromFileURLs(enabled);
284 }
285
286 void InjectedBundle::setNeedsStorageAccessFromFileURLsQuirk(WebPageGroupProxy* pageGroup, bool needsQuirk)
287 {
288     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
289     for (auto page : pages)
290         page->settings().setNeedsStorageAccessFromFileURLsQuirk(needsQuirk);
291 }
292
293 void InjectedBundle::setMinimumLogicalFontSize(WebPageGroupProxy* pageGroup, int size)
294 {
295     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
296     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
297         (*iter)->settings().setMinimumLogicalFontSize(size);
298 }
299
300 void InjectedBundle::setFrameFlatteningEnabled(WebPageGroupProxy* pageGroup, bool enabled)
301 {
302     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
303     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
304         (*iter)->settings().setFrameFlatteningEnabled(enabled);
305 }
306
307 void InjectedBundle::setJavaScriptCanAccessClipboard(WebPageGroupProxy* pageGroup, bool enabled)
308 {
309     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
310     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
311         (*iter)->settings().setJavaScriptCanAccessClipboard(enabled);
312 }
313
314 void InjectedBundle::setPrivateBrowsingEnabled(WebPageGroupProxy* pageGroup, bool enabled)
315 {
316     if (enabled) {
317         WebProcess::singleton().ensureLegacyPrivateBrowsingSessionInNetworkProcess();
318         WebFrameNetworkingContext::ensurePrivateBrowsingSession(SessionID::legacyPrivateSessionID());
319     } else
320         SessionTracker::destroySession(SessionID::legacyPrivateSessionID());
321
322     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
323     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
324         (*iter)->enableLegacyPrivateBrowsing(enabled);
325 }
326
327 void InjectedBundle::setUseDashboardCompatibilityMode(WebPageGroupProxy* pageGroup, bool enabled)
328 {
329 #if ENABLE(DASHBOARD_SUPPORT)
330     for (auto& page : PageGroup::pageGroup(pageGroup->identifier())->pages())
331         page->settings().setUsesDashboardBackwardCompatibilityMode(enabled);
332 #endif
333 }
334
335 void InjectedBundle::setPopupBlockingEnabled(WebPageGroupProxy* pageGroup, bool enabled)
336 {
337     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
338     HashSet<Page*>::const_iterator end = pages.end();
339     for (HashSet<Page*>::const_iterator iter = pages.begin(); iter != end; ++iter)
340         (*iter)->settings().setJavaScriptCanOpenWindowsAutomatically(!enabled);
341 }
342
343 void InjectedBundle::setAuthorAndUserStylesEnabled(WebPageGroupProxy* pageGroup, bool enabled)
344 {
345     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
346     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
347         (*iter)->settings().setAuthorAndUserStylesEnabled(enabled);
348 }
349
350 void InjectedBundle::setSpatialNavigationEnabled(WebPageGroupProxy* pageGroup, bool enabled)
351 {
352     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
353     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
354         (*iter)->settings().setSpatialNavigationEnabled(enabled);
355 }
356
357 void InjectedBundle::addOriginAccessWhitelistEntry(const String& sourceOrigin, const String& destinationProtocol, const String& destinationHost, bool allowDestinationSubdomains)
358 {
359     SecurityPolicy::addOriginAccessWhitelistEntry(SecurityOrigin::createFromString(sourceOrigin).get(), destinationProtocol, destinationHost, allowDestinationSubdomains);
360 }
361
362 void InjectedBundle::removeOriginAccessWhitelistEntry(const String& sourceOrigin, const String& destinationProtocol, const String& destinationHost, bool allowDestinationSubdomains)
363 {
364     SecurityPolicy::removeOriginAccessWhitelistEntry(SecurityOrigin::createFromString(sourceOrigin).get(), destinationProtocol, destinationHost, allowDestinationSubdomains);
365 }
366
367 void InjectedBundle::resetOriginAccessWhitelists()
368 {
369     SecurityPolicy::resetOriginAccessWhitelists();
370 }
371
372 void InjectedBundle::setAsynchronousSpellCheckingEnabled(WebPageGroupProxy* pageGroup, bool enabled)
373 {
374     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
375     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
376         (*iter)->settings().setAsynchronousSpellCheckingEnabled(enabled);
377 }
378
379 int InjectedBundle::numberOfPages(WebFrame* frame, double pageWidthInPixels, double pageHeightInPixels)
380 {
381     Frame* coreFrame = frame ? frame->coreFrame() : 0;
382     if (!coreFrame)
383         return -1;
384     if (!pageWidthInPixels)
385         pageWidthInPixels = coreFrame->view()->width();
386     if (!pageHeightInPixels)
387         pageHeightInPixels = coreFrame->view()->height();
388
389     return PrintContext::numberOfPages(*coreFrame, FloatSize(pageWidthInPixels, pageHeightInPixels));
390 }
391
392 int InjectedBundle::pageNumberForElementById(WebFrame* frame, const String& id, double pageWidthInPixels, double pageHeightInPixels)
393 {
394     Frame* coreFrame = frame ? frame->coreFrame() : 0;
395     if (!coreFrame)
396         return -1;
397
398     Element* element = coreFrame->document()->getElementById(id);
399     if (!element)
400         return -1;
401
402     if (!pageWidthInPixels)
403         pageWidthInPixels = coreFrame->view()->width();
404     if (!pageHeightInPixels)
405         pageHeightInPixels = coreFrame->view()->height();
406
407     return PrintContext::pageNumberForElement(element, FloatSize(pageWidthInPixels, pageHeightInPixels));
408 }
409
410 String InjectedBundle::pageSizeAndMarginsInPixels(WebFrame* frame, int pageIndex, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft)
411 {
412     Frame* coreFrame = frame ? frame->coreFrame() : 0;
413     if (!coreFrame)
414         return String();
415
416     return PrintContext::pageSizeAndMarginsInPixels(coreFrame, pageIndex, width, height, marginTop, marginRight, marginBottom, marginLeft);
417 }
418
419 bool InjectedBundle::isPageBoxVisible(WebFrame* frame, int pageIndex)
420 {
421     Frame* coreFrame = frame ? frame->coreFrame() : 0;
422     if (!coreFrame)
423         return false;
424
425     return PrintContext::isPageBoxVisible(coreFrame, pageIndex);
426 }
427
428 bool InjectedBundle::isProcessingUserGesture()
429 {
430     return ScriptController::processingUserGesture();
431 }
432
433 void InjectedBundle::addUserScript(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld, const String& source, const String& url, API::Array* whitelist, API::Array* blacklist, WebCore::UserScriptInjectionTime injectionTime, WebCore::UserContentInjectedFrames injectedFrames)
434 {
435     // url is not from URL::string(), i.e. it has not already been parsed by URL, so we have to use the relative URL constructor for URL instead of the ParsedURLStringTag version.
436     UserScript userScript{ source, URL(URL(), url), whitelist ? whitelist->toStringVector() : Vector<String>(), blacklist ? blacklist->toStringVector() : Vector<String>(), injectionTime, injectedFrames };
437
438     pageGroup->userContentController().addUserScript(*scriptWorld, WTFMove(userScript));
439 }
440
441 void InjectedBundle::addUserStyleSheet(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld, const String& source, const String& url, API::Array* whitelist, API::Array* blacklist, WebCore::UserContentInjectedFrames injectedFrames)
442 {
443     // url is not from URL::string(), i.e. it has not already been parsed by URL, so we have to use the relative URL constructor for URL instead of the ParsedURLStringTag version.
444     UserStyleSheet userStyleSheet{ source, URL(URL(), url), whitelist ? whitelist->toStringVector() : Vector<String>(), blacklist ? blacklist->toStringVector() : Vector<String>(), injectedFrames, UserStyleUserLevel };
445
446     pageGroup->userContentController().addUserStyleSheet(*scriptWorld, WTFMove(userStyleSheet));
447 }
448
449 void InjectedBundle::removeUserScript(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld, const String& url)
450 {
451     // url is not from URL::string(), i.e. it has not already been parsed by URL, so we have to use the relative URL constructor for URL instead of the ParsedURLStringTag version.
452     pageGroup->userContentController().removeUserScriptWithURL(*scriptWorld, URL(URL(), url));
453 }
454
455 void InjectedBundle::removeUserStyleSheet(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld, const String& url)
456 {
457     // url is not from URL::string(), i.e. it has not already been parsed by URL, so we have to use the relative URL constructor for URL instead of the ParsedURLStringTag version.
458     pageGroup->userContentController().removeUserStyleSheetWithURL(*scriptWorld, URL(URL(), url));
459 }
460
461 void InjectedBundle::removeUserScripts(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld)
462 {
463     pageGroup->userContentController().removeUserScripts(*scriptWorld);
464 }
465
466 void InjectedBundle::removeUserStyleSheets(WebPageGroupProxy* pageGroup, InjectedBundleScriptWorld* scriptWorld)
467 {
468     pageGroup->userContentController().removeUserStyleSheets(*scriptWorld);
469 }
470
471 void InjectedBundle::removeAllUserContent(WebPageGroupProxy* pageGroup)
472 {
473     pageGroup->userContentController().removeAllUserContent();
474 }
475
476 void InjectedBundle::garbageCollectJavaScriptObjects()
477 {
478     GCController::singleton().garbageCollectNow();
479 }
480
481 void InjectedBundle::garbageCollectJavaScriptObjectsOnAlternateThreadForDebugging(bool waitUntilDone)
482 {
483     GCController::singleton().garbageCollectOnAlternateThreadForDebugging(waitUntilDone);
484 }
485
486 size_t InjectedBundle::javaScriptObjectsCount()
487 {
488     JSLockHolder lock(commonVM());
489     return commonVM().heap.objectCount();
490 }
491
492 void InjectedBundle::reportException(JSContextRef context, JSValueRef exception)
493 {
494     if (!context || !exception)
495         return;
496
497     JSC::ExecState* execState = toJS(context);
498     JSLockHolder lock(execState);
499
500     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a Page.
501     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
502     if (!toJSDOMWindow(globalObject->vm(), globalObject))
503         return;
504
505     WebCore::reportException(execState, toJS(execState, exception));
506 }
507
508 void InjectedBundle::didCreatePage(WebPage* page)
509 {
510     m_client.didCreatePage(this, page);
511 }
512
513 void InjectedBundle::willDestroyPage(WebPage* page)
514 {
515     m_client.willDestroyPage(this, page);
516 }
517
518 void InjectedBundle::didInitializePageGroup(WebPageGroupProxy* pageGroup)
519 {
520     m_client.didInitializePageGroup(this, pageGroup);
521 }
522
523 void InjectedBundle::didReceiveMessage(const String& messageName, API::Object* messageBody)
524 {
525     m_client.didReceiveMessage(this, messageName, messageBody);
526 }
527
528 void InjectedBundle::didReceiveMessageToPage(WebPage* page, const String& messageName, API::Object* messageBody)
529 {
530     m_client.didReceiveMessageToPage(this, page, messageName, messageBody);
531 }
532
533 void InjectedBundle::setUserStyleSheetLocation(WebPageGroupProxy* pageGroup, const String& location)
534 {
535     const HashSet<Page*>& pages = PageGroup::pageGroup(pageGroup->identifier())->pages();
536     for (HashSet<Page*>::iterator iter = pages.begin(); iter != pages.end(); ++iter)
537         (*iter)->settings().setUserStyleSheetLocation(URL(URL(), location));
538 }
539
540 void InjectedBundle::setWebNotificationPermission(WebPage* page, const String& originString, bool allowed)
541 {
542 #if ENABLE(NOTIFICATIONS)
543     page->notificationPermissionRequestManager()->setPermissionLevelForTesting(originString, allowed);
544 #else
545     UNUSED_PARAM(page);
546     UNUSED_PARAM(originString);
547     UNUSED_PARAM(allowed);
548 #endif
549 }
550
551 void InjectedBundle::removeAllWebNotificationPermissions(WebPage* page)
552 {
553 #if ENABLE(NOTIFICATIONS)
554     page->notificationPermissionRequestManager()->removeAllPermissionsForTesting();
555 #else
556     UNUSED_PARAM(page);
557 #endif
558 }
559
560 uint64_t InjectedBundle::webNotificationID(JSContextRef jsContext, JSValueRef jsNotification)
561 {
562 #if ENABLE(NOTIFICATIONS)
563     WebCore::Notification* notification = JSNotification::toWrapped(toJS(jsContext)->vm(), toJS(toJS(jsContext), jsNotification));
564     if (!notification)
565         return 0;
566     return WebProcess::singleton().supplement<WebNotificationManager>()->notificationIDForTesting(notification);
567 #else
568     UNUSED_PARAM(jsContext);
569     UNUSED_PARAM(jsNotification);
570     return 0;
571 #endif
572 }
573
574 // FIXME Get rid of this function and move it into WKBundle.cpp.
575 PassRefPtr<API::Data> InjectedBundle::createWebDataFromUint8Array(JSContextRef context, JSValueRef data)
576 {
577     JSC::ExecState* execState = toJS(context);
578     RefPtr<Uint8Array> arrayData = WebCore::toUnsharedUint8Array(execState->vm(), toJS(execState, data));
579     return API::Data::create(static_cast<unsigned char*>(arrayData->baseAddress()), arrayData->byteLength());
580 }
581
582 void InjectedBundle::setTabKeyCyclesThroughElements(WebPage* page, bool enabled)
583 {
584     page->corePage()->setTabKeyCyclesThroughElements(enabled);
585 }
586
587 void InjectedBundle::setCSSAnimationTriggersEnabled(bool enabled)
588 {
589 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
590     RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(enabled);
591 #else
592     UNUSED_PARAM(enabled);
593 #endif
594 }
595
596 void InjectedBundle::setWebAnimationsEnabled(bool enabled)
597 {
598 #if ENABLE(WEB_ANIMATIONS)
599     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(enabled);
600 #else
601     UNUSED_PARAM(enabled);
602 #endif
603 }
604
605 } // namespace WebKit