public class BrowserComponent

  1. Object
  2. Component
  3. Container
  4. BrowserComponent

ImplementsAnimation, Editable, Iterable<Component>, StyleListener

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 Display.getInstance().setProperty("WebLoadingHidden", "true"); 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");

Nested types

enum BrowserComponent.JSTypeEnum with the possible types for a JSRef object.
class BrowserComponent.JSRefA wrapper class for a Javascript value that is returned via the com.codename1.util.Callback) method.
class BrowserComponent.JSExpressionA wrapper class for a literal javascript expression that can be passed as an arg in java.lang.Object[]).
class BrowserComponent.JSProxyA thin wrapper around a Javascript variable that makes it easier to call methods on that variable.

Fields

public static final String BROWSER_PROPERTY_FOLLOW_TARGET_BLANK = "BrowserComponent.followTargetBlank"Browser property key to control whether links with target="_blank" or target="_new" should be followed in the current browser view.
public static final String BROWSER_PROPERTY_INTERFACE_STYLE = "BrowserComponent.interfaceStyle"Browser property key to pin the appearance (light/dark) of the native web widget regardless of the device-wide setting.
public static final String onStart = "onStart"String constant for web event listener com.codename1.ui.events.ActionListener)
public static final String onLoad = "onLoad"String constant for web event listener com.codename1.ui.events.ActionListener)
public static final String onError = "onError"String constant for web event listener com.codename1.ui.events.ActionListener)
public static final String onMessage = "onMessage"String constant for web event listener.

Constructors

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

Methods

public static boolean isNativeBrowserSupported()Returns true if the platform supports embedding a native browser component
public static String injectParameters(String jsExpression, Object... params)Injects parameters into a Javascript string expression.
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.
public boolean isFireCallbacksOnEdt()Checks if javascript callbacks are run on the EDT.
public void setFireCallbacksOnEdt(boolean edt)Sets whether javascript callbacks should be run on the EDT.
public AsyncResource<Image> captureScreenshot()Async method for capturing a screenshot of the browser content.
public BrowserNavigationCallback getBrowserNavigationCallback()Deprecated The browser navigation callback interface allows handling a case where a URL invocation can be delegated to Java code.
public void setBrowserNavigationCallback(BrowserNavigationCallback callback)Deprecated Set the browser navigation callback which allows handling a case where a URL invocation can be delegated to Java code.
public void addBrowserNavigationCallback(BrowserNavigationCallback callback)Adds a navigation callback.
public void removeBrowserNavigationCallback(BrowserNavigationCallback callback)Removes a navigation callback.
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
public void postMessage(String message, String targetOrigin)Calls the postMessage() method on the webpage’s window object.
public boolean fireBrowserNavigationCallbacks(String url)Fires all of the registered browser navigation callbacks against the provided URL.
public void waitForReady()Uses invokeAndBlock to wait until the BrowserComponent is ready.
public BrowserComponent ready(SuccessCallback<BrowserComponent> onReady)Registers a callback to be run when the BrowserComponent is “ready”.
public AsyncResource<BrowserComponent> ready()Returns a promise that will complete when the browser component is “ready”.
public AsyncResource<BrowserComponent> ready(int timeout)Returns a promise that will complete when the browser component is “ready”.
public void setProperty(String key, Object value)This method allows customizing the properties of a web view in various ways including platform specific settings.
public String getTitle()The page title
public String getURL()The page URL
public void setURL(String url)Sets the page URL, jar: URL’s must be supported by the implementation
public void setURL(URL url)Sets the page URL.
public void setURL(URI uri)Sets the page URL.
public void setURL(String url, Map<String, String> headers)Sets the page URL, jar: URL’s must be supported by the implementation.
public boolean isURLWithCustomHeadersSupported()Returns true if the method java.util.Map) is supported
public void setURLHierarchy(String url) throws IOExceptionSets the page URL while respecting the hierarchy of the html
public void reload()Reload the current page
public boolean hasBack()Indicates whether back is currently available
public boolean hasForward()Indicates whether forward is currently available
public void back()Navigates back in the history
public void forward()Navigates forward in the history
public void clearHistory()Clears navigation history
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.
public void setPinchToZoomEnabled(boolean e)Some platforms require that you enable pinch to zoom explicitly.
public boolean isNativeScrollingEnabled()This method is unreliable and is only here for consistency with setNativeScrollingEnabled.
public void setNativeScrollingEnabled(boolean b)This flag allows disabling the native browser scrolling on platforms that support it
public void setPage(String html, String baseUrl)Shows the given HTML in the native viewer
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
public void removeWebEventListener(String type, ActionListener listener)Removes the listener, see addWebEventListener for details
public void stop()Cancel the loading of the current page
public void destroy()Release native resources of this Browser Component
public void fireWebEvent(String type, ActionEvent ev)Used internally by the implementation to fire an event from the native browser widget
public void execute(String javaScript)Executes the given JavaScript string within the current context
public void execute(String js, Object[] params)Executes given javascript string within current context.
public String executeAndReturnString(String javaScript)Executes the given JavaScript and returns a result string from the underlying platform where applicable.
public String executeAndReturnString(String javaScript, Object[] params)Executes the given javascript and returns the result string from the underlying platform.
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.
public void execute(String js, SuccessCallback<BrowserComponent.JSRef> callback)Asynchronously executes the provided javascript expression.
public void execute(int timeout, String js, SuccessCallback<BrowserComponent.JSRef> callback)Execute javascript with a timeout.
public void execute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)Executes Javascript expression.
public void execute(String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)Executes Javascript expression.
public void addJSCallback(String installJs, SuccessCallback<BrowserComponent.JSRef> callback)Registers a Java method as a callback in javascript.
public void addJSCallback(String installJs, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)Registers Java method as a callback in Javascript.
public void removeJSCallback(Callback<BrowserComponent.JSRef> callback)Removes a JS callback that was added via the com.codename1.util.SuccessCallback) method.
public void removeJSCallback(SuccessCallback<BrowserComponent.JSRef> callback)
public BrowserComponent.JSRef executeAndWait(int timeout, String js, Object... params)This uses invokeAndBlock to wait for the result of the given javascript expression.
public BrowserComponent.JSRef executeAndWait(String js, Object... params)This uses invokeAndBlock to wait for the result of the given javascript expression.
public BrowserComponent.JSRef executeAndWait(String js)This uses invokeAndBlock to wait for the result of the given javascript expression.
public BrowserComponent.JSRef executeAndWait(int timeout, String js)This uses invokeAndBlock to wait for the result of the given javascript expression.
public void exposeInJavaScript(Object o, String name)Deprecated Allows exposing the given object to JavaScript code so the JavaScript code can invoke methods and access fields on the given object.
public void putClientProperty(String key, Object value)Sets a client property on this component.
public boolean isDebugMode()Indicates if debug mode is set (might have no effect though)
public void setDebugMode(boolean mode)Toggles debug mode for the browser component which helps detect coding errors in the JavaScript bridge logic

