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