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.
4 
5 package org.chromium.chrome.browser.document;
6 
7 import org.chromium.base.BuildInfo;
8 import org.chromium.base.annotations.NativeMethods;
9 import org.chromium.components.embedder_support.delegate.WebContentsDelegateAndroid;
10 import org.chromium.content_public.browser.WebContents;
11 
12 /**
13  * Stubs out calls to the WebContentsDelegateAndroid.  Attaching a WebContentsDelegateAndroid to a
14  * newly created WebContents signals to Chrome that it was created properly, which is needed in
15  * situations where Chrome on Android needs to create the Activity for the WebContents
16  * asynchronously.
17  */
18 public class DocumentWebContentsDelegate extends WebContentsDelegateAndroid {
19     /**
20      * Singleton instance of the WebContentsDelegate.  Delegates can be assigned to multiple
21      * WebContents.
22      */
23     private static DocumentWebContentsDelegate sInstance;
24 
25     /**
26      * Native side pointer to the stubbed WebContentsDelegate.
27      */
28     private long mNativePtr;
29 
30     /**
31      * @return The Singleton instance, creating it if necessary.
32      */
getInstance()33     public static DocumentWebContentsDelegate getInstance() {
34         if (sInstance == null) sInstance = new DocumentWebContentsDelegate();
35         return sInstance;
36     }
37 
38     /**
39      * Attaches the native side delegate to the native WebContents.
40      * @param webContents The {@link WebContents} to attach to.
41      */
attachDelegate(WebContents webContents)42     public void attachDelegate(WebContents webContents) {
43         DocumentWebContentsDelegateJni.get().attachContents(
44                 mNativePtr, DocumentWebContentsDelegate.this, webContents);
45     }
46 
DocumentWebContentsDelegate()47     private DocumentWebContentsDelegate() {
48         mNativePtr =
49                 DocumentWebContentsDelegateJni.get().initialize(DocumentWebContentsDelegate.this);
50     }
51 
52     @Override
addMessageToConsole(int level, String message, int lineNumber, String sourceId)53     public boolean addMessageToConsole(int level, String message, int lineNumber, String sourceId) {
54         // Only output console.log messages on debug variants of Android OS. crbug/869804
55         return !BuildInfo.isDebugAndroid();
56     }
57 
58     @NativeMethods
59     interface Natives {
initialize(DocumentWebContentsDelegate caller)60         long initialize(DocumentWebContentsDelegate caller);
attachContents(long nativeDocumentWebContentsDelegate, DocumentWebContentsDelegate caller, WebContents webContents)61         void attachContents(long nativeDocumentWebContentsDelegate,
62                 DocumentWebContentsDelegate caller, WebContents webContents);
63     }
64 }
65