Javafx webengine что это
Перейти к содержимому

Javafx webengine что это

  • автор:

Javafx webengine что это

Loading always happens on a background thread. Methods that initiate loading return immediately after scheduling a background job. To track progress and/or cancel a job, use the Worker instance available from the getLoadWorker() method.

The following example changes the stage title when loading completes successfully:

User Interface Callbacks

A number of user interface callbacks may be registered with a WebEngine object. These callbacks are invoked when a script running on the page requests a user interface operation to be performed, for example, opens a popup window or changes status text. A WebEngine object cannot handle such requests internally, so it passes the request to the corresponding callbacks. If no callback is defined for a specific operation, the request is silently ignored.

The following example shows a callback that resizes a browser window:

Access to Document Model

The WebEngine objects create and manage a Document Object Model (DOM) for their Web pages. The model can be accessed and modified using Java DOM Core classes. The getDocument() method provides access to the root of the model. Additionally DOM Event specification is supported to define event handlers in Java code.

The following example attaches a Java event listener to an element of a Web page. Clicking on the element causes the application to exit:

Evaluating JavaScript expressions

It is possible to execute arbitrary JavaScript code in the context of the current page using the executeScript(java.lang.String) method. For example:

The execution result is returned to the caller, as described in the next section.

Mapping JavaScript values to Java objects

If the result is a JavaScript object, it is wrapped as an instance of the JSObject class. (As a special case, if the JavaScript object is a JavaRuntimeObject as discussed in the next section, then the original Java object is extracted instead.) The JSObject class is a proxy that provides access to methods and properties of its underlying JavaScript object. The most commonly used JSObject methods are getMember (to read a named property), setMember (to set or define a property), and call (to call a function-valued property).

A DOM Node is mapped to an object that both extends JSObject and implements the appropriate DOM interfaces. To get a JSObject object for a Node just do a cast:

In some cases the context provides a specific Java type that guides the conversion. For example if setting a Java String field from a JavaScript expression, then the JavaScript value is converted to a string.

Mapping Java objects to JavaScript values
Calling back to Java from JavaScript

The JSObject.setMember method is useful to enable upcalls from JavaScript into Java code, as illustrated by the following example. The Java code establishes a new JavaScript object named app . This object has one public member, the method exit . You can then refer to the object and the method from your HTML page:

When a user clicks the link the application is closed.

If there are multiple Java methods with the given name, then the engine selects one matching the number of parameters in the call. (Varargs are not handled.) An unspecified one is chosen if there are multiple ones with the correct number of parameters.

You can pick a specific overloaded method by listing the parameter types in an extended method name , which has the form » method_name ( param_type1 . param_typen )» . Typically you’d write the JavaScript expression:

Threading

WebEngine objects must be created and accessed solely from the JavaFX Application thread. This rule also applies to any DOM and JavaScript objects obtained from the WebEngine object.

Property Summary

All Methods Instance Methods Concrete Methods

Type Property and Description
ObjectProperty<Callback<String,Boolean>> confirmHandler

Constructor Summary

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type Method and Description
ObjectProperty<Callback<String,Boolean>> confirmHandlerProperty ()

Methods inherited from class java.lang.Object

Property Detail

document
location
title
javaScriptEnabled
userStyleSheetLocation

This should be a local URL, i.e. either ‘data:’ , ‘file:’ , or ‘jar:’ . Remote URLs are not allowed for security reasons.

userDataDirectory

If the value of this property is not null , the WebEngine will attempt to store local user data in the respective directory. If the value of this property is null , the WebEngine will attempt to store local user data in an automatically selected system-dependent user- and application-specific directory.

When a WebEngine is about to start loading a web page or executing a script for the first time, it checks whether it can actually use the directory specified by this property. If the check fails for some reason, the WebEngine invokes the WebEngine.onError event handler, if any, with a WebErrorEvent describing the reason. If the invoked event handler modifies the userDataDirectory property, the WebEngine retries with the new value as soon as the handler returns. If the handler does not modify the userDataDirectory property (which is the default), the WebEngine continues without local user data.

