Upstream JavaScript injection for iOS
[chromium-blink-merge.git] / ios / web / web_state / js / crw_js_injection_receiver.mm
blob745fab8d14be2cd26d9c95eb1e62585c4a5b17e7
1 // Copyright 2012 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/public/web_state/js/crw_js_injection_receiver.h"
7 #include "base/logging.h"
8 #import "base/mac/scoped_nsobject.h"
9 #import "ios/web/public/web_state/js/crw_js_injection_evaluator.h"
10 #import "ios/web/public/web_state/js/crw_js_injection_manager.h"
12 @implementation CRWJSInjectionReceiver {
13   // Used to evaluate JavaScripts.
14   id<CRWJSInjectionEvaluator> _evaluator;
16   // Map from a CRWJSInjectionManager class to its instance created for this
17   // receiver.
18   base::scoped_nsobject<NSMutableDictionary> _managers;
21 - (id)init {
22   NOTREACHED();
23   return [super init];
26 - (id)initWithEvaluator:(id<CRWJSInjectionEvaluator>)evaluator {
27   DCHECK(evaluator);
28   self = [super init];
29   if (self) {
30     _evaluator = evaluator;
31     _managers.reset([[NSMutableDictionary alloc] init]);
32   }
33   return self;
36 #pragma mark -
37 #pragma mark CRWJSInjectionEvaluatorMethods
39 - (void)evaluateJavaScript:(NSString*)script
40        stringResultHandler:(web::JavaScriptCompletion)handler {
41   [_evaluator evaluateJavaScript:script stringResultHandler:handler];
44 - (BOOL)scriptHasBeenInjectedForClass:(Class)jsInjectionManagerClass
45                        presenceBeacon:(NSString*)beacon {
46   return [_evaluator scriptHasBeenInjectedForClass:jsInjectionManagerClass
47                                     presenceBeacon:beacon];
50 - (void)injectScript:(NSString*)script forClass:(Class)jsInjectionManagerClass {
51   [_evaluator injectScript:script forClass:jsInjectionManagerClass];
54 - (CRWJSInjectionManager*)instanceOfClass:(Class)jsInjectionManagerClass {
55   DCHECK(_managers);
56   CRWJSInjectionManager* manager =
57       [_managers objectForKey:jsInjectionManagerClass];
58   if (!manager) {
59     base::scoped_nsobject<CRWJSInjectionManager> newManager(
60         [[jsInjectionManagerClass alloc] initWithReceiver:self]);
61     [_managers setObject:newManager forKey:jsInjectionManagerClass];
62     manager = newManager;
63   }
64   DCHECK(manager);
65   for (Class depedencyClass in [manager directDependencies]) {
66     [self instanceOfClass:depedencyClass];
67   }
68   return manager;
71 @end
73 @implementation CRWJSInjectionReceiver (Testing)
74 - (NSDictionary*)managers {
75   return _managers.get();
77 @end