Class BrowserComponent

All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>

public class BrowserComponent extends Container

The browser component is an interface to an embeddable native platform browser on platforms that support embedding the native browser in place, if you need wide compatibility and flexibility you should check out the HTMLComponent which provides a lightweight 100% cross platform web component.

This component will only work on platforms that support embedding a native browser which exclude earlier versions of Blackberry devices and J2ME devices.

Its recommended that you place this component in a fixed position (none scrollable) on the screen without other focusable components to prevent confusion between focus authority and allow the component to scroll itself rather than CodenameOne making that decision for it.

On Android this component might show a native progress indicator dialog. You can disable that functionality using the call.

The following code shows the basic usage of the BrowserComponent:

Form hi = new Form("Browser", new BorderLayout());
BrowserComponent browser = new BrowserComponent();
browser.setURL("https://www.codenameone.com/");
hi.add(BorderLayout.CENTER, browser);

Debugging on Android

You can use Chrome's remote debugging features to debug the contents of a BrowserComponent. On Android 4.4 (KitKat) and higher, you will need to define the "android.webContentsDebuggingEnabled" display property in order for this to work. You can define this inside your app's init() method:

java Display.getInstance().setProperty("android.webContentsDebuggingEnabled", "true");

  • Field Details

    • BROWSER_PROPERTY_FOLLOW_TARGET_BLANK

      public static final String BROWSER_PROPERTY_FOLLOW_TARGET_BLANK
      Browser property key to control whether links with target="_blank" or target="_new" should be followed in the current browser view. Defaults to true.
      See Also:
    • onStart

      public static final String onStart
      String constant for web event listener com.codename1.ui.events.ActionListener)
      See Also:
    • onLoad

      public static final String onLoad
      String constant for web event listener com.codename1.ui.events.ActionListener)
      See Also:
    • onError

      public static final String onError
      String constant for web event listener com.codename1.ui.events.ActionListener)
      See Also:
    • onMessage

      public static final String onMessage

      String constant for web event listener. Use this event types to register to receive messages in a cross-domain-safe way from the web page. To send a message from the webpage, the page should include a function like:

      `function postToCN1(msg) {
      if (window.cn1PostMessage) {
      // Case 1: Running inside native app in a WebView
      window.cn1PostMessage(msg);` else {
      // Case 2: Running inside a Javascript app in an iframe
      window.parent.postMessage(msg, '*');
      }
        }
      }
      

      Receiving a message:

      `myBrowserComponent.addWebEventListener(BrowserComponent.onMessage, e->{
      CN.callSerially(()->{
      Log.p("Message: "+e.getSource());
      Dialog.show("Here", (String)e.getSource(), "OK", null);`);
        });
      }
      
      See Also:
  • Constructor Details

    • BrowserComponent

      public BrowserComponent()
      This constructor will work as expected when a browser component is supported, see isNativeBrowserSupported()
  • Method Details

    • isNativeBrowserSupported

      public static boolean isNativeBrowserSupported()

      Returns true if the platform supports embedding a native browser component

      Returns

      true if native browsing is supported

    • injectParameters

      public static String injectParameters(String jsExpression, Object... params)

      Injects parameters into a Javascript string expression. This will quote strings properly. The expression should include placeholders for each parameter of the form ${0}, ${1}, etc..

      Parameters
      • jsExpression: The javascript expression with placeholders to inject parameters.

      • params

      Returns

      The expression with placeholders replaced by parameters.

    • createDataURI

      public static String createDataURI(byte[] data, String mime)

      This method creates a data URI which allows developers creating HTML for local use to embed local images into the HTML by appending them as a URI. E.g. instead of referencing a file or URL just load the image data and place the contents of this string into the src attribute.

      This is the easiest way to get an HTML with local images to work on all mobile platforms.

      Parameters
      • data: data of an image

      • mime: the mime type of the image e.g. image/png

      Returns

      a data URL that can be placed into the img src attribute in HTML e.g. data:image/png;base64,encodedData

      Since

      6.0

    • isFireCallbacksOnEdt

      public boolean isFireCallbacksOnEdt()

      Checks if javascript callbacks are run on the EDT.

      Returns

      True if javascript callbacks are run on the EDT.

      Since

      5.0

      See also
      • #setFireCallbacksOnEdt(boolean)
    • setFireCallbacksOnEdt

      public void setFireCallbacksOnEdt(boolean edt)

      Sets whether javascript callbacks should be run on the EDT. Default is true.

      Parameters
      • edt: True if callbacks should be run on EDT. False if they should be run on the platform's main thread.
      Since

      5.0

    • captureScreenshot

      public AsyncResource<Image> captureScreenshot()

      Async method for capturing a screenshot of the browser content. Currently only supported in the simulator. Also, only displays the visible rectangle of the BrowserComponent, not the entire page.

      Returns

      AsyncResource resolving to an Image of the webview contents.

      Since

      7.0

    • getBrowserNavigationCallback

      public BrowserNavigationCallback getBrowserNavigationCallback()

      The browser navigation callback interface allows handling a case where a URL invocation can be delegated to Java code. This allows binding Java side functionality to JavaScript functionality in the same way PhoneGap/Cordova work

      Returns

      the callback interface

      Deprecated

      Call #fireBrowserNavigationCallbacks(java.lang.String) to determine whether navigation should occur for a particulr URL.

    • setBrowserNavigationCallback

      public void setBrowserNavigationCallback(BrowserNavigationCallback callback)

      Set the browser navigation callback which allows handling a case where a URL invocation can be delegated to Java code. This allows binding Java side functionality to JavaScript functionality in the same way PhoneGap/Cordova work

      Parameters
      • callback: the callback interface
      Deprecated

      Use invalid input: 'Instead'

    • addBrowserNavigationCallback

      public void addBrowserNavigationCallback(BrowserNavigationCallback callback)

      Adds a navigation callback.

      Parameters
      • callback: The callback to call before navigating to a URL.
    • removeBrowserNavigationCallback

      public void removeBrowserNavigationCallback(BrowserNavigationCallback callback)

      Removes a navigation callback.

      Parameters
      • callback: The callback to call before navigating to a URL.
    • deinitialize

      protected void deinitialize()
      Description copied from class: Component
      Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.
      Overrides:
      deinitialize in class Component
    • postMessage

      public void postMessage(String message, String targetOrigin)

      Calls the postMessage() method on the webpage's window object.

      This is useful mainly for the Javascript port so that you don't have to worry about cross-domain issues, as postMessage() is supported cross-domain.

      To receive a message, the web page should register a "message" event listener, just as it would to receive messages from other windows in the browser. See MDN docs for postMessage() for more information.

      Parameters
      • message: The message to send.

      • targetOrigin: The target origin of the message. E.g. http://example.com:1234

      Since

      7.0

    • fireBrowserNavigationCallbacks

      public boolean fireBrowserNavigationCallbacks(String url)

      Fires all of the registered browser navigation callbacks against the provided URL.

      Parameters
      • url: The URL to fire the navigation callbacks against.
      Returns

      True if all of the callbacks say that they can browse. False otherwise.

    • waitForReady

      public void waitForReady()
      Uses invokeAndBlock to wait until the BrowserComponent is ready. The browser component is considered to be ready once the onLoad event has been fired for the first page.
    • ready

      Registers a callback to be run when the BrowserComponent is "ready". The browser component is considered to be ready once the onLoad event has been fired on the first page. If this method is called after the browser component is already "ready", then the callback will be executed immediately. Otherwise it will be called in the first onLoad event.

      Parameters
      • onReady: Callback to be executed when the browser component is ready.
      Returns

      Self for chaining.

      Since

      7.0

      See also
      • #waitForReady()
    • ready

      Returns a promise that will complete when the browser component is "ready". It is considered to be ready once it has received the start or load event from at least one page. Default timeout is 5000ms.

      Returns

      AsyncResouce that will complete when the browser component is ready.

      Since

      7.0

    • ready

      public AsyncResource<BrowserComponent> ready(int timeout)

      Returns a promise that will complete when the browser component is "ready". It is considered to be ready once it has received the start or load event from at least one page.

      Parameters
      • timeout: Timeout in milliseconds to wait.
      Returns

      AsyncResouce that will complete when the browser component is ready.

      Since

      7.0

    • setProperty

      public void setProperty(String key, Object value)

      This method allows customizing the properties of a web view in various ways including platform specific settings. When a property isn't supported by a specific platform it is just ignored.

      Parameters
      • key: see the documentation with the CodenameOne Implementation for further details

      • value: see the documentation with the CodenameOne Implementation for further details

    • getTitle

      public String getTitle()

      The page title

      Returns

      the title

    • getURL

      public String getURL()

      The page URL

      Returns

      the URL

    • setURL

      public void setURL(String url)

      Sets the page URL, jar: URL's must be supported by the implementation

      Parameters
      • url: the URL
    • setURL

      public void setURL(URL url)

      Sets the page URL.

      Parameters
      • url: The URL to the page to display.
    • setURL

      public void setURL(URI uri)

      Sets the page URL.

      Parameters
      • uri: URI to the page to display.
    • setURL

      public void setURL(String url, Map<String,String> headers)

      Sets the page URL, jar: URL's must be supported by the implementation. Notice this API isn't supported in all platforms see #isURLWithCustomHeadersSupported()

      Parameters
      • url: the URL

      • headers: headers to push into the request for the url

    • isURLWithCustomHeadersSupported

      public boolean isURLWithCustomHeadersSupported()

      Returns true if the method java.util.Map) is supported

      Returns

      false by default

    • setURLHierarchy

      public void setURLHierarchy(String url) throws IOException

      Sets the page URL while respecting the hierarchy of the html

      Parameters
      • url: the URL
      Throws:
      IOException
    • reload

      public void reload()
      Reload the current page
    • hasBack

      public boolean hasBack()

      Indicates whether back is currently available

      Returns

      true if back should work

    • hasForward

      public boolean hasForward()

      Indicates whether forward is currently available

      Returns

      true if forward should work

    • back

      public void back()
      Navigates back in the history
    • forward

      public void forward()
      Navigates forward in the history
    • clearHistory

      public void clearHistory()
      Clears navigation history
    • isPinchToZoomEnabled

      public boolean isPinchToZoomEnabled()

      This method is unreliable and is only here for consistency with setPinchToZoomEnabled, it will not return whether the platform supports pinch since this is very hard to detect properly.

      Returns

      the last value for setPinchToZoomEnabled

    • setPinchToZoomEnabled

      public void setPinchToZoomEnabled(boolean e)

      Some platforms require that you enable pinch to zoom explicitly. This method has no effect if pinch to zoom isn't supported by the platform

      Parameters
      • e: true to enable pinch to zoom, false to disable it
    • isNativeScrollingEnabled

      public boolean isNativeScrollingEnabled()

      This method is unreliable and is only here for consistency with setNativeScrollingEnabled.

      Returns

      the last value for setNativeScrollingEnabled

    • setNativeScrollingEnabled

      public void setNativeScrollingEnabled(boolean b)

      This flag allows disabling the native browser scrolling on platforms that support it

      Parameters
      • b: true to enable native scrolling, notice that non-native scrolling might be problematic
    • setPage

      public void setPage(String html, String baseUrl)

      Shows the given HTML in the native viewer

      Parameters
      • html: HTML web page

      • baseUrl: base URL to associate with the HTML

    • addWebEventListener

      public void addWebEventListener(String type, ActionListener listener)

      Adds a listener to the given event type name, event type names are platform specific but some must be fired for all platforms and will invoke the action listener when the appropriate event loads

      Parameters
      • type: platform specific but must support: onStart, onLoad, onError

      • listener: callback for the event

    • removeWebEventListener

      public void removeWebEventListener(String type, ActionListener listener)

      Removes the listener, see addWebEventListener for details

      Parameters
      • type: see addWebEventListener for details

      • listener: see addWebEventListener for details

    • stop

      public void stop()
      Cancel the loading of the current page
    • destroy

      public void destroy()
      Release native resources of this Browser Component
    • fireWebEvent

      public void fireWebEvent(String type, ActionEvent ev)

      Used internally by the implementation to fire an event from the native browser widget

      Parameters
      • type: the type of the event

      • ev: the event

    • execute

      public void execute(String javaScript)

      Executes the given JavaScript string within the current context

      Parameters
      • javaScript: the JavaScript string
    • execute

      public void execute(String js, Object[] params)

      Executes given javascript string within current context.

      Parameters
      • js: The javascript to execute.

      • params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. See java.lang.Object...) for more information about injected parameters. by parameters.

    • executeAndReturnString

      public String executeAndReturnString(String javaScript)

      Executes the given JavaScript and returns a result string from the underlying platform where applicable.

      Note: Some platforms use Display#invokeAndBlock(java.lang.Runnable) inside this method which is very costly. Try to avoid this synchronous method, and prefer to use one of the asynchronous versions. E.g. com.codename1.util.SuccessCallback)

      Parameters
      • javaScript: the JavaScript code to execute
      Returns

      the string returned from the Javascript call

    • executeAndReturnString

      public String executeAndReturnString(String javaScript, Object[] params)

      Executes the given javascript and returns the result string from the underlying platform.

      Note: Some platforms use Display#invokeAndBlock(java.lang.Runnable) inside this method which is very costly. Try to avoid this synchronous method, and prefer to use one of the asynchronous versions. E.g. com.codename1.util.SuccessCallback)

      Parameters
      • javaScript: The javascript to execute.

      • params: Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. See java.lang.Object...) for more information about injected parameters.

      Returns

      The result as a string.

      Since

      5.0

    • createJSProxy

      public BrowserComponent.JSProxy createJSProxy(String javascriptExpression)
      Creates a proxy for a Javascript object that makes it easier to call methods, retrieve, and manipulate properties on the object.
    • execute

      public void execute(String js, SuccessCallback<BrowserComponent.JSRef> callback)

      Asynchronously executes the provided javascript expression. The expression may provide a callback which you can call inside the expression directly.

      Example

      Getting the window object.

      `bc.execute("callback.onSuccess(window)", value -> {
      System.out.println("value="+value+"; type="+value.getJSType());
      // value=[object Window]; type=OBJECT`);
      }
      

      Getting an Integer

      `bc.execute("callback.onSuccess(1+2)", value -> {
      System.out.println("value="+value.getInt()+"; type="+value.getJSType());
      // value=3; type=NUMBER`);
      }
      

      Getting a String

      `bc.execute("callback.onSuccess('hello world')",value -> {
      System.out.println("value="+value+"; type="+value.getJSType());
      // value=hello world; type=STRING`
      );
      }
      

      After a Javascript Timeout

      Since this call is asynchronous, the javascript code can wait to call the callback to any time in the future - e.g. after a timeout, after an ajax response, in some event handler, etc.. The CN1 UI will not be blocked, the provided callback will be called at the appropriate time on the EDT.

      `bc.execute("setTimeout(function(){callback.onSuccess('hello world')`, 1500)",
      value -> {
      System.out.println("value="+value+"; type="+value.getJSType());
      // value=hello world; type=STRING
      }
      );
      }
      

      NOTE: The callback can only be called once, so you shouldn't use this method to register a callback with an event listener that will be called repeatedly. If you want to register a Java callback with a Javascript event, you should use the com.codename1.util.Callback) method instead.

      Parameters
      • js: The javascript expression. If you want to receive any result from this expression, the expression itself must include a call to callback.onSuccess(value).

      • callback: The callback. You should call this directly from Javascript. You can call either callback.onSuccess(value) or callback.onError(message,code).

    • execute

      public void execute(int timeout, String js, SuccessCallback<BrowserComponent.JSRef> callback)

      Execute javascript with a timeout. If timeout is reached before callback is run, then the callback's onError method is run (if callback is a Callback). If callback isn't a Callback (i.e. has no onError(), then this will log an error, and call the onSucess method with a null arg.

      Parameters
      • js: The javascript to execute

      • timeout: The timeout in milliseconds.

      • callback: The callback

    • execute

      public void execute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)

      Executes Javascript expression.

      Parameters
      • timeout: The timeout in ms

      • js: The javascript expression to execute.

      • params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. See java.lang.Object...) for more information about injected parameters. by parameters.

      • callback: Callback to call when complete.

    • execute

      public void execute(String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)

      Executes Javascript expression.

      Parameters
      • js: The javascript expression to execute.

      • params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. See java.lang.Object...) for more information about injected parameters. by parameters.

      • callback: Callback to call when complete.

    • addJSCallback

      public void addJSCallback(String installJs, SuccessCallback<BrowserComponent.JSRef> callback)

      Registers a Java method as a callback in javascript. The callback argument can be referenced inside the javascript expression so that it can be fired when certain events occur.

      Examples

      Register a Callback to be called whenever a button is clicked

      `bc.addJSCallback("someButton.addEventListener('click', function(){callback.onSuccess('hello world')`)", new Callback() {
      public void onSucess(JSRef value) {
      System.out.println("Received click: "+value);
      }
      });
      }
      
      Parameters
      • installJs

      • callback

    • addJSCallback

      public void addJSCallback(String installJs, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)

      Registers Java method as a callback in Javascript. The callback argument can be referenced inside the javascript expression so that it can be fired when certain events occur.

      Parameters
      • installJs: The javascript expression. to run.

      • params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. See java.lang.Object...) for more information about injected parameters. by parameters.

      • callback: The callback to call on completion.

    • removeJSCallback

      public void removeJSCallback(Callback<BrowserComponent.JSRef> callback)

      Removes a JS callback that was added via the com.codename1.util.SuccessCallback) method.

      Note: This won't unregister any callbacks from the Javascript environment. You'll need to perform your own additional cleanup in Javascript if this callback is registered in any event handlers.

      Parameters
      • callback: The callback to remove.
    • removeJSCallback

      public void removeJSCallback(SuccessCallback<BrowserComponent.JSRef> callback)
    • executeAndWait

      public BrowserComponent.JSRef executeAndWait(int timeout, String js, Object... params)

      This uses invokeAndBlock to wait for the result of the given javascript expression.

      Parameters
      • timeout: Timeout in milliseconds.

      • js: The javascript expression.

      • params: Parameters to inject in the expression. See java.lang.Object...) for details.

      Returns

      The result.

    • executeAndWait

      public BrowserComponent.JSRef executeAndWait(String js, Object... params)

      This uses invokeAndBlock to wait for the result of the given javascript expression.

      Parameters
      • js: The javascript expression.

      • params: Parameters to inject in the expression. See java.lang.Object...) for details.

      Returns

      The result.

    • executeAndWait

      public BrowserComponent.JSRef executeAndWait(String js)

      This uses invokeAndBlock to wait for the result of the given javascript expression. It is extremely important that the js expression calls either callback.onSuccess(value) or literalcallback.onError(message, code) at some point, or this method will never return.

      #executeAndWait(java.lang.String) vs #executeAndReturnString(java.lang.String)

      #executeAndReturnString(java.lang.String) is also blocking, but it uses javascript eval to return the value of the expression. Therefore it can't return the result of any asynchronous operations.

      #executeAndWait(java.lang.String) is built directly on top of com.codename1.util.SuccessCallback) which is fully asynchronous, and allows you to specify where and when you call the callback within the javascript code. This means that you must explicitly call either callback.onSuccess(value) or literalcallback.onError(message, code) at some point in the Javascript expression - or the method will block indefinitely.

      Parameters
      • js: The javascript expression to execute. You must call callback.onSuccess(value) with the result that you want to have returned.
      Returns

      The result that is returned from javascript when it calls callback.onSuccess(value)

    • executeAndWait

      public BrowserComponent.JSRef executeAndWait(int timeout, String js)

      This uses invokeAndBlock to wait for the result of the given javascript expression. It is extremely important that the js expression calls either callback.onSuccess(value) or literalcallback.onError(message, code) at some point, or this method will never return.

      #executeAndWait(java.lang.String) vs #executeAndReturnString(java.lang.String)

      #executeAndReturnString(java.lang.String) is also blocking, but it uses javascript eval to return the value of the expression. Therefore it can't return the result of any asynchronous operations.

      #executeAndWait(java.lang.String) is built directly on top of com.codename1.util.SuccessCallback) which is fully asynchronous, and allows you to specify where and when you call the callback within the javascript code. This means that you must explicitly call either callback.onSuccess(value) or literalcallback.onError(message, code) at some point in the Javascript expression - or the method will block indefinitely.

      Parameters
      • timeout: Timeout in ms

      • js: The javascript expression to execute. You must call callback.onSuccess(value) with the result that you want to have returned.

      Returns

      The result that is returned from javascript when it calls callback.onSuccess(value)

    • exposeInJavaScript

      public void exposeInJavaScript(Object o, String name)

      Allows exposing the given object to JavaScript code so the JavaScript code can invoke methods and access fields on the given object. Notice that on RIM devices which don't support reflection this object must implement the propriatery Scriptable interface http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/script/Scriptable.html

      Parameters
      • o: the object to invoke, notice all public fields and methods would be exposed to JavaScript

      • name: the name to expose within JavaScript

      Deprecated
    • putClientProperty

      public void putClientProperty(String key, Object value)
      Description copied from class: Component

      Client properties allow the association of meta-data with a component, this is useful for some applications that construct GUI's on the fly and need to track the connection between the UI and the data. Setting the value to null will remove the client property from the component.

      Parameters
      • key: arbitrary key for the property

      • value: the value assigned to the given client property

      Overrides:
      putClientProperty in class Component
    • isDebugMode

      public boolean isDebugMode()

      Indicates if debug mode is set (might have no effect though)

      Returns

      true if debug mode was activated

    • setDebugMode

      public void setDebugMode(boolean mode)

      Toggles debug mode for the browser component which helps detect coding errors in the JavaScript bridge logic

      Parameters
      • mode: true to debug false otherwise, this might have no effect in some platforms