Once the WebEngine has started loading a web page or executing a script, changes made to this property have no effect on where the WebEngine stores or will store local user data.

Currently, the directory specified by this property is used only to store the data that backs the window.localStorage objects. In the future, more types of data can be added.

userAgent
onAlert
onStatusChanged
onResized
onVisibilityChanged
createPopupHandler

To satisfy this request a handler may create a new WebEngine , attach a visibility handler and optionally a resize handler, and return the newly created engine. To block the popup, a handler should return null .

By default, a popup handler is installed that opens popups in this WebEngine .

confirmHandler

An implementation may display a dialog box with Yes and No options, and return the user’s choice.

promptHandler

An implementation may display a dialog box with an text field, and return the user’s input.

onError

Constructor Detail

WebEngine
WebEngine

Method Detail

getLoadWorker
getDocument
documentProperty
getLocation
locationProperty
getTitle
titleProperty
setJavaScriptEnabled
isJavaScriptEnabled
javaScriptEnabledProperty
setUserStyleSheetLocation
getUserStyleSheetLocation
userStyleSheetLocationProperty

This should be a local URL, i.e. either ‘data:’ , ‘file:’ , or ‘jar:’ . Remote URLs are not allowed for security reasons.

getUserDataDirectory

If the value of this property is not null , the WebEngine will attempt to store local user data in the respective directory. If the value of this property is null , the WebEngine will attempt to store local user data in an automatically selected system-dependent user- and application-specific directory.

When a WebEngine is about to start loading a web page or executing a script for the first time, it checks whether it can actually use the directory specified by this property. If the check fails for some reason, the WebEngine invokes the WebEngine.onError event handler, if any, with a WebErrorEvent describing the reason. If the invoked event handler modifies the userDataDirectory property, the WebEngine retries with the new value as soon as the handler returns. If the handler does not modify the userDataDirectory property (which is the default), the WebEngine continues without local user data.

Once the WebEngine has started loading a web page or executing a script, changes made to this property have no effect on where the WebEngine stores or will store local user data.

setUserDataDirectory

If the value of this property is not null , the WebEngine will attempt to store local user data in the respective directory. If the value of this property is null , the WebEngine will attempt to store local user data in an automatically selected system-dependent user- and application-specific directory.

When a WebEngine is about to start loading a web page or executing a script for the first time, it checks whether it can actually use the directory specified by this property. If the check fails for some reason, the WebEngine invokes the WebEngine.onError event handler, if any, with a WebErrorEvent describing the reason. If the invoked event handler modifies the userDataDirectory property, the WebEngine retries with the new value as soon as the handler returns. If the handler does not modify the userDataDirectory property (which is the default), the WebEngine continues without local user data.

Once the WebEngine has started loading a web page or executing a script, changes made to this property have no effect on where the WebEngine stores or will store local user data.

userDataDirectoryProperty

If the value of this property is not null , the WebEngine will attempt to store local user data in the respective directory. If the value of this property is null , the WebEngine will attempt to store local user data in an automatically selected system-dependent user- and application-specific directory.

When a WebEngine is about to start loading a web page or executing a script for the first time, it checks whether it can actually use the directory specified by this property. If the check fails for some reason, the WebEngine invokes the WebEngine.onError event handler, if any, with a WebErrorEvent describing the reason. If the invoked event handler modifies the userDataDirectory property, the WebEngine retries with the new value as soon as the handler returns. If the handler does not modify the userDataDirectory property (which is the default), the WebEngine continues without local user data.

Once the WebEngine has started loading a web page or executing a script, changes made to this property have no effect on where the WebEngine stores or will store local user data.

Руководство JavaFX WebView и WebEngine

Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook

1- JavaFX WebView

  • Изображает содержание HTML от локальных и удаленных URL
  • Собирает историю веб
  • Выполняет команды Javascript
  • Выполняет вызовы от Javascript до JavaFX
  • Управляет поп ап окна в веб
  • Применяет эффекты для встроенного браузера
  • Canvas
  • Media Playback
  • Form controls (except for <input type="color"> )
  • Editable content
  • History maintenance
  • Support for the <meter> and <progress> tags.
  • Support for the <details> and <summary> tags.
  • DOM
  • SVG
  • Support for domain names written in national languages

