1 // Copyright 2013 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 "components/translate/ios/browser/js_translate_manager.h"
7 #import <Foundation/Foundation.h>
9 #include "base/logging.h"
10 #include "base/mac/bundle_locations.h"
11 #import "base/mac/scoped_nsobject.h"
12 #include "base/memory/scoped_ptr.h"
14 @implementation JsTranslateManager {
15 base::scoped_nsobject<NSString> _translationScript;
19 return _translationScript.get();
22 - (void)setScript:(NSString*)script {
23 // The translation script uses performance.now() for metrics, which is not
24 // supported except on iOS 8.0. To make the translation script work on these
25 // iOS versions, add some JavaScript to |script| that defines an
26 // implementation of performance.now().
27 NSString* const kPerformancePlaceholder =
28 @"var performance = window['performance'] || {};"
29 @"performance.now = performance['now'] ||"
30 @"(function () { return Date.now(); });\n";
31 script = [kPerformancePlaceholder stringByAppendingString:script];
32 // TODO(shreyasv): This leads to some duplicate code from
33 // CRWJSInjectionManager. Consider refactoring this to its own js injection
36 [base::mac::FrameworkBundle() pathForResource:@"translate_ios"
40 NSString* content = [NSString stringWithContentsOfFile:path
41 encoding:NSUTF8StringEncoding
43 DCHECK(!error && [content length]);
44 script = [script stringByAppendingString:content];
45 _translationScript.reset([script copy]);
48 - (void)injectWaitUntilTranslateReadyScript {
49 [self.receiver evaluateJavaScript:@"__gCrWeb.translate.checkTranslateReady()"
50 stringResultHandler:nil];
53 - (void)injectTranslateStatusScript {
54 [self.receiver evaluateJavaScript:@"__gCrWeb.translate.checkTranslateStatus()"
55 stringResultHandler:nil];
58 - (void)startTranslationFrom:(const std::string&)source
59 to:(const std::string&)target {
61 [NSString stringWithFormat:@"cr.googleTranslate.translate('%s','%s')",
62 source.c_str(), target.c_str()];
63 [self.receiver evaluateJavaScript:js stringResultHandler:nil];
66 - (void)revertTranslation {
67 DCHECK([self hasBeenInjected]);
68 [self.receiver evaluateJavaScript:@"cr.googleTranslate.revert()"
69 stringResultHandler:nil];
73 #pragma mark CRWJSInjectionManager methods
75 - (NSString*)injectionContent {
76 DCHECK(_translationScript);
77 return _translationScript.autorelease();
80 - (NSString*)presenceBeacon {
81 return @"cr.googleTranslate";