1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/web_state/js/page_script_util.h"
7 #import <UIKit/UIKit.h>
8 #import <WebKit/WebKit.h>
10 #import "base/mac/scoped_nsobject.h"
11 #include "base/strings/sys_string_conversions.h"
12 #import "base/test/ios/wait_util.h"
13 #import "ios/web/public/test/js_test_util.h"
14 #include "ios/web/public/test/test_browser_state.h"
15 #import "ios/web/public/test/test_web_client.h"
16 #include "ios/web/public/test/web_test_util.h"
17 #import "ios/web/web_state/web_view_creation_utils.h"
18 #include "testing/gtest_mac.h"
19 #include "testing/platform_test.h"
24 class PageScriptUtilTest : public PlatformTest {
26 void SetUp() override { SetWebClient(&web_client_); }
28 void TearDown() override { SetWebClient(nullptr); }
30 // WebClient and BrowserState required for web view creation.
31 TestWebClient web_client_;
32 TestBrowserState browser_state_;
35 // Tests that UIWebView early page script is a valid script that injects global
37 TEST_F(PageScriptUtilTest, UIWebViewEarlyPageScript) {
38 base::scoped_nsobject<UIWebView> web_view([[UIWebView alloc] init]);
39 EvaluateJavaScriptAsString(web_view, GetEarlyPageScript(UI_WEB_VIEW_TYPE));
40 EXPECT_NSEQ(@"object",
41 EvaluateJavaScriptAsString(web_view, @"typeof __gCrWeb"));
44 // Tests that WKWebView early page script is a valid script that injects global
46 TEST_F(PageScriptUtilTest, WKWebViewEarlyPageScript) {
47 CR_TEST_REQUIRES_WK_WEB_VIEW();
48 base::scoped_nsobject<WKWebView> web_view(
49 CreateWKWebView(CGRectZero, &browser_state_));
50 EvaluateJavaScript(web_view, GetEarlyPageScript(WK_WEB_VIEW_TYPE));
51 EXPECT_NSEQ(@"object", EvaluateJavaScript(web_view, @"typeof __gCrWeb"));
54 // Tests that embedder's UIWebView script is included into early script.
55 TEST_F(PageScriptUtilTest, UIEmbedderScript) {
56 web_client_.SetEarlyPageScript(@"__gCrEmbedder = {};", UI_WEB_VIEW_TYPE);
57 base::scoped_nsobject<UIWebView> web_view([[UIWebView alloc] init]);
58 EvaluateJavaScriptAsString(web_view, GetEarlyPageScript(UI_WEB_VIEW_TYPE));
59 EXPECT_NSEQ(@"object",
60 EvaluateJavaScriptAsString(web_view, @"typeof __gCrEmbedder"));
63 // Tests that embedder's WKWebView script is included into early script.
64 TEST_F(PageScriptUtilTest, WKEmbedderScript) {
65 CR_TEST_REQUIRES_WK_WEB_VIEW();
66 web_client_.SetEarlyPageScript(@"__gCrEmbedder = {};", WK_WEB_VIEW_TYPE);
67 base::scoped_nsobject<WKWebView> web_view(
68 CreateWKWebView(CGRectZero, &browser_state_));
69 EvaluateJavaScript(web_view, GetEarlyPageScript(WK_WEB_VIEW_TYPE));
70 EXPECT_NSEQ(@"object", EvaluateJavaScript(web_view, @"typeof __gCrEmbedder"));