2- Пример с WebView

3- Пример WebView с ProgressBar

4- Вызов Javascript из JavaFX

5- Создание вызова Upcalls от JavaScript до JavaFX

View more Tutorials:

Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

  • * * Swift for Beginners, Learn Apple’s New Programming Language
  • Learn and Understand NodeJS
  • JavaFX tutorial: Learn JavaFX with Examples
  • JavaFx Tutorial For Beginners
  • Sharepoint: SPFx Development Model
  • JavaFX : Learn to build powerful client applications
  • Reactive Programming with Spring Framework 5
  • Java for Intermediate Users
  • Learning JavaScript Programming Tutorial. A Definitive Guide
  • Swift — Advanced API’s & Technique
  • SQL Server DBA Essentials for beginners
  • Advanced Java programming with JavaFx: Write an email client
  • Java, JSP and JDBC programming guides for complete BEGINNER
  • Bootstrap 4 Single Page Website from Scratch
  • Java Fx Concepts With Practical Examples
  • From 0 to 1: JavaFX and Swing for Awesome Java UIs
  • UI&UX Design , Animation And Material design In Javafx
  • Build Outstanding Java Apps with JavaFX much faster
  • Core Java. Exceptions
  • Learn Dart 2 in 90 minutes
  • Spring & Hibernate for Beginners (includes Spring Boot)
  • Web Programming with Python
  • * * AngularJS Masterclass — Deep Dive & Understand AngularJS
  • * * Crash Course Into JavaFX: The Best Way to make GUI Apps
  • Learn Hibernate 4 : Java’s Popular ORM Framework

JavaFX WebView

The JavaFX WebView ( javafx.scene.web.WebView ) component is capable of showing web pages (HTML, CSS, SVG, JavaScript) inside a JavaFX application. As such, the JavaFX WebView is a mini browser. The WebView component is very handy when you need to show documentation (e.g. Help texts), news, blog posts or other content which needs to be downloaded from a web server at runtime.

The JavaFX WebView uses the WebKit open source browser engine internally to render the web pages.

JavaFX WebView Example

The WebView component is a JavaFX Node so it can be included in the scene graph like any other JavaFX component which is also a Node . Here is a simple JavaFX WebView example:

This example shows a JavaFX application that creates a WebView which is inserted into a JavaFX VBox layout component — which is again placed inside a JavaFX Stage — which is set on the primary Stage .

WebView WebEngine

The JavaFX WebView WebEngine ( javafx.scene.web.WebEngine ) is an internal component used by the WebView to load the data that is to be displayed inside the WebView . To make the WebView WebEngine load data, you must first obtain the WebEngine instance from the WebView .

Obtaining the WebEngine

You obtain the WebEngine from the WebView by calling the WebView getEngine() method. Here is an example of obtaining the WebEngine from a JavaFX WebView :

Load a Web Page

Once you have obtained a WebEngine instance from the WebView you can load data by calling its load() method. The load() method takes a URL as parameter. Here is an example of loading a web page via the WebEngine load() method:

Load Local Content

The WebView WebEngine can load local content too — meaning content that is supplied to it directly in a method call (not loaded over the Internet). The WebEngine loads local content via the loadContent() method. Here is an example of loading local contain in a JavaFX WebView using loadContent()

The first parameter to the loadContent() call in the example above is the content itself. In this example it is a very simple HTML document contained in a Java String.

The second parameter to the loadContent() call in the example above is the content type (mime type) of the content. Since we are loading an HTML document, the standard content type for that is text/html .

Reload Content

It is possible to reload the content currently loaded in a JavaFX WebView . You do so using the WebEngine reload() method. Here is an example of reloading content in a JavaFX WebView using the WebEngine reload() method:

WebView Zoom

