Class BrowserComponent
- All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>
The browser component is an interface to an embeddable native platform browser on platforms that support embedding the native browser in place, if you need wide compatibility and flexibility you should check out the HTMLComponent which provides a lightweight 100% cross platform web component.
This component will only work on platforms that support embedding a native browser which exclude earlier versions of Blackberry devices and J2ME devices.
Its recommended that you place this component in a fixed position (none scrollable) on the screen without other focusable components to prevent confusion between focus authority and allow the component to scroll itself rather than CodenameOne making that decision for it.
On Android this component might show a native progress indicator dialog. You can disable that functionality using the call.
The following code shows the basic usage of the BrowserComponent:
Form hi = new Form("Browser", new BorderLayout());
BrowserComponent browser = new BrowserComponent();
browser.setURL("https://www.codenameone.com/");
hi.add(BorderLayout.CENTER, browser);
Debugging on Android
You can use Chrome's remote debugging features to debug the contents of a BrowserComponent. On Android 4.4 (KitKat) and higher, you will need to define the "android.webContentsDebuggingEnabled" display property in order for this to work. You can define this inside your app's init() method:
java Display.getInstance().setProperty("android.webContentsDebuggingEnabled", "true");
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classA wrapper class for a literal javascript expression that can be passed as an arg injava.lang.Object[]).classA thin wrapper around a Javascript variable that makes it easier to call methods on that variable.static classA wrapper class for a Javascript value that is returned via thecom.codename1.util.Callback)method.static enumEnum with the possible types for aJSRefobject. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringBrowser property key to control whether links withtarget="_blank"ortarget="_new"should be followed in the current browser view.static final StringString constant for web event listenercom.codename1.ui.events.ActionListener)static final StringString constant for web event listenercom.codename1.ui.events.ActionListener)static final StringString constant for web event listener.static final StringString constant for web event listenercom.codename1.ui.events.ActionListener)Fields inherited from class Component
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 Summary
ConstructorsConstructorDescriptionThis constructor will work as expected when a browser component is supported, see isNativeBrowserSupported() -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a navigation callback.voidaddJSCallback(String installJs, SuccessCallback<BrowserComponent.JSRef> callback) Registers a Java method as a callback in javascript.voidaddJSCallback(String installJs, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback) Registers Java method as a callback in Javascript.voidaddWebEventListener(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 loadsvoidback()Navigates back in the historyAsync method for capturing a screenshot of the browser content.voidClears navigation historystatic StringcreateDataURI(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.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 voidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.voiddestroy()Release native resources of this Browser Componentvoidexecute(int timeout, String js, SuccessCallback<BrowserComponent.JSRef> callback) Execute javascript with a timeout.voidexecute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback) Executes Javascript expression.voidExecutes the given JavaScript string within the current contextvoidexecute(String js, SuccessCallback<BrowserComponent.JSRef> callback) Asynchronously executes the provided javascript expression.voidExecutes given javascript string within current context.voidexecute(String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback) Executes Javascript expression.executeAndReturnString(String javaScript) Executes the given JavaScript and returns a result string from the underlying platform where applicable.executeAndReturnString(String javaScript, Object[] params) Executes the given javascript and returns the result string from the underlying platform.executeAndWait(int timeout, String js) This uses invokeAndBlock to wait for the result of the given javascript expression.executeAndWait(int timeout, String js, Object... params) This uses invokeAndBlock to wait for the result of the given javascript expression.executeAndWait(String js) This uses invokeAndBlock to wait for the result of the given javascript expression.executeAndWait(String js, Object... params) This uses invokeAndBlock to wait for the result of the given javascript expression.voidexposeInJavaScript(Object o, String name) Allows exposing the given object to JavaScript code so the JavaScript code can invoke methods and access fields on the given object.booleanFires all of the registered browser navigation callbacks against the provided URL.voidfireWebEvent(String type, ActionEvent ev) Used internally by the implementation to fire an event from the native browser widgetvoidforward()Navigates forward in the historyThe browser navigation callback interface allows handling a case where a URL invocation can be delegated to Java code.getTitle()The page titlegetURL()The page URLbooleanhasBack()Indicates whether back is currently availablebooleanIndicates whether forward is currently availablestatic StringinjectParameters(String jsExpression, Object... params) Injects parameters into a Javascript string expression.booleanIndicates if debug mode is set (might have no effect though)booleanChecks if javascript callbacks are run on the EDT.static booleanReturns true if the platform supports embedding a native browser componentbooleanThis method is unreliable and is only here for consistency with setNativeScrollingEnabled.booleanThis 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.booleanReturns true if the methodjava.util.Map)is supportedvoidpostMessage(String message, String targetOrigin) Calls the postMessage() method on the webpage's window object.voidputClientProperty(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.ready()Returns a promise that will complete when the browser component is "ready".ready(int timeout) Returns a promise that will complete when the browser component is "ready".ready(SuccessCallback<BrowserComponent> onReady) Registers a callback to be run when the BrowserComponent is "ready".voidreload()Reload the current pagevoidRemoves a navigation callback.voidremoveJSCallback(Callback<BrowserComponent.JSRef> callback) Removes a JS callback that was added via thecom.codename1.util.SuccessCallback)method.voidvoidremoveWebEventListener(String type, ActionListener listener) Removes the listener, see addWebEventListener for detailsvoidSet the browser navigation callback which allows handling a case where a URL invocation can be delegated to Java code.voidsetDebugMode(boolean mode) Toggles debug mode for the browser component which helps detect coding errors in the JavaScript bridge logicvoidsetFireCallbacksOnEdt(boolean edt) Sets whether javascript callbacks should be run on the EDT.voidsetNativeScrollingEnabled(boolean b) This flag allows disabling the native browser scrolling on platforms that support itvoidShows the given HTML in the native viewervoidsetPinchToZoomEnabled(boolean e) Some platforms require that you enable pinch to zoom explicitly.voidsetProperty(String key, Object value) This method allows customizing the properties of a web view in various ways including platform specific settings.voidSets the page URL.voidSets the page URL, jar: URL's must be supported by the implementationvoidSets the page URL, jar: URL's must be supported by the implementation.voidSets the page URL.voidsetURLHierarchy(String url) Sets the page URL while respecting the hierarchy of the htmlvoidstop()Cancel the loading of the current pagevoidUses invokeAndBlock to wait until the BrowserComponent is ready.Methods inherited from class Container
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, 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, updateTabIndicesMethods inherited from class Component
addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, 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, initComponent, 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, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, 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, setAccessibilityText, 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, setUIIDFinal, setUnselectedStyle, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContainsMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface Iterable
forEach, spliterator
-
Field Details
-
BROWSER_PROPERTY_FOLLOW_TARGET_BLANK
Browser property key to control whether links withtarget="_blank"ortarget="_new"should be followed in the current browser view. Defaults totrue.- See Also:
-
onStart
String constant for web event listenercom.codename1.ui.events.ActionListener)- See Also:
-
onLoad
String constant for web event listenercom.codename1.ui.events.ActionListener)- See Also:
-
onError
String constant for web event listenercom.codename1.ui.events.ActionListener)- See Also:
-
onMessage
String constant for web event listener. Use this event types to register to receive messages in a cross-domain-safe way from the web page. To send a message from the webpage, the page should include a function like:
`function postToCN1(msg) { if (window.cn1PostMessage) { // Case 1: Running inside native app in a WebView window.cn1PostMessage(msg);` else { // Case 2: Running inside a Javascript app in an iframe window.parent.postMessage(msg, '*'); } } }Receiving a message:
`myBrowserComponent.addWebEventListener(BrowserComponent.onMessage, e->{ CN.callSerially(()->{ Log.p("Message: "+e.getSource()); Dialog.show("Here", (String)e.getSource(), "OK", null);`); }); }- See Also:
-
-
Constructor Details
-
BrowserComponent
public BrowserComponent()This constructor will work as expected when a browser component is supported, see isNativeBrowserSupported()
-
-
Method Details
-
isNativeBrowserSupported
public static boolean isNativeBrowserSupported()Returns true if the platform supports embedding a native browser component
Returns
true if native browsing is supported
-
injectParameters
Injects parameters into a Javascript string expression. This will quote strings properly. The expression should include placeholders for each parameter of the form ${0}, ${1}, etc..
Parameters
-
jsExpression: The javascript expression with placeholders to inject parameters. -
params
Returns
The expression with placeholders replaced by parameters.
-
-
createDataURI
This method creates a data URI which allows developers creating HTML for local use to embed local images into the HTML by appending them as a URI. E.g. instead of referencing a file or URL just load the image data and place the contents of this string into the src attribute.
This is the easiest way to get an HTML with local images to work on all mobile platforms.
Parameters
-
data: data of an image -
mime: the mime type of the image e.g. image/png
Returns
a data URL that can be placed into the img src attribute in HTML e.g. data:image/png;base64,encodedData
Since
6.0
-
-
isFireCallbacksOnEdt
public boolean isFireCallbacksOnEdt()Checks if javascript callbacks are run on the EDT.
Returns
True if javascript callbacks are run on the EDT.
Since
5.0
See also
- #setFireCallbacksOnEdt(boolean)
-
setFireCallbacksOnEdt
public void setFireCallbacksOnEdt(boolean edt) Sets whether javascript callbacks should be run on the EDT. Default is true.
Parameters
edt: True if callbacks should be run on EDT. False if they should be run on the platform's main thread.
Since
5.0
-
captureScreenshot
Async method for capturing a screenshot of the browser content. Currently only supported in the simulator. Also, only displays the visible rectangle of the BrowserComponent, not the entire page.
Returns
AsyncResource resolving to an Image of the webview contents.
Since
7.0
-
deinitialize
protected void deinitialize()Description copied from class:ComponentInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.- Overrides:
deinitializein classComponent
-
postMessage
Calls the postMessage() method on the webpage's window object.
This is useful mainly for the Javascript port so that you don't have to worry about cross-domain issues, as postMessage() is supported cross-domain.
To receive a message, the web page should register a "message" event listener, just as it would to receive messages from other windows in the browser. See MDN docs for postMessage() for more information.
Parameters
-
message: The message to send. -
targetOrigin: The target origin of the message. E.g. http://example.com:1234
Since
7.0
-
-
waitForReady
public void waitForReady()Uses invokeAndBlock to wait until the BrowserComponent is ready. The browser component is considered to be ready once the onLoad event has been fired for the first page. -
ready
Registers a callback to be run when the BrowserComponent is "ready". The browser component is considered to be ready once the onLoad event has been fired on the first page. If this method is called after the browser component is already "ready", then the callback will be executed immediately. Otherwise it will be called in the first onLoad event.
Parameters
onReady: Callback to be executed when the browser component is ready.
Returns
Self for chaining.
Since
7.0
See also
- #waitForReady()
-
ready
Returns a promise that will complete when the browser component is "ready". It is considered to be ready once it has received the start or load event from at least one page. Default timeout is 5000ms.
Returns
AsyncResouce that will complete when the browser component is ready.
Since
7.0
-
ready
Returns a promise that will complete when the browser component is "ready". It is considered to be ready once it has received the start or load event from at least one page.
Parameters
timeout: Timeout in milliseconds to wait.
Returns
AsyncResouce that will complete when the browser component is ready.
Since
7.0
-
setProperty
This method allows customizing the properties of a web view in various ways including platform specific settings. When a property isn't supported by a specific platform it is just ignored.
Parameters
-
key: see the documentation with the CodenameOne Implementation for further details -
value: see the documentation with the CodenameOne Implementation for further details
-
-
getTitle
The page title
Returns
the title
-
getURL
The page URL
Returns
the URL
-
setURL
Sets the page URL, jar: URL's must be supported by the implementation
Parameters
url: the URL
-
setURL
Sets the page URL.
Parameters
url: The URL to the page to display.
-
setURL
Sets the page URL.
Parameters
uri: URI to the page to display.
-
setURL
-
isURLWithCustomHeadersSupported
public boolean isURLWithCustomHeadersSupported()Returns true if the method
java.util.Map)is supportedReturns
false by default
-
setURLHierarchy
Sets the page URL while respecting the hierarchy of the html
Parameters
url: the URL
- Throws:
IOException
-
reload
public void reload()Reload the current page -
hasBack
public boolean hasBack()Indicates whether back is currently available
Returns
true if back should work
-
hasForward
public boolean hasForward()Indicates whether forward is currently available
Returns
true if forward should work
-
back
public void back()Navigates back in the history -
forward
public void forward()Navigates forward in the history -
clearHistory
public void clearHistory()Clears navigation history -
isPinchToZoomEnabled
public boolean isPinchToZoomEnabled()This method is unreliable and is only here for consistency with setPinchToZoomEnabled, it will not return whether the platform supports pinch since this is very hard to detect properly.
Returns
the last value for setPinchToZoomEnabled
-
setPinchToZoomEnabled
public void setPinchToZoomEnabled(boolean e) Some platforms require that you enable pinch to zoom explicitly. This method has no effect if pinch to zoom isn't supported by the platform
Parameters
e: true to enable pinch to zoom, false to disable it
-
isNativeScrollingEnabled
public boolean isNativeScrollingEnabled()This method is unreliable and is only here for consistency with setNativeScrollingEnabled.
Returns
the last value for setNativeScrollingEnabled
-
setNativeScrollingEnabled
public void setNativeScrollingEnabled(boolean b) This flag allows disabling the native browser scrolling on platforms that support it
Parameters
b: true to enable native scrolling, notice that non-native scrolling might be problematic
-
setPage
-
addWebEventListener
Adds a listener to the given event type name, event type names are platform specific but some must be fired for all platforms and will invoke the action listener when the appropriate event loads
Parameters
-
type: platform specific but must support: onStart, onLoad, onError -
listener: callback for the event
-
-
removeWebEventListener
Removes the listener, see addWebEventListener for details
Parameters
-
type: see addWebEventListener for details -
listener: see addWebEventListener for details
-
-
stop
public void stop()Cancel the loading of the current page -
destroy
public void destroy()Release native resources of this Browser Component -
fireWebEvent
Used internally by the implementation to fire an event from the native browser widget
Parameters
-
type: the type of the event -
ev: the event
-
-
execute
Executes the given JavaScript string within the current context
Parameters
javaScript: the JavaScript string
-
execute
Executes given javascript string within current context.
Parameters
-
js: The javascript to execute. -
params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. Seejava.lang.Object...)for more information about injected parameters. by parameters.
-
-
executeAndReturnString
Executes the given JavaScript and returns a result string from the underlying platform where applicable.
Note: Some platforms use
Display#invokeAndBlock(java.lang.Runnable)inside this method which is very costly. Try to avoid this synchronous method, and prefer to use one of the asynchronous versions. E.g.com.codename1.util.SuccessCallback)Parameters
javaScript: the JavaScript code to execute
Returns
the string returned from the Javascript call
-
executeAndReturnString
Executes the given javascript and returns the result string from the underlying platform.
Note: Some platforms use
Display#invokeAndBlock(java.lang.Runnable)inside this method which is very costly. Try to avoid this synchronous method, and prefer to use one of the asynchronous versions. E.g.com.codename1.util.SuccessCallback)Parameters
-
javaScript: The javascript to execute. -
params: Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. Seejava.lang.Object...)for more information about injected parameters.
Returns
The result as a string.
Since
5.0
-
-
createJSProxy
Creates a proxy for a Javascript object that makes it easier to call methods, retrieve, and manipulate properties on the object. -
execute
Asynchronously executes the provided javascript expression. The expression may provide a callback which you can call inside the expression directly.
Example
Getting the window object.
`bc.execute("callback.onSuccess(window)", value -> { System.out.println("value="+value+"; type="+value.getJSType()); // value=[object Window]; type=OBJECT`); }Getting an Integer
`bc.execute("callback.onSuccess(1+2)", value -> { System.out.println("value="+value.getInt()+"; type="+value.getJSType()); // value=3; type=NUMBER`); }Getting a String
`bc.execute("callback.onSuccess('hello world')",value -> { System.out.println("value="+value+"; type="+value.getJSType()); // value=hello world; type=STRING` ); }After a Javascript Timeout
Since this call is asynchronous, the javascript code can wait to call the callback to any time in the future - e.g. after a timeout, after an ajax response, in some event handler, etc.. The CN1 UI will not be blocked, the provided callback will be called at the appropriate time on the EDT.
`bc.execute("setTimeout(function(){callback.onSuccess('hello world')`, 1500)", value -> { System.out.println("value="+value+"; type="+value.getJSType()); // value=hello world; type=STRING } ); }NOTE: The callback can only be called once, so you shouldn't use this method to register a callback with an event listener that will be called repeatedly. If you want to register a Java callback with a Javascript event, you should use the
com.codename1.util.Callback)method instead.Parameters
-
js: The javascript expression. If you want to receive any result from this expression, the expression itself must include a call to callback.onSuccess(value). -
callback: The callback. You should call this directly from Javascript. You can call eithercallback.onSuccess(value)orcallback.onError(message,code).
-
-
execute
Execute javascript with a timeout. If timeout is reached before callback is run, then the callback's onError method is run (if callback is a Callback). If callback isn't a Callback (i.e. has no onError(), then this will log an error, and call the onSucess method with a null arg.
Parameters
-
js: The javascript to execute -
timeout: The timeout in milliseconds. -
callback: The callback
-
-
execute
public void execute(int timeout, String js, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback) Executes Javascript expression.
Parameters
-
timeout: The timeout in ms -
js: The javascript expression to execute. -
params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. Seejava.lang.Object...)for more information about injected parameters. by parameters. -
callback: Callback to call when complete.
-
-
execute
Executes Javascript expression.
Parameters
-
js: The javascript expression to execute. -
params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. Seejava.lang.Object...)for more information about injected parameters. by parameters. -
callback: Callback to call when complete.
-
-
addJSCallback
Registers a Java method as a callback in javascript. The callback argument can be referenced inside the javascript expression so that it can be fired when certain events occur.
Examples
Register a Callback to be called whenever a button is clicked
`bc.addJSCallback("someButton.addEventListener('click', function(){callback.onSuccess('hello world')`)", new Callback() { public void onSucess(JSRef value) { System.out.println("Received click: "+value); } }); }Parameters
-
installJs -
callback
-
-
addJSCallback
public void addJSCallback(String installJs, Object[] params, SuccessCallback<BrowserComponent.JSRef> callback) Registers Java method as a callback in Javascript. The callback argument can be referenced inside the javascript expression so that it can be fired when certain events occur.
Parameters
-
installJs: The javascript expression. to run. -
params: @param params Parameters to inject into the javascript expression. The expression should contain placeholders of the form ${0 }, ${1 }, etc... to be replaced. Seejava.lang.Object...)for more information about injected parameters. by parameters. -
callback: The callback to call on completion.
-
-
removeJSCallback
Removes a JS callback that was added via the
com.codename1.util.SuccessCallback)method.Note: This won't unregister any callbacks from the Javascript environment. You'll need to perform your own additional cleanup in Javascript if this callback is registered in any event handlers.
Parameters
callback: The callback to remove.
-
removeJSCallback
-
executeAndWait
This uses invokeAndBlock to wait for the result of the given javascript expression.
Parameters
-
timeout: Timeout in milliseconds. -
js: The javascript expression. -
params: Parameters to inject in the expression. Seejava.lang.Object...)for details.
Returns
The result.
-
-
executeAndWait
This uses invokeAndBlock to wait for the result of the given javascript expression.
Parameters
-
js: The javascript expression. -
params: Parameters to inject in the expression. Seejava.lang.Object...)for details.
Returns
The result.
-
-
executeAndWait
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)orliteralcallback.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 ofcom.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 eithercallback.onSuccess(value)orliteralcallback.onError(message, code)at some point in the Javascript expression - or the method will block indefinitely.Parameters
js: The javascript expression to execute. You must callcallback.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
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)orliteralcallback.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 ofcom.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 eithercallback.onSuccess(value)orliteralcallback.onError(message, code)at some point in the Javascript expression - or the method will block indefinitely.Parameters
-
timeout: Timeout in ms -
js: The javascript expression to execute. You must callcallback.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
Allows exposing the given object to JavaScript code so the JavaScript code can invoke methods and access fields on the given object. Notice that on RIM devices which don't support reflection this object must implement the propriatery Scriptable interface http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/script/Scriptable.html
Parameters
-
o: the object to invoke, notice all public fields and methods would be exposed to JavaScript -
name: the name to expose within JavaScript
Deprecated
-
-
putClientProperty
Description copied from class:ComponentClient properties allow the association of meta-data with a component, this is useful for some applications that construct GUI's on the fly and need to track the connection between the UI and the data. Setting the value to null will remove the client property from the component.
Parameters
-
key: arbitrary key for the property -
value: the value assigned to the given client property
- Overrides:
putClientPropertyin classComponent
-
-
isDebugMode
public boolean isDebugMode()Indicates if debug mode is set (might have no effect though)
Returns
true if debug mode was activated
-
setDebugMode
public void setDebugMode(boolean mode) Toggles debug mode for the browser component which helps detect coding errors in the JavaScript bridge logic
Parameters
mode: true to debug false otherwise, this might have no effect in some platforms
-