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 #include "base/files/file_path.h"
8 #include "base/files/file_util.h"
9 #include "base/mac/bundle_locations.h"
10 #include "base/strings/sys_string_conversions.h"
11 #include "ios/web/public/web_client.h"
16 // Returns an autoreleased string containing the JavaScript to be injected into
17 // the web view as early as possible. Does not include embedder's script.
18 NSString* GetWebEarlyPageScript(WebViewType web_view_type) {
19 switch (web_view_type) {
20 case UI_WEB_VIEW_TYPE:
21 return GetPageScript(@"web_bundle_ui");
22 case WK_WEB_VIEW_TYPE:
23 return GetPageScript(@"web_bundle_wk");
30 NSString* GetPageScript(NSString* script_file_name) {
31 DCHECK(script_file_name);
33 [base::mac::FrameworkBundle() pathForResource:script_file_name
35 DCHECK(path) << "Script file not found: "
36 << base::SysNSStringToUTF8(script_file_name) << ".js";
38 NSString* content = [NSString stringWithContentsOfFile:path
39 encoding:NSUTF8StringEncoding
41 DCHECK(!error) << "Error fetching script: " << [error.description UTF8String];
46 NSString* GetEarlyPageScript(WebViewType web_view_type) {
47 DCHECK(GetWebClient());
48 NSString* embedder_page_script =
49 GetWebClient()->GetEarlyPageScript(web_view_type);
50 DCHECK(embedder_page_script);
52 // Make sure that script is injected only once. For example, content of
53 // WKUserScript can be injected into the same page multiple times
54 // without notifying WKNavigationDelegate (e.g. after window.document.write
55 // JavaScript call). Injecting the script multiple times invalidates the
56 // __gCrWeb.windowId variable and will break the ability to send messages from
57 // JS to the native code. Wrapping injected script into "if (!injected)" check
58 // prevents multiple injections into the same page.
59 NSString* kScriptTemplate = @"if (typeof __gCrWeb !== 'object') { %@; %@ }";
60 return [NSString stringWithFormat:kScriptTemplate,
61 GetWebEarlyPageScript(web_view_type),
62 embedder_page_script];