It is possible to set the zoom level of a JavaFX WebView . For instance, you can specify that the WebView should always zoom in 25%, or zoom out 10% etc. Zooming in scales up or down all of the content displayed inside the WebView . You set the WebView zoom level via the setZoom() method. Here is an example of setting the JavaFX WebView zoom level:

The setZoom() method takes a double value. A value of 1.0 means a zoom level of 100% which means no zoom. A value of 0.5 means a zoom level of 50%, which means zoom out to 50% of original size. In the example above, the value of 1.25 means a zoom level of 125%, meaning zoom in until a size of 125% of the original size.

WebView Font Scale

It also possible to only scale the text displayed inside a JavaFX WebView without scaling any of the non-text content (e.g. images) displayed inside the WebView . You set the font scaling property via the setFontScale() method. Here is an example of scaling up the text displayed in a JavaFX WebView by 25% (125% total):

The setFontScale() method takes a double parameter which specifies the font scale value. A scale value of 1.0 means no scaling up or down. A value of 0.5 means scaling down to half size, and a value of 2.0 means scaling up to double size.

Set User-Agent HTTP Header

You can set the User-Agent HTTP header sent to the web servers your WebView instance is loading web pages from. You set the User-Agent HTTP header via the WebEngine setUserAgent() method. Here is an example of setting the User-Agent HTTP header of a WebView :

You do not need to set the User-Agent HTTP Header, but you might be interested in having your particular app show up as a separate browser. You might want to include the version of WebKit your application is using. This gives web servers a better chance of optimizing their website for their visitor browsers, including yours. Here is an example of including the JavaFX and WebKit version in the User-Agent :

Disable WebView Context Menu

A JavaFX WebView has a default context menu (right click menu) which is displayed when you right click (context click) on the WebView in the JavaFX application. You can disable the WebView context menu by calling the WebView setContextMenuEnabled() method with a parameter value of false . Here is an example of disabling the context menu of a JavaFX WebView :

Browsing History

You can access the browsing history of a JavaFX WebView . The browsing history consists of the pages the user has visited while browsing inside the WebView . You access the browsing history of a JavaFX WebView via its WebEngine object. You call the WebEngine getHistory() method, and you get a WebHistory object back. Here is an example of obtaining the WebHistory object from a WebView WebEngine object:

Once you have access to the WebHistory object, you can start inspecting and manipulating the browsing history. We will see how in the following sections.

Browsing History Entries

You can access the browsing history entries kept inside a WebHistory object by calling its getEntries() method. Here is an example of obtaining a list of the browsing history entries from a WebHistory object:

The list returned is a list of WebHistory.Entry objects which can be inspected for information about each entry.

Iterate Browsing History Entries

You can access the browsing history entries (the pages visited) kept inside a WebHistory object. Here is an example of iterating through all the browsing history entries of a JavaFX WebHistory object:

You can also iterate the browsing history entries using a for-each loop, like this:

WebHistory.Entry

A WebHistory.Entry contains the following information:

  • URL
  • Title
  • Last visited date

You can access the URL, title and last visited date from a WebHistory.Entry using the following methods:

Go Forward and Backward in History

Once you have an instance of the WebHistory object you can actually manipulate the history. You can force the WebView to go forward and back in the browsing history. You do so by calling the WebHistory go() method. Here are two examples of going forward and backward in the browsing history:

If you pass a negative integer to the go() method the browser will move backward in the browsing history to the page (URL) visited just before the currently displayed page.

If you pass a positive integer to the go() method, you will make the WebView go one entry forward in the browsing history. That only works if the user has already visited at least 2 pages, and gone back from the first page.

Current History Entry Index

If you have moved back and forth a bit in the browsing history, you might be interested in seeing what index in the browsing history the current history entry has. You can see the index of the current browsing history entry via the method WebHistory getCurrentIndex() method. Here is an example of reading the index of the current browsing history entry:

Listening for State Changes When Loading Document

When you tell the WebEngine to load a document, the document is loaded in the background via another thread. You can listen for changes in the document loading status, so you can be notified when the document has finished loading. Here is an example of listening for document load status changes of a WebView WebEngine :

Execute JavaScript From Java

