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
:
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:
Display.getInstance().setProperty("android.webContentsDebuggingEnabled", "true");
Modifier and Type | Class and Description |
---|---|
static class |
BrowserComponent.JSExpression
A wrapper class for a literal javascript expression that can be passed as an
arg in
execute(java.lang.String, java.lang.Object[]) . |
class |
BrowserComponent.JSProxy
A thin wrapper around a Javascript variable that makes it easier to
call methods on that variable.
|
static class |
BrowserComponent.JSRef
A wrapper class for a Javascript value that is returned via the
#execute(java.lang.String, com.codename1.util.Callback)
method. |
static class |
BrowserComponent.JSType
Enum with the possible types for a
BrowserComponent.JSRef object. |
Modifier and Type | Field and Description |
---|---|
static String |
onError
String constant for web event listener
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener) |
static String |
onLoad
String constant for web event listener
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener) |
static String |
onMessage
String constant for web event listener.
|
static String |
onStart
String constant for web event listener
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener) |
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR
Constructor and Description |
---|
BrowserComponent()
This constructor will work as expected when a browser component is supported, see isNativeBrowserSupported()
|
Modifier and Type | Method and Description |
---|---|
void |
addBrowserNavigationCallback(BrowserNavigationCallback callback)
Adds a navigation callback.
|
void |
addJSCallback(String installJs,
Object[] params,
SuccessCallback<BrowserComponent.JSRef> callback)
Registers Java method as a callback in Javascript.
|
void |
addJSCallback(String installJs,
SuccessCallback<BrowserComponent.JSRef> callback)
Registers a Java method as a callback in javascript.
|
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
|
void |
back()
Navigates back in the history
|
AsyncResource<Image> |
captureScreenshot()
Async method for capturing a screenshot of the browser content.
|
void |
clearHistory()
Clears navigation history
|
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.
|
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.
|
protected void |
deinitialize()
Invoked to indicate that the component initialization is being reversed
since the component was detached from the container hierarchy.
|
void |
destroy()
Release native resources of this Browser Component
|
void |
execute(int timeout,
String js,
Object[] params,
SuccessCallback<BrowserComponent.JSRef> callback)
Executes Javascript expression.
|
void |
execute(int timeout,
String js,
SuccessCallback<BrowserComponent.JSRef> callback)
Execute javascript with a timeout.
|
void |
execute(String javaScript)
Executes the given JavaScript string within the current context
|
void |
execute(String js,
Object[] params)
Executes given javascript string within current context.
|
void |
execute(String js,
Object[] params,
SuccessCallback<BrowserComponent.JSRef> callback)
Executes Javascript expression.
|
void |
execute(String js,
SuccessCallback<BrowserComponent.JSRef> callback)
Asynchronously executes the provided javascript expression.
|
String |
executeAndReturnString(String javaScript)
Executes the given JavaScript and returns a result string from the underlying platform
where applicable.
|
String |
executeAndReturnString(String javaScript,
Object[] params)
Executes the given javascript and returns the result string from the underlying platform.
|
BrowserComponent.JSRef |
executeAndWait(int timeout,
String js)
This uses invokeAndBlock to wait for the result of the given javascript expression.
|
BrowserComponent.JSRef |
executeAndWait(int timeout,
String js,
Object... params)
This uses invokeAndBlock to wait for the result of the given javascript expression.
|
BrowserComponent.JSRef |
executeAndWait(String js)
This uses invokeAndBlock to wait for the result of the given javascript expression.
|
BrowserComponent.JSRef |
executeAndWait(String js,
Object... params)
This uses invokeAndBlock to wait for the result of the given javascript expression.
|
void |
exposeInJavaScript(Object o,
String name)
Deprecated.
this doesn't work in most platforms see issue 459 for details, use the setBrowserNavigationCallback
method instead
|
boolean |
fireBrowserNavigationCallbacks(String url)
Fires all of the registered browser navigation callbacks against the provided URL.
|
void |
fireWebEvent(String type,
ActionEvent ev)
Used internally by the implementation to fire an event from the native browser widget
|
void |
forward()
Navigates forward in the history
|
BrowserNavigationCallback |
getBrowserNavigationCallback()
Deprecated.
Call
fireBrowserNavigationCallbacks(java.lang.String) to determine whether navigation should occur for a particulr URL. |
String |
getTitle()
The page title
|
String |
getURL()
The page URL
|
boolean |
hasBack()
Indicates whether back is currently available
|
boolean |
hasForward()
Indicates whether forward is currently available
|
protected void |
initComponent()
Allows subclasses to bind functionality that relies on fully initialized and
"ready for action" component state
|
static String |
injectParameters(String jsExpression,
Object... params)
Injects parameters into a Javascript string expression.
|
boolean |
isDebugMode()
Indicates if debug mode is set (might have no effect though)
|
boolean |
isFireCallbacksOnEdt()
Checks if javascript callbacks are run on the EDT.
|
static boolean |
isNativeBrowserSupported()
Returns true if the platform supports embedding a native browser component
|
boolean |
isNativeScrollingEnabled()
This method is unreliable and is only here for consistency with setNativeScrollingEnabled.
|
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.
|
boolean |
isURLWithCustomHeadersSupported()
Returns true if the method
setURL(java.lang.String, java.util.Map) is supported |
void |
postMessage(String message,
String targetOrigin)
Calls the postMessage() method on the webpage's window object.
|
void |
putClientProperty(String key,
Object value)
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.
|
AsyncResource<BrowserComponent> |
ready()
Returns a promise that will complete when the browser component is "ready".
|
AsyncResource<BrowserComponent> |
ready(int timeout)
Returns a promise that will complete when the browser component is "ready".
|
BrowserComponent |
ready(SuccessCallback<BrowserComponent> onReady)
Registers a callback to be run when the BrowserComponent is "ready".
|
void |
reload()
Reload the current page
|
void |
removeBrowserNavigationCallback(BrowserNavigationCallback callback)
Removes a navigation callback.
|
void |
removeJSCallback(Callback<BrowserComponent.JSRef> callback)
Removes a JS callback that was added via the
addJSCallback(java.lang.String, com.codename1.util.SuccessCallback) method. |
void |
removeJSCallback(SuccessCallback<BrowserComponent.JSRef> callback) |
void |
removeWebEventListener(String type,
ActionListener listener)
Removes the listener, see addWebEventListener for details
|
void |
setBrowserNavigationCallback(BrowserNavigationCallback callback)
Deprecated.
Use {@link #addBrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback) Instead
|
void |
setDebugMode(boolean mode)
Toggles debug mode for the browser component which helps detect coding errors in the JavaScript
bridge logic
|
void |
setFireCallbacksOnEdt(boolean edt)
Sets whether javascript callbacks should be run on the EDT.
|
void |
setNativeScrollingEnabled(boolean b)
This flag allows disabling the native browser scrolling on platforms that support it
|
void |
setPage(String html,
String baseUrl)
Shows the given HTML in the native viewer
|
void |
setPinchToZoomEnabled(boolean e)
Some platforms require that you enable pinch to zoom explicitly.
|
void |
setProperty(String key,
Object value)
This method allows customizing the properties of a web view in various ways including platform specific settings.
|
void |
setURL(String url)
Sets the page URL, jar: URL's must be supported by the implementation
|
void |
setURL(String url,
Map<String,String> headers)
Sets the page URL, jar: URL's must be supported by the implementation.
|
void |
setURL(URI uri)
Sets the page URL.
|
void |
setURL(URL url)
Sets the page URL.
|
void |
setURLHierarchy(String url)
Sets the page URL while respecting the hierarchy of the html
|
void |
stop()
Cancel the loading of the current page
|
void |
waitForReady()
Uses invokeAndBlock to wait until the BrowserComponent is ready.
|
add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, keyPressed, keyReleased, layoutContainer, morph, morphAndWait, paint, paintBackground, paintBorderBackground, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndices
addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, bindProperty, blocksSideSwipe, calcScrollSize, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, paintBackgrounds, paintBorder, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, pointerReleased, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUnselectedStyle, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
public static final String onStart
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener)
public static final String onLoad
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener)
public static final String onError
addWebEventListener(java.lang.String, com.codename1.ui.events.ActionListener)
public static final String onMessage
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);
});
});
public BrowserComponent()
public void setFireCallbacksOnEdt(boolean edt)
edt
- True if callbacks should be run on EDT. False if they should be run on the platform's main thread.public boolean isFireCallbacksOnEdt()
setFireCallbacksOnEdt(boolean)
public void setBrowserNavigationCallback(BrowserNavigationCallback callback)
callback
- the callback interfacepublic AsyncResource<Image> captureScreenshot()
public BrowserNavigationCallback getBrowserNavigationCallback()
fireBrowserNavigationCallbacks(java.lang.String)
to determine whether navigation should occur for a particulr URL.public void addBrowserNavigationCallback(BrowserNavigationCallback callback)
callback
- The callback to call before navigating to a URL.public void removeBrowserNavigationCallback(BrowserNavigationCallback callback)
callback
- The callback to call before navigating to a URL.protected void initComponent()
Component
initComponent
in class Component
protected void deinitialize()
Component
deinitialize
in class Component
public void postMessage(String message, String targetOrigin)
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.
message
- The message to send.targetOrigin
- The target origin of the message. E.g. http://example.com:1234public boolean fireBrowserNavigationCallbacks(String url)
url
- The URL to fire the navigation callbacks against.public void waitForReady()
public BrowserComponent ready(SuccessCallback<BrowserComponent> onReady)
onReady
- Callback to be executed when the browser component is ready.waitForReady()
public AsyncResource<BrowserComponent> ready()
public AsyncResource<BrowserComponent> ready(int timeout)
timeout
- Timeout in milliseconds to wait.public static boolean isNativeBrowserSupported()
public void setProperty(String key, Object value)
key
- see the documentation with the CodenameOne Implementation for further detailsvalue
- see the documentation with the CodenameOne Implementation for further detailspublic String getTitle()
public String getURL()
public void setURL(String url)
url
- the URLpublic void setURL(URL url)
url
- The URL to the page to display.public void setURL(URI uri)
uri
- URI to the page to display.public void setURL(String url, Map<String,String> headers)
isURLWithCustomHeadersSupported()
url
- the URLheaders
- headers to push into the request for the urlpublic boolean isURLWithCustomHeadersSupported()
setURL(java.lang.String, java.util.Map)
is supportedpublic void setURLHierarchy(String url) throws IOException
url
- the URLIOException
public void reload()
public boolean hasBack()
public boolean hasForward()
public void back()
public void forward()
public void clearHistory()
public void setPinchToZoomEnabled(boolean e)
e
- true to enable pinch to zoom, false to disable itpublic boolean isPinchToZoomEnabled()
public void setNativeScrollingEnabled(boolean b)
b
- true to enable native scrolling, notice that non-native scrolling might be problematicpublic boolean isNativeScrollingEnabled()
public void setPage(String html, String baseUrl)
html
- HTML web pagebaseUrl
- base URL to associate with the HTMLpublic void addWebEventListener(String type, ActionListener listener)
type
- platform specific but must support: onStart, onLoad, onErrorlistener
- callback for the eventpublic void removeWebEventListener(String type, ActionListener listener)
type
- see addWebEventListener for detailslistener
- see addWebEventListener for detailspublic void stop()
public void destroy()
public void fireWebEvent(String type, ActionEvent ev)
type
- the type of the eventev
- the eventpublic void execute(String javaScript)
javaScript
- the JavaScript stringpublic void execute(String js, Object[] params)
js
- 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 injectParameters(java.lang.String, java.lang.Object...)
for more information about injected parameters.
by parameters.public String executeAndReturnString(String javaScript)
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. execute(java.lang.String, com.codename1.util.SuccessCallback)
javaScript
- the JavaScript code to executepublic String executeAndReturnString(String javaScript, Object[] params)
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. execute(java.lang.String, com.codename1.util.SuccessCallback)
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 injectParameters(java.lang.String, java.lang.Object...)
for more information about injected parameters.public BrowserComponent.JSProxy createJSProxy(String javascriptExpression)
public void execute(String js, SuccessCallback<BrowserComponent.JSRef> callback)
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 #addJSCallback(java.lang.String, com.codename1.util.Callback)
method
instead.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)
.public void execute(int timeout, String js, SuccessCallback<BrowserComponent.JSRef> callback)
js
- The javascript to executetimeout
- The timeout in milliseconds.callback
- The callbackpublic void execute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)
timeout
- The timeout in msjs
- The javascript expression 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 injectParameters(java.lang.String, java.lang.Object...)
for more information about injected parameters.
by parameters.callback
- Callback to call when complete.public void execute(String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)
js
- The javascript expression 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 injectParameters(java.lang.String, java.lang.Object...)
for more information about injected parameters.
by parameters.callback
- Callback to call when complete.public void addJSCallback(String installJs, SuccessCallback<BrowserComponent.JSRef> callback)
Register a Callback to be called whenever a button is clicked
bc.addJSCallback("someButton.addEventListener('click', function(){callback.onSuccess('hello world')})", new Callback<JSRef>() {
public void onSucess(JSRef value) {
System.out.println("Received click: "+value);
}
});
installJs
- callback
- public void addJSCallback(String installJs, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback)
installJs
- The javascript expression. to run.params
- Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0} , ${1} , etc... to be replaced. See injectParameters(java.lang.String, java.lang.Object...)
for more information about injected parameters.
by parameters.callback
- The callback to call on completion.public void removeJSCallback(Callback<BrowserComponent.JSRef> callback)
addJSCallback(java.lang.String, 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.
callback
- The callback to remove.public void removeJSCallback(SuccessCallback<BrowserComponent.JSRef> callback)
public static String injectParameters(String jsExpression, Object... params)
jsExpression
- The javascript expression with placeholders to inject parameters.params
- public BrowserComponent.JSRef executeAndWait(int timeout, String js, Object... params)
timeout
- Timeout in milliseconds.js
- The javascript expression.params
- Parameters to inject in the expression. See injectParameters(java.lang.String, java.lang.Object...)
for details.public BrowserComponent.JSRef executeAndWait(String js, Object... params)
js
- The javascript expression.params
- Parameters to inject in the expression. See injectParameters(java.lang.String, java.lang.Object...)
for details.public BrowserComponent.JSRef executeAndWait(String js)
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 execute(java.lang.String, 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.
js
- The javascript expression to execute. You must call callback.onSuccess(value)
with the result that you want to have returned.callback.onSuccess(value)
public BrowserComponent.JSRef executeAndWait(int timeout, String js)
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 execute(java.lang.String, 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.
timeout
- Timeout in msjs
- The javascript expression to execute. You must call callback.onSuccess(value)
with the result that you want to have returned.callback.onSuccess(value)
public void exposeInJavaScript(Object o, String name)
o
- the object to invoke, notice all public fields and methods would be exposed to JavaScriptname
- the name to expose within JavaScriptpublic void setDebugMode(boolean mode)
mode
- true to debug false otherwise, this might have no effect in some platformspublic void putClientProperty(String key, Object value)
Component
putClientProperty
in class Component
key
- arbitrary key for the propertyvalue
- the value assigned to the given client propertypublic boolean isDebugMode()
public static String createDataURI(byte[] data, String mime)
This is the easiest way to get an HTML with local images to work on all mobile platforms.
data
- data of an imagemime
- the mime type of the image e.g. image/png