Inherited fields

Inherited methods

From Container

encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, keyPressed, keyReleased, getLayout, setLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, calcPreferredSize, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Field details

BROWSER_PROPERTY_FOLLOW_TARGET_BLANK

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

BROWSER_PROPERTY_INTERFACE_STYLE

public static final String BROWSER_PROPERTY_INTERFACE_STYLE = "BrowserComponent.interfaceStyle"
Browser property key to pin the appearance (light/dark) of the native web widget regardless of the device-wide setting. This drives the prefers-color-scheme CSS media query and the user-agent rendering of form controls and default backgrounds inside the page. Accepted values are "light", "dark" and "auto" (follow the device, the default). Use it via browser.setProperty(BrowserComponent.BROWSER_PROPERTY_INTERFACE_STYLE, "light"). Currently honored on iOS (WKWebView); platforms that do not support pinning the web-view appearance ignore it.

onStart

public static final String onStart = "onStart"
String constant for web event listener com.codename1.ui.events.ActionListener)

onLoad

public static final String onLoad = "onLoad"
String constant for web event listener com.codename1.ui.events.ActionListener)

onError

public static final String onError = "onError"
String constant for web event listener com.codename1.ui.events.ActionListener)

onMessage

public static final String onMessage = "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);`);
  });
}

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 String
The javascript expression with placeholders to inject parameters.
params Object...
Not documented.

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 byte[]
data of an image
mime String
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

isFireCallbacksOnEdt

public boolean isFireCallbacksOnEdt()
Checks if javascript callbacks are run on the EDT.

Returns

True if javascript callbacks are run on the EDT.

setFireCallbacksOnEdt

public void setFireCallbacksOnEdt(boolean edt)
Sets whether javascript callbacks should be run on the EDT. Default is true.

Parameters

edt boolean
True if callbacks should be run on EDT. False if they should be run on the platform’s main thread.

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.

getBrowserNavigationCallback

public BrowserNavigationCallback getBrowserNavigationCallback()
Deprecated. Call #fireBrowserNavigationCallbacks(java.lang.String) to determine whether navigation should occur for a particulr URL.
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

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 BrowserNavigationCallback
the callback interface

addBrowserNavigationCallback

public void addBrowserNavigationCallback(BrowserNavigationCallback callback)
Adds a navigation callback.

Parameters

callback BrowserNavigationCallback
The callback to call before navigating to a URL.

removeBrowserNavigationCallback

public void removeBrowserNavigationCallback(BrowserNavigationCallback callback)
Removes a navigation callback.

Parameters

callback BrowserNavigationCallback
The callback to call before navigating to a URL.

deinitialize

protected void deinitialize()
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.

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 String
The message to send.
targetOrigin String
The target origin of the message. E.g. http://example.com:1234

fireBrowserNavigationCallbacks

public boolean fireBrowserNavigationCallbacks(String url)
Fires all of the registered browser navigation callbacks against the provided URL.

Parameters

url String
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

public BrowserComponent ready(SuccessCallback<BrowserComponent> onReady)
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 SuccessCallback<BrowserComponent>
Callback to be executed when the browser component is ready.

Returns

Self for chaining.

ready

public AsyncResource<BrowserComponent> 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.

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 int
Timeout in milliseconds to wait.

Returns

AsyncResouce that will complete when the browser component is ready.

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 String
see the documentation with the CodenameOne Implementation for further details
value Object
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 String
the URL

setURL

public void setURL(URL url)
Sets the page URL.

Parameters

url URL
The URL to the page to display.

setURL

public void setURL(URI uri)
Sets the page URL.

Parameters

uri 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 String
the URL
headers Map<String, String>
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 String
the URL

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 boolean
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 boolean
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 String
HTML web page
baseUrl String
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 String
platform specific but must support: onStart, onLoad, onError
listener ActionListener
callback for the event

removeWebEventListener

public void removeWebEventListener(String type, ActionListener listener)
Removes the listener, see addWebEventListener for details

Parameters

type String
see addWebEventListener for details
listener ActionListener
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 String
the type of the event
ev ActionEvent
the event

execute

public void execute(String javaScript)
Executes the given JavaScript string within the current context

Parameters

javaScript String
the JavaScript string

execute

public void execute(String js, Object[] params)
Executes given javascript string within current context.

Parameters

js String
The javascript to execute.
params Object[]
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 String
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 String
The javascript to execute.
params Object[]
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.

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 String
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 SuccessCallback<BrowserComponent.JSRef>
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

timeout int
The timeout in milliseconds.
js String
The javascript to execute
callback SuccessCallback<BrowserComponent.JSRef>
The callback

execute

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

Parameters

timeout int
The timeout in ms
js String
The javascript expression to execute.
params Object[]
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 SuccessCallback<BrowserComponent.JSRef>
Callback to call when complete.

execute

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

Parameters

js String
The javascript expression to execute.
params Object[]
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 SuccessCallback<BrowserComponent.JSRef>
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);
}
});
}

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 String
The javascript expression. to run.
params Object[]
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 SuccessCallback<BrowserComponent.JSRef>
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 Callback<BrowserComponent.JSRef>
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 int
Timeout in milliseconds.
js String
The javascript expression.
params Object...
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 String
The javascript expression.
params Object...
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 String
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 int
Timeout in ms
js String
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)
Deprecated. this doesn’t work in most platforms see issue 459 for details, use the setBrowserNavigationCallback method instead
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 Object
the object to invoke, notice all public fields and methods would be exposed to JavaScript
name String
the name to expose within JavaScript

putClientProperty

public void putClientProperty(String key, Object value)

Sets a client property on this component. BrowserComponent supports several special client properties that control platform-specific behavior.

HTML5/JavaScript Port Client Properties

  • HTML5Peer.removeOnDeinitialize (Boolean): Controls whether the underlying iframe is removed from the DOM when the component is deinitialized.

    When a Dialog is shown, the parent Form is deinitialized, which normally causes BrowserComponent’s iframe to be removed from the DOM. When the Dialog is dismissed, the Form is re-shown but the iframe must be recreated from scratch, losing all JavaScript state (editor content, event listeners, etc.).

    Setting this to Boolean.FALSE preserves the iframe in the DOM across deinitialization cycles, which is essential for:

    • WebRTC connections that break when removed from DOM
    • Editors and interactive components that need to preserve state
    • Any app that shows dialogs over a BrowserComponent

    Example:

    BrowserComponent browser = new BrowserComponent();
    browser.putClientProperty("HTML5Peer.removeOnDeinitialize", Boolean.FALSE);
    
  • BrowserComponent.firebug (Boolean): Enables debug mode with Firebug console integration (development only).

Parameters

key String
the client property key
value Object
the client property value

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 boolean
true to debug false otherwise, this might have no effect in some platforms