It is possible to execute JavaScript embedded in the HTML page displayed inside a JavaFX WebView from Java. You execute JavaScript in a WebView from Java via the WebEngine executeScript() method. Here is a simple example of executing JavaScript embedded in a WebView from Java code:

The executeScript() method takes a Java String as parameter which contains the JavaScript to execute. The example above calls a JavaScript function named myFunction() . This function has to be defined inside the web page displayed in the WebView the above WebEngine to.

Executing From a WebEngine Listener

So far I have had some problems executing JavaScript functions from Java, unless I call executeScript() from within a WebEngine listener. Here is an example of executing JavaScript from Java from within a WebEngine listener:

If you know what causes the problem, or why this «limitation» exists, I would appreciate an email explaining it 🙂

JavaScript Return Values

If a JavaScript function returns a value, that value will be converted to a Java data type and returned from the executeScript() method. Imagine that the myFunction() JavaScript function returns a String. In that case, a Java String would be returned from the executeScript() method. Here is how catching that String would look:

The following table shows what Java types various JavaScript return types are converted to:

JavaScript Type Java Type
null null
boolean Boolean
int32 Integer
number Double
string String
object JSObject ( netscape.javascript.JSObject )

Executing Java From JavaScript

It is also possible to call Java code from JavaScript running inside a JavaFX WebView . In order to do that you must make a Java object available to the JavaScript running inside the WebView . The easiest way to do that is to set the Java object as a member of the window object in the document displayed in the WebView . Here is how that is done:

The example above first gets access to the window object via the WebEngine executeScript() method. Second, the example sets an instance of the MyObject class as member on the window object. JavaScript running inside the WebView can now call methods on this object, as if it was a JavaScript object.

The MyObject class looks like this:

Once an object of this class has been exposed as a member of the window object named myObject , you can call its doIt() method like this:

Please keep in mind that when the document first loads in the WebView , the myObject is not yet exposed on the window object. Therefore, if you try to call a method on it immediately, it may fail.

Access the DOM

You can access the DOM of the web page displayed inside a JavaFX WebView by calling the WebEngine getDocument() method. Here is an example of accessing the DOM of a WebView :

The Document object returned is a org.w3c.dom.Document instance.

Web Page CSS Style Sheet

Normally a web page provides its own CSS style sheet. However, in case a web page has no CSS style sheet you can set a CSS style sheet for it using the WebEngine setUserStyleSheetLocation() . Here is an example of setting the CSS style sheet for a web page using WebEngine setUserStyleSheetLocation() ;

The String passed as parameter to the setUserStyleSheetLocation() method should be the path in the file system to where the CSS style sheet file is located,

WebView CSS Styles

It is possible to style a JavaFX WebView component with CSS, just like you can style any other JavaFX component. You can set the following CSS properties for a JavaFX WebView :

Javafx webengine что это

Loading Web Pages

  • From an arbitrary URL using the load(java.lang.String) method. This method uses the java.net package for network access and protocol handling.
  • From an in-memory String using the loadContent(java.lang.String, java.lang.String) and loadContent(java.lang.String) methods.

Loading always happens on a background thread. Methods that initiate loading return immediately after scheduling a background job. To track progress and/or cancel a job, use the Worker instance available from the getLoadWorker() method.

The following example changes the stage title when loading completes successfully:

User Interface Callbacks

A number of user interface callbacks may be registered with a WebEngine object. These callbacks are invoked when a script running on the page requests a user interface operation to be performed, for example, opens a popup window or changes status text. A WebEngine object cannot handle such requests internally, so it passes the request to the corresponding callbacks. If no callback is defined for a specific operation, the request is silently ignored.

The table below shows JavaScript user interface methods and properties with their corresponding WebEngine callbacks:

JavaScript Callback Table

JavaScript method/property WebEngine callback
window.alert() onAlert
window.confirm() confirmHandler
window.open() createPopupHandler
window.open() and
window.close()
onVisibilityChanged
window.prompt() promptHandler
Setting window.status onStatusChanged
Setting any of the following:
window.innerWidth , window.innerHeight ,
window.outerWidth , window.outerHeight ,
window.screenX , window.screenY ,
window.screenLeft , window.screenTop

onResized

The following example shows a callback that resizes a browser window:

Access to Document Model

The WebEngine objects create and manage a Document Object Model (DOM) for their Web pages. The model can be accessed and modified using Java DOM Core classes. The getDocument() method provides access to the root of the model. Additionally DOM Event specification is supported to define event handlers in Java code.

The following example attaches a Java event listener to an element of a Web page. Clicking on the element causes the application to exit:

Evaluating JavaScript expressions

It is possible to execute arbitrary JavaScript code in the context of the current page using the executeScript(java.lang.String) method. For example:

The execution result is returned to the caller, as described in the next section.

Mapping JavaScript values to Java objects

JavaScript values are represented using the obvious Java classes: null becomes Java null; a boolean becomes a java.lang.Boolean ; and a string becomes a java.lang.String . A number can be java.lang.Double or a java.lang.Integer , depending. The undefined value maps to a specific unique String object whose value is «undefined» .

If the result is a JavaScript object, it is wrapped as an instance of the JSObject class. (As a special case, if the JavaScript object is a JavaRuntimeObject as discussed in the next section, then the original Java object is extracted instead.) The JSObject class is a proxy that provides access to methods and properties of its underlying JavaScript object. The most commonly used JSObject methods are getMember (to read a named property), setMember (to set or define a property), and call (to call a function-valued property).

A DOM Node is mapped to an object that both extends JSObject and implements the appropriate DOM interfaces. To get a JSObject object for a Node just do a cast:

In some cases the context provides a specific Java type that guides the conversion. For example if setting a Java String field from a JavaScript expression, then the JavaScript value is converted to a string.

Mapping Java objects to JavaScript values

The arguments of the JSObject methods setMember and call pass Java objects to the JavaScript environment. This is roughly the inverse of the JavaScript-to-Java mapping described above: Java String , Number , or Boolean objects are converted to the obvious JavaScript values. A JSObject object is converted to the original wrapped JavaScript object. Otherwise a JavaRuntimeObject is created. This is a JavaScript object that acts as a proxy for the Java object, in that accessing properties of the JavaRuntimeObject causes the Java field or method with the same name to be accessed.

Note that the Java objects bound using JSObject.setMember , JSObject.setSlot , and JSObject.call are implemented using weak references. This means that the Java object can be garbage collected, causing subsequent accesses to the JavaScript objects to have no effect.

Calling back to Java from JavaScript

The JSObject.setMember method is useful to enable upcalls from JavaScript into Java code, as illustrated by the following example. The Java code establishes a new JavaScript object named app . This object has one public member, the method exit . You can then refer to the object and the method from your HTML page:

When a user clicks the link the application is closed.

Note that in the above example, the application holds a reference to the JavaApplication instance. This is required for the callback from JavaScript to execute the desired method.

In the following example, the application does not hold a reference to the Java object:

In this case, since the property value is a local object, «new JavaApplication()» , the value may be garbage collected in next GC cycle.

When a user clicks the link, it does not guarantee to execute the callback method exit .

If there are multiple Java methods with the given name, then the engine selects one matching the number of parameters in the call. (Varargs are not handled.) An unspecified one is chosen if there are multiple ones with the correct number of parameters.

You can pick a specific overloaded method by listing the parameter types in an «extended method name», which has the form » method_name ( param_type1 . param_typen )» . Typically you’d write the JavaScript expression:

The Java class and method must both be declared public.

Deploying an Application as a Module

If any Java class passed to JavaScript is in a named module, then it must be reflectively accessible to the javafx.web module. A class is reflectively accessible if the module opens the containing package to at least the javafx.web module. Otherwise, the method will not be called, and no error or warning will be produced.

For example, if com.foo.MyClass is in the foo.app module, the module-info.java might look like this:

Alternatively, a class is reflectively accessible if the module exports the containing package unconditionally.

WebEngine objects must be created and accessed solely from the JavaFX Application thread. This rule also applies to any DOM and JavaScript objects obtained from the WebEngine object.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *