public class 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.JSType | Enum with the possible types for a JSRef object. |
class BrowserComponent.JSRef | A wrapper class for a Javascript value that is returned via the com.codename1.util.Callback) method. |
class BrowserComponent.JSExpression | A wrapper class for a literal javascript expression that can be passed as an arg in java.lang.Object[]). |
class BrowserComponent.JSProxy | A 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
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
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"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"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"com.codename1.ui.events.ActionListener)onLoad
public static final String onLoad = "onLoad"com.codename1.ui.events.ActionListener)onError
public static final String onError = "onError"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()Method details
isNativeBrowserSupported
public static boolean isNativeBrowserSupported()Returns
injectParameters
public static String injectParameters(String jsExpression, Object... params)Parameters
jsExpressionString- The javascript expression with placeholders to inject parameters.
paramsObject...- Not documented.
Returns
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
databyte[]- data of an image
mimeString- the mime type of the image e.g. image/png
Returns
isFireCallbacksOnEdt
public boolean isFireCallbacksOnEdt()Returns
See also
setFireCallbacksOnEdt
public void setFireCallbacksOnEdt(boolean edt)Parameters
edtboolean- 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()Returns
deinitialize
protected void deinitialize()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
messageString- The message to send.
targetOriginString- The target origin of the message. E.g. http://example.com:1234
waitForReady
public void waitForReady()ready
public BrowserComponent ready(SuccessCallback<BrowserComponent> onReady)Parameters
onReadySuccessCallback<BrowserComponent>- Callback to be executed when the browser component is ready.
Returns
See also
ready
public AsyncResource<BrowserComponent> ready()Returns
ready
public AsyncResource<BrowserComponent> ready(int timeout)Parameters
timeoutint- Timeout in milliseconds to wait.
Returns
setProperty
public void setProperty(String key, Object value)Parameters
keyString- see the documentation with the CodenameOne Implementation for further details
valueObject- see the documentation with the CodenameOne Implementation for further details
getTitle
public String getTitle()Returns
getURL
public String getURL()Returns
setURL
public void setURL(String url)Parameters
urlString- the URL
setURL
public void setURL(URL url)Parameters
urlURL- The URL to the page to display.
setURL
public void setURL(URI uri)Parameters
uriURI- URI to the page to display.
setURL
public void setURL(String url, Map<String, String> headers)#isURLWithCustomHeadersSupported()Parameters
urlString- the URL
headersMap<String, String>- headers to push into the request for the url
isURLWithCustomHeadersSupported
public boolean isURLWithCustomHeadersSupported()java.util.Map) is supportedReturns
setURLHierarchy
public void setURLHierarchy(String url)
throws IOExceptionParameters
urlString- the URL
Throws
reload
public void reload()hasBack
public boolean hasBack()Returns
hasForward
public boolean hasForward()Returns
back
public void back()forward
public void forward()clearHistory
public void clearHistory()isPinchToZoomEnabled
public boolean isPinchToZoomEnabled()Returns
setPinchToZoomEnabled
public void setPinchToZoomEnabled(boolean e)Parameters
eboolean- true to enable pinch to zoom, false to disable it
isNativeScrollingEnabled
public boolean isNativeScrollingEnabled()Returns
setNativeScrollingEnabled
public void setNativeScrollingEnabled(boolean b)Parameters
bboolean- true to enable native scrolling, notice that non-native scrolling might be problematic
setPage
public void setPage(String html, String baseUrl)Parameters
htmlString- HTML web page
baseUrlString- base URL to associate with the HTML
addWebEventListener
public void addWebEventListener(String type, ActionListener listener)Parameters
typeString- platform specific but must support: onStart, onLoad, onError
listenerActionListener- callback for the event
removeWebEventListener
public void removeWebEventListener(String type, ActionListener listener)Parameters
typeString- see addWebEventListener for details
listenerActionListener- see addWebEventListener for details
stop
public void stop()destroy
public void destroy()fireWebEvent
public void fireWebEvent(String type, ActionEvent ev)Parameters
typeString- the type of the event
evActionEvent- the event
execute
public void execute(String javaScript)Parameters
javaScriptString- the JavaScript string
execute
public void execute(String js, Object[] params)Parameters
jsString- The javascript to execute.
paramsObject[]- 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
javaScriptString- the JavaScript code to execute
Returns
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
javaScriptString- The javascript to execute.
paramsObject[]- 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
createJSProxy
public BrowserComponent.JSProxy createJSProxy(String javascriptExpression)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
jsString- The javascript expression. If you want to receive any result from this expression, the expression itself must include a call to callback.onSuccess(value).
callbackSuccessCallback<BrowserComponent.JSRef>- The callback. You should call this directly from Javascript. You can call either
callback.onSuccess(value)orcallback.onError(message,code).
execute
public void execute(int timeout, String js, SuccessCallback<BrowserComponent.JSRef> callback)Parameters
timeoutint- The timeout in milliseconds.
jsString- The javascript to execute
callbackSuccessCallback<BrowserComponent.JSRef>- The callback
execute
public void execute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)Parameters
timeoutint- The timeout in ms
jsString- The javascript expression to execute.
paramsObject[]- 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. callbackSuccessCallback<BrowserComponent.JSRef>- Callback to call when complete.
execute
public void execute(String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)Parameters
jsString- The javascript expression to execute.
paramsObject[]- 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. callbackSuccessCallback<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)Parameters
installJsString- The javascript expression. to run.
paramsObject[]- 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. callbackSuccessCallback<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
callbackCallback<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)Parameters
timeoutint- Timeout in milliseconds.
jsString- The javascript expression.
paramsObject...- Parameters to inject in the expression. See
java.lang.Object...)for details.
Returns
executeAndWait
public BrowserComponent.JSRef executeAndWait(String js, Object... params)Parameters
jsString- The javascript expression.
paramsObject...- Parameters to inject in the expression. See
java.lang.Object...)for details.
Returns
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
jsString- The javascript expression to execute. You must call
callback.onSuccess(value)with the result that you want to have returned.
Returns
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
timeoutint- Timeout in ms
jsString- The javascript expression to execute. You must call
callback.onSuccess(value)with the result that you want to have returned.
Returns
callback.onSuccess(value)exposeInJavaScript
public void exposeInJavaScript(Object o, String name)Parameters
oObject- the object to invoke, notice all public fields and methods would be exposed to JavaScript
nameString- 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.FALSEpreserves 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
keyString- the client property key
valueObject- the client property value
isDebugMode
public boolean isDebugMode()Returns
setDebugMode
public void setDebugMode(boolean mode)Parameters
modeboolean- true to debug false otherwise, this might have no effect in some platforms