List icon Conteúdo

Mapeamento

Nesta seção, mostraremos como a principal funcionalidade da versão 6.x é mapeada para a versão 7.0.

Engine

Criar engine

6.x

O Engine não faz parte da API pública. Ele é criado internamente quando a primeira instância Browser é criada na aplicação. Apenas um Engine pode ser criado e utilizado na aplicação.

7.0

O Engine é uma parte da API pública agora. É possível criar e utilizar várias instâncias Engine na aplicação. Para criar uma instância Engine com as opções necessárias, utilize o seguinte código:

Java
Kotlin
Engine engine = Engine.newInstance(
        EngineOptions.newBuilder(RenderingMode.OFF_SCREEN)
                // O idioma usado nas páginas de erro padrão e GUI.
                .language(Language.ENGLISH_US)
                // O caminho absoluto para o diretório onde os dados 
                // tais como cache, cookies, histórico, cache GPU, armazenamento local 
                // links visitados, dados web, ficheiros de dicionário de verificação ortográfica 
                // etc. são armazenados.
                .userDataDir(Paths.get("/Users/Me/JxBrowser/UserData"))
                .build());
val engine = Engine.newInstance(
        EngineOptions.newBuilder(RenderingMode.OFF_SCREEN) 
            // A linguagem usada nas páginas de erro padrão e GUI.
            .language(Language.ENGLISH_US)
            // O caminho absoluto para o diretório onde os dados 
            // tais como cache, cookies, histórico, cache GPU, armazenamento local 
            // links visitados, dados web, ficheiros de dicionário de verificação ortográfica 
            // etc. são armazenados.
            .userDataDir(Path("/Users/Me/JxBrowser/UserData"))
            .build()
)

O Engine executa um processo nativo separado onde o Chromium com as opções fornecidas é criado e inicializado. O processo nativo comunica com o processo Java através da ponte IPC (Inter-Process Communication). Se o processo nativo for terminado inesperadamente devido a uma falha, o processo Java continuará a ser executado.

Você pode utilizar a seguinte notificação para saber quando as instâncias Engine são terminadas inesperadamente, para que possa recriar o Engine e restaurar as instâncias Browser:

Java
Kotlin
engine.on(EngineCrashed.class, event -> {
   // Limpar todos os recursos alocados e recriar o Engine.
});
engine.on(EngineCrashed::class.java) { event ->
    // Limpa todos os recursos alocados e recria o Engine.
}

Encerrando o Motor

6.x

A instância Engine é encerrada automaticamente quando a última instância Browser é encerrada na aplicação.

7.0

O Engine deve ser fechado manualmente através do método close() quando não for mais necessário:

Java
Kotlin
engine.close();
engine.close()

Quando se fecha o Engine, todas as suas instâncias Browser são fechadas automaticamente. Qualquer tentativa de utilização de um Engine já fechado, conduzirá a uma exceção.

Para saber quando o Engine está fechado, utilize a seguinte notificação:

Java
Kotlin
engine.on(EngineClosed.class, event -> {});
engine.on(EngineClosed::class.java) { event -> }

Browser

Criando um browser

6.x

Java
Kotlin
Browser browser = new Browser();
val browser = Browser()

7.0

Java
Kotlin
Browser browser = engine.newBrowser();
val browser = engine.newBrowser()

Criando um browser com opções

6.x

Java
Kotlin
BrowserContextParams browserContextParams =
        new BrowserContextParams("Users/Me/JxBrowser/Data");
browserContextParams.setStorageType(StorageType.MEMORY);
BrowserContext browserContext = new BrowserContext(browserContextParams);
Browser browser = new Browser(BrowserType.HEAVYWEIGHT, browserContext);
val browserContextParams = BrowserContextParams("Users/Me/JxBrowser/Data")
browserContextParams.setStorageType(StorageType.MEMORY)
val browserContext = BrowserContext(browserContextParams)
val browser = Browser(BrowserType.HEAVYWEIGHT, browserContext)

7.0

A funcionalidade BrowserContext foi movida para Engine. Assim, o mesmo código deve ser substituído por:

Java
Kotlin
Engine engine = Engine.newInstance(EngineOptions.newBuilder(HARDWARE_ACCELERATED)
        .userDataDir(Paths.get("/Users/Me/JxBrowser/UserData"))
        .enableIncognito()
        .build());
Browser browser = engine.newBrowser();
val engine = Engine.newInstance(EngineOptions.newBuilder(HARDWARE_ACCELERATED)
        .userDataDir(Path("/Users/Me/JxBrowser/UserData"))
        .enableIncognito()
        .build()
) 
val browser = engine.newBrowser()

Fechando o browser

6.x

Java
Kotlin
browser.dispose();
browser.dispose()

7.0

Java
Kotlin
browser.close();
browser.close()

Responsivo/não responsivo

6.x

Java
Kotlin
browser.addRenderListener(new RenderAdapter() {
    @Override
    public void onRenderUnresponsive(RenderEvent event) {}

    @Override
    public void onRenderResponsive(RenderEvent event) {}
});
browser.addRenderListener(object: RenderAdapter {
    override fun onRenderUnresponsive(event: RenderEvent) {}
    override fun onRenderResponsive(event: RenderEvent) {}
})

7.0

Java
Kotlin
browser.on(BrowserBecameResponsive.class, event -> {});
browser.on(BrowserBecameUnresponsive.class, event -> {});
browser.on(BrowserBecameResponsive::class.java) { event -> }
browser.on(BrowserBecameUnresponsive::class.java) { event -> }

BrowserView

Criando o Swing BrowserView

6.x

Java
Kotlin
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
...
BrowserView view = new BrowserView(browser);
import com.teamdev.jxbrowser.chromium.swing.BrowserView
...
val view = BrowserView(browser)

7.0

Java
Kotlin
import com.teamdev.jxbrowser.view.swing.BrowserView;
...
BrowserView view = BrowserView.newInstance(browser);
import com.teamdev.jxbrowser.view.swing.BrowserView
...
val view = BrowserView.newInstance(browser)

Criando um BrowserView JavaFX

6.x

Java
Kotlin
import com.teamdev.jxbrowser.chromium.javafx.BrowserView;
...
BrowserView view = new BrowserView(browser);
import com.teamdev.jxbrowser.chromium.javafx.BrowserView
...
val view = BrowserView(browser)

7.0

Java
Kotlin
import com.teamdev.jxbrowser.view.javafx.BrowserView;
...
BrowserView view = BrowserView.newInstance(browser);
import com.teamdev.jxbrowser.view.javafx.BrowserView
...
val view = BrowserView.newInstance(browser)

Frame

Trabalhando com frame

6.x

Uma página Web pode ser constituída por um frame principal que pode conter vários sub-frames. Para efetuar uma operação com um frame, é necessário passar o identificador do frame para o método correspondente. Por exemplo:

Java
Kotlin
// Obtém HTML do frame principal.
browser.getHTML();

// Obtém HTML de todos os frames.
for (Long frameId : browser.getFramesIds()) {
String html = browser.getHTML(frameId);
}
// Obtém o HTML do frame principal.
browser.html

// Obtém o HTML de todos os frames.
for (frameId in browser.framesIds) {
    val html = browser.getHTML(frameId)
}

7.0

O Frame é uma parte da API pública agora. É possível trabalhar com o frame através da instância Frame. Por exemplo:

Java
Kotlin
// Obtém o HTML do frame principal se ele existir.
browser.mainFrame().ifPresent(Frame::getHtml);

// Obter o HTML de todos os frames.
browser.frames().forEach(frame -> {
String html = frame.html();
});
// Obtém o HTML do frame principal se ele existir.
browser.mainFrame().ifPresent(Frame::getHtml)

// Obtém o HTML de todos os frames.
browser.frames().forEach { frame ->
    val html = frame.html()
}

Navegação

Carregando URL

6.x

Java
Kotlin
browser.loadURL("https://www.google.com");
browser.loadURL("https://www.google.com")

7.0

Java
Kotlin
browser.navigation().loadUrl("https://www.google.com");
browser.navigation().loadUrl("https://www.google.com")

Carregamento de HTML

6.x

Java
Kotlin
browser.loadHTML("<html><body></body></html>");
browser.loadHTML("<html><body></body></html>")

7.0

Java
Kotlin
browser.mainFrame().ifPresent(frame ->
        frame.loadHtml("<html><body></body></html>"));
browser.mainFrame().ifPresent { frame -> 
        frame.loadHtml("<html><body></body></html>") }

Filtragem de URLs

6.x

Java
Kotlin
browser.setLoadHandler(new DefaultLoadHandler() {
    @Override
    public boolean onLoad(LoadParams params) {
        if (params.getURL().startsWith("mailto:")) {
            return true; // Cancelar o carregamento
        }
        return false; // Continuar o carregamento
    }
});
browser.setLoadHandler(object: DefaultLoadHandler {
        override fun onLoad(params: LoadParams): Boolean {
            return if (params.getURL().startsWith("mailto:")) {
                true // Cancelar o carregamento
            } else false // Continuar o carregamento
        }
})

7.0

Java
Kotlin
navigation.set(StartNavigationCallback.class, params -> {
    if (params.url().startsWith("mailto:")) {
        return Response.ignore();
    }
    return Response.start();
});
navigation.set(StartNavigationCallback::class.java,
    StartNavigationCallback { params ->
        if (params.url().startsWith("mailto:")) Response.ignore() else Response.start()
    }
)

Eventos de navegação

Iniciar o carregamento

6.x

Java
Kotlin
browser.addLoadListener(new LoadAdapter() {
    @Override
    public void onStartLoadingFrame(StartLoadingEvent event) {
        String url = event.getValidatedURL();
    }
});
browser.addLoadListener(object: LoadAdapter {
    override fun onStartLoadingFrame(event: StartLoadingEvent) {
        val url = event.validatedURL
    }
})

7.0

Java
Kotlin
browser.navigation().on(NavigationStarted.class, event -> {
    String url = event.url();
});
browser.navigation().on(NavigationStarted::class.java) { event -> 
    val url = event.url()
}

Finalizar o carregamento

6.x

Java
Kotlin
browser.addLoadListener(new LoadAdapter() {
    @Override
    public void onFinishLoadingFrame(FinishLoadingEvent event) {
        String html = browser.getHTML(event.getFrameId());
    }
});
browser.addLoadListener(object: LoadAdapter {
    override fun onFinishLoadingFrame(event: FinishLoadingEvent) {
        val html = browser.getHTML(event.frameId)
    }
})

7.0

Java
Kotlin
browser.navigation().on(FrameLoadFinished.class, event -> {
    String html = event.frame().html();
});
browser.navigation().on(FrameLoadFinished::class.java) { event -> 
    val html = event.frame().html()
}

Falha no carregamento

6.x

Java
Kotlin
browser.addLoadListener(new LoadAdapter() {
    @Override
    public void onFailLoadingFrame(FailLoadingEvent event) {
        NetError errorCode = event.getErrorCode();
    }
});
browser.addLoadListener(object: LoadAdapter {
    override fun onFailLoadingFrame(event: FailLoadingEvent) {
        val errorCode = event.errorCode
    }
})

7.0

Java
Kotlin
browser.navigation().on(FrameLoadFailed.class, event -> {
    NetError error = event.error();
});
browser.navigation().on(FrameLoadFailed::class.java) { event -> 
    val error = event.error()
}
ou
Java
Kotlin
browser.navigation().on(NavigationFinished.class, event -> {
    NetError errorCode = event.error();
});
browser.navigation().on(NavigationFinished::class.java) { event -> 
    val errorCode = event.error()
}

Rede

Configurando o User-Agent

6.x

Java
Kotlin
BrowserPreferences.setUserAgent("My User-Agent");
BrowserPreferences.setUserAgent("My User-Agent")

7.0

Java
Kotlin
Engine engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .userAgent("My User-Agent")
        .build());
val engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .userAgent("My User-Agent")
        .build())

Configurando o Accept-Language

6.x

Java
Kotlin
browserContext.setAcceptLanguage("fr, en-gb;q=0.8, en;q=0.7");
browserContext.setAcceptLanguage("fr, en-gb;q=0.8, en;q=0.7")

7.0

Java
Kotlin
engine.network().acceptLanguage("fr, en-gb;q=0.8, en;q=0.7");
engine.network().acceptLanguage("fr, en-gb;q=0.8, en;q=0.7")

Configurando o proxy

6.x

Java
Kotlin
ProxyService proxyService = browserContext.getProxyService();
proxyService.setProxyConfig(new CustomProxyConfig("http-proxy-server:80"));
val proxyService = browserContext.proxyService
proxyService.setProxyConfig(CustomProxyConfig("http-proxy-server:80"))

7.0

Java
Kotlin
engine.proxy().config(CustomProxyConfig.newInstance("http-proxy-server:80"));
engine.proxy().config(CustomProxyConfig.newInstance("http-proxy-server:80"))

Redirecionando o request de URL

6.x

Java
Kotlin
browserContext.getNetworkService().setNetworkDelegate(new NetworkDelegate() {
    @Override
    public void onBeforeURLRequest(BeforeURLRequestParams params) {
        params.setURL("https://www.google.com");
    }
});
browserContext.networkService.setNetworkDelegate(object: NetworkDelegate {
    override fun onBeforeURLRequest(params: BeforeURLRequestParams) {
        params.setURL("https://www.google.com")
    }
})

7.0

Java
Kotlin
engine.network().set(BeforeUrlRequestCallback.class, (params) -> 
        Response.redirect("https://www.google.com"));
engine.network().set(BeforeUrlRequestCallback::class.java,
    BeforeUrlRequestCallback { params ->
        Response.redirect("https://www.google.com")
    }
)

Substituindo de cabeçalhos HTTP

6.x

Java
Kotlin
browserContext.getNetworkService().setNetworkDelegate(new NetworkDelegate() {
    ...
    @Override
    public void onBeforeSendHeaders(BeforeSendHeadersParams params) {
        HttpHeadersEx headers = params.getHeadersEx();
        headers.setHeader("User-Agent", "MyUserAgent");
        headers.setHeader("Content-Type", "text/html");
    }
});
browserContext.networkService.setNetworkDelegate(object: NetworkDelegate {
    override fun onBeforeSendHeaders(params: BeforeSendHeadersParams) {
        val headers = params.headersEx
        headers.setHeader("User-Agent", "MyUserAgent")
        headers.setHeader("Content-Type", "text/html")
    }
})

7.0

Java
Kotlin
engine.network().set(BeforeSendHeadersCallback.class, (params) ->
        Response.override(Arrays.asList(
                HttpHeader.of("User-Agent", "MyUserAgent"),
                HttpHeader.of("Content-Type", "text/html"))));
engine.network().set(BeforeSendHeadersCallback::class.java,
    BeforeSendHeadersCallback { params ->
        Response.override(listOf(
                HttpHeader.of("User-Agent", "MyUserAgent"),
                HttpHeader.of("Content-Type", "text/html")))
    }
)

Interceptar requests de URL

6.x

Java
Kotlin
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
protocolService.setProtocolHandler("https", new ProtocolHandler() {
    @Override
    public URLResponse onRequest(URLRequest request) {
        URLResponse response = new URLResponse();
        String html = "<html><body><p>Olá!</p></body></html>";
        response.setData(html.getBytes());
        response.getHeaders().setHeader("Content-Type", "text/html");
        return response;
    }
});
val browserContext = browser.context
val protocolService = browserContext.protocolService
protocolService.setProtocolHandler("https", object: ProtocolHandler {
    override fun onRequest(request: URLRequest): URLResponse {
        val response = URLResponse()
        val html = "<html><body><p>Olá!</p></body></html>"
        response.setData(html.toByteArray())
        response.headers.setHeader("Content-Type", "text/html")
        return response
    }
});

7.0

Java
Kotlin
Network network = engine.network();
network.set(InterceptRequestCallback.class, params -> {
    UrlRequest urlRequest = params.urlRequest();
    if (urlRequest.url().startsWith("https")) {
        Options options = UrlRequestJob.Options
                .newBuilder(urlRequest.id(), HttpStatus.OK)
                .addHttpHeader(HttpHeader.of("Content-Type", "text/html"))
                .build();
        UrlRequestJob urlRequestJob = network.newUrlRequestJob(options);
        String html = "<html><body><p>Olá!</p></body></html>";
        urlRequestJob.write(html.getBytes(UTF_8));
        urlRequestJob.complete();
        return Response.intercept(urlRequestJob);
    }
    return Response.proceed();
});
val network = engine.network()
network.set(InterceptRequestCallback::class.java, InterceptRequestCallback { params ->
    val urlRequest = params.urlRequest()
    if (urlRequest.url().startsWith("https")) {
        val options = UrlRequestJob.Options
            .newBuilder(urlRequest.id(), HttpStatus.OK)
            .addHttpHeader(HttpHeader.of("Content-Type", "text/html"))
            .build()
        val urlRequestJob = network.newUrlRequestJob(options)
        val html = "<html><body><p>Olá!</p></body></html>"
        urlRequestJob.write(html.toByteArray(UTF_8))
        urlRequestJob.complete()
        Response.intercept(urlRequestJob)
    } else {
        Response.proceed()
    }
})

Autenticação

Proxy, Basic, Digest, NTLM

6.x

Java
Kotlin
NetworkService networkService = browserContext.getNetworkService();
networkService.setNetworkDelegate(new NetworkDelegate() {
    ...
    @Override
    public boolean onAuthRequired(AuthRequiredParams params) {
        if (params.isProxy()) {
            params.setUsername("user");
            params.setPassword("password");
            return false;
        }
        return true; // Cancela o request de autenticação
    }
});
val networkService = browser.networkService
networkService.setNetworkDelegate(object: NetworkDelegate {
    ...
    override fun onAuthRequired(params: AuthRequiredParams): Boolean {
        return if (params.isProxy()) {
            params.setUsername("user")
            params.setPassword("password")
            false
        } else true // Cancela o request de autenticação
    }
});

7.0

Java
Kotlin
engine.network().set(AuthenticateCallback.class, (params, tell) -> {
    if (params.isProxy()) {
        tell.authenticate("user", "password");
    } else {
        tell.cancel();
    }
});
engine.network().set(AuthenticateCallback::class.java, 
    AuthenticateCallback { params, tell ->
        if (params.isProxy) {
            tell.authenticate("user", "password")
        } else {
            tell.cancel()
        }
    }
)

Certificado de cliente HTTPS

6.x

Java
Kotlin
browser.setDialogHandler(new DialogHandler() {
    ...
    @Override
    public CloseStatus onSelectCertificate(CertificatesDialogParams params) {
        List<Certificate> certificates = params.getCertificates();
        if (certificates.isEmpty()) {
            return CloseStatus.CANCEL;
        } else {
            params.setSelectedCertificate(certificates.get(certificates.size() - 1));
            return CloseStatus.OK;
        }
    }
});
browser.setDialogHandler(object: DialogHandler {
    ...
    override fun onSelectCertificate(params: CertificatesDialogParams): CloseStatus {
        val certificates = params.certificates
        return if (certificates.isEmpty()) {
            CloseStatus.CANCEL
        } else {
            params.setSelectedCertificate(certificates[certificates.size - 1])
            CloseStatus.OK
        }
    }
});

7.0

Java
Kotlin
browser.set(SelectClientCertificateCallback.class, (params, tell) -> {
    List<Certificate> certificates = params.certificates();
    if (certificates.isEmpty()) {
        tell.cancel();
    } else {
        tell.select(certificates.size() - 1);
    }
});
browser.set(SelectClientCertificateCallback::class.java,
    SelectClientCertificateCallback { params, tell ->
        val certificates = params.certificates()
        if (certificates.isEmpty()) {
            tell.cancel()
        } else {
            tell.select(certificates.size - 1)
        }
    }
)

Plugins

Filtrando plugins

6.x

Java
Kotlin
browser.getPluginManager().setPluginFilter(new PluginFilter() {
    @Override
    public boolean isPluginAllowed(PluginInfo pluginInfo) {
        return true;
    }
});
browser.pluginManager.setPluginFilter(object: PluginFilter {
    override fun isPluginAllowed(pluginInfo: PluginInfo): Boolean {
        return true
    }
})

7.0

Java
Kotlin
engine.plugins().set(AllowPluginCallback.class, params -> Response.allow());
engine.plugins().set(AllowPluginCallback::class.java,
    AllowPluginCallback { Response.allow() })

DOM

Acessando o document

6.x

Java
Kotlin
DOMDocument document = browser.getDocument();
if (document != null) {
    String baseURI = document.getBaseURI();
}
val document = browser.document
val baseURI = document?.baseURI

7.0

Java
Kotlin
browser.mainFrame().ifPresent(frame ->
        frame.document().ifPresent(document -> {
            String baseUri = document.baseUri();
        }));
browser.mainFrame().ifPresent { frame ->
    frame.document().ifPresent { document ->
        val baseUri = document.baseUri()
    }
}

Eventos DOM

Trabalhando com eventos

6.x

Java
Kotlin
element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
    @Override
    public void handleEvent(DOMEvent event) {
        DOMEventTarget eventTarget = event.getTarget();
        if (eventTarget != null) {
            ...
        }
    }
}, false);
element.addEventListener(DOMEventType.OnClick, object: DOMEventListener {
    override fun handleEvent(event: DOMEvent) {
        val eventTarget = event.target
        if (eventTarget != null) {
            ...
        }
    }
})

7.0

Java
Kotlin
element.addEventListener(EventType.CLICK, event ->
        event.target().ifPresent(eventTarget -> {
            ...
        }), false);
element.addEventListener(EventType.CLICK, { event ->
    event.target().ifPresent { eventTarget ->
        ...
    }
}, false)

CSS

Injetando CSS

6.x

Java
Kotlin
browser.setCustomStyleSheet("body { background-color: orange; }");
browser.setCustomStyleSheet("body { background-color: orange; }")

7.0

Java
Kotlin
browser.set(InjectCssCallback.class, params -> 
        Response.inject("body { background-color: orange; }"));
browser.set(InjectCssCallback::class.java,
        InjectCssCallback { Response.inject("body { background-color: orange; }") })

JavaScript

Chamando JavaScript a partir do Java

6.x

Java
Kotlin
String string = browser.executeJavaScriptAndReturnValue("'Hello'")
        .asString().getValue();
double number = browser.executeJavaScriptAndReturnValue("123")
        .asNumber().getValue();
boolean bool = browser.executeJavaScriptAndReturnValue("true")
        .asBoolean().getValue();
JSObject window = browser.executeJavaScriptAndReturnValue("window")
        .asObject();
val string = browser.executeJavaScriptAndReturnValue("'Hello'")
        .asString().value
val number = browser.executeJavaScriptAndReturnValue("123")
        .asNumber().value
val bool = browser.executeJavaScriptAndReturnValue("true")
        .asBoolean().value
val window = browser.executeJavaScriptAndReturnValue("window")
        .asObject()

7.0

A classe JSValue foi removida. A conversão de tipos agora é efetuada automaticamente. É possível executar JavaScript tanto de forma síncrona, bloqueando a execução da thread atual, como de forma assíncrona:

Java
Kotlin
browser.mainFrame().ifPresent(frame -> {
    String string = frame.executeJavaScript("'Hello'");
    Double number = frame.executeJavaScript("123");
    Boolean bool = frame.executeJavaScript("true");
    JsObject window = frame.executeJavaScript("window");

    frame.executeJavaScript("document", (Consumer<Document>) document -> {
        String baseUri = document.baseUri();
    });
});
browser.mainFrame().ifPresent { frame: Frame ->
    val string = frame.executeJavaScript<String>("'Hello'")
    val number = frame.executeJavaScript<Double>("123")
    val bool = frame.executeJavaScript<Boolean>("true")
    val window = frame.executeJavaScript<JsObject>("window")
    
    frame.executeJavaScript("document", Consumer<Document> { document ->
        val baseUri = document.baseUri()
    })
}

Chamando o Java a partir do JavaScript

6.x

No código Java:

Java
Kotlin
public class JavaObject {
    public void foo(String text) {}
}

JSValue window = browser.executeJavaScriptAndReturnValue("window");
if (window.isObject()) {
    window.asObject().setProperty("java", new JavaObject());
}
class JavaObject {
    fun foo(text String) {}
}

val window = browser.executeJavaScriptAndReturnValue("window")
if (window.isObject()) {
    window.asObject().setProperty("java", JavaObject())
}

No código JavaScript:

window.java.foo("Olá");

7.0

Por razões de segurança, apenas os métodos públicos anotados com @JsAccessible podem ser acessados a partir do JavaScript.

No código Java:

Java
Kotlin
public class JavaObject {
    @JsAccessible
    public void foo(String text) {}
}

JsObject window = frame.executeJavaScript("window");
window.putProperty("java", new JavaObject());
class JavaObject {
    @JsAccessible
    fun foo(text: String) {}
}

val window = frame.executeJavaScript<JsObject>("window")
window?.putProperty("java", JavaObject())

No código JavaScript:

window.java.foo("Olá");

Injetando JavaScript

6.x

Java
Kotlin
browser.addScriptContextListener(new ScriptContextAdapter() {
    @Override
    public void onScriptContextCreated(ScriptContextEvent event) {
        JSValue window = browser.executeJavaScriptAndReturnValue(
                event.getJSContext().getFrameId(), "window");
    }
});
browser.addScriptContextListener(object: ScriptContextAdapter {
    override fun onScriptContextCreated(event: ScriptContextEvent) {
        val window = browser.executeJavaScriptAndReturnValue(
                event.jsContext.frameId, "window")
    }
})

7.0

Java
Kotlin
browser.set(InjectJsCallback.class, params -> {
    JsObject window = params.frame().executeJavaScript("window");
    return Response.proceed();
});
browser.set(InjectJsCallback::class.java, InjectJsCallback { params ->
    val window = params.frame().executeJavaScript<JsObject>("window")
    Response.proceed()
})

Eventos do console

6.x

Java
Kotlin
browser.addConsoleListener(new ConsoleListener() {
    @Override
    public void onMessage(ConsoleEvent event) {
        String message = event.getMessage();
    }
});
browser.addConsoleListener(object: ConsoleListener {
    override fun onMessage(event: ConsoleEvent) {
        val message = event.message
    }
})

7.0

Java
Kotlin
browser.on(ConsoleMessageReceived.class, event -> {
    String message = event.consoleMessage().message();
});
browser.on(ConsoleMessageReceived::class.java) { event ->
    val message = event.consoleMessage().message()
}

Pop-ups

Contendo de pop-ups

6.x

Java
Kotlin
browser.setPopupHandler(new PopupHandler() {
    @Override
    public PopupContainer handlePopup(PopupParams params) {
        return null;
    }
});
browser.setPopupHandler(object: PopupHandler {
    override fun handlePopup(params: PopupParams): PopupContainer? {
        return null
    }
})

7.0

Java
Kotlin
browser.set(CreatePopupCallback.class, (params) -> Response.suppress());
browser.set(CreatePopupCallback::class.java, CreatePopupCallback { Response.suppress() })

Abrindo pop-ups

6.x

Java
Kotlin
browser.setPopupHandler(new PopupHandler() {
    @Override
    public PopupContainer handlePopup(PopupParams params) {
        return new PopupContainer() {
            @Override
            public void insertBrowser(Browser popupBrowser, Rectangle initialBounds) {}
        };
    }
});
browser.setPopupHandler(object: PopupHandler {
    override fun handlePopup(params: PopupParams): PopupContainer {
        return object: PopupContainer {
            override fun insertBrowser(popupBrowser: Browser, initialBounds: Rectangle) {}
        }
    }
})

7.0

Java
Kotlin
browser.set(CreatePopupCallback.class, (params) -> Response.create());
browser.set(OpenPopupCallback.class, (params) -> {
    Browser popup = params.popupBrowser();
    return OpenPopupCallback.Response.proceed();
});
browser.set(CreatePopupCallback::class.java, CreatePopupCallback { Response.create() })
browser.set(OpenPopupCallback::class.java, OpenPopupCallback { params -> 
    val popup = params.popupBrowser()
    OpenPopupCallback.Response.proceed()
})

Diálogos

Diálogos JavaScript

6.x

Java
Kotlin
browser.setDialogHandler(new DialogHandler() {
    @Override
    public void onAlert(DialogParams params) {
    }

    @Override
    public CloseStatus onConfirmation(DialogParams params) {
        return CloseStatus.CANCEL;
    }

    @Override
    public CloseStatus onPrompt(PromptDialogParams params) {
        params.setPromptText("Text");
        return CloseStatus.OK;
    }
...
});
browser.setDialogHandler(object: DialogHandler {
    override fun onAlert(params: DialogParams) {}
    override fun onConfirmation(params: DialogParams): CloseStatus =
        CloseStatus.CANCEL
    override fun onPrompt(params: PromptDialogParams): CloseStatus {
        params.setPromptText("Text")
        return CloseStatus.OK
    }  
})

7.0

Java
Kotlin
browser.set(AlertCallback.class, (params, tell) -> tell.ok());
browser.set(ConfirmCallback.class, (params, tell) -> tell.cancel());
browser.set(PromptCallback.class, (params, tell) -> tell.ok("Text"));
browser.set(AlertCallback::class.java, AlertCallback { params, tell -> tell.ok() })
browser.set(ConfirmCallback::class.java, ConfirmCallback { params, tell -> tell.cancel() })
browser.set(PromptCallback::class.java, PromptCallback { params, tell -> tell.ok("Text") })

Diálogos de arquivo

6.x

Java
Kotlin
browser.setDialogHandler(new DialogHandler() {
    @Override
    public CloseStatus onFileChooser(FileChooserParams params) {
        FileChooserMode mode = params.getMode();
        if (mode == FileChooserMode.Open) {
            params.setSelectedFiles(new File(params.getDefaultFileName()));
        }
        if (mode == FileChooserMode.OpenMultiple) {
            params.setSelectedFiles(new File("file1.txt"), new File("file2.txt"));
        }
        return CloseStatus.OK;
    }
    ...
});
browser.setDialogHandler(object: DialogHandler {
    override fun onFileChooser(params: FileChooserParams): CloseStatus {
        val mode = params.mode
        if (mode == FileChooserMode.Open) {
            params.setSelectedFiles(File(params.defaultFileName))
        }
        if (mode == FileChooserMode.OpenMultiple) {
            params.setSelectedFiles(File("file1.txt"), File("file2.txt"))
        }
        return CloseStatus.OK
    }
})

7.0

Java
Kotlin
browser.set(OpenFileCallback.class, (params, tell) ->
        tell.open(Paths.get(params.defaultFileName())));
browser.set(OpenFilesCallback.class, (params, callback) ->
        callback.open(Paths.get("file1.txt"), Paths.get("file2.txt")));
browser.set(OpenFileCallback::class.java, 
    OpenFileCallback { params, tell -> 
        tell.open(Path(params.defaultFileName()))
    }
)
browser.set(OpenFilesCallback::class.java, 
    OpenFilesCallback { _, callback -> 
        callback.open(Path("file1.txt"), Path("file2.txt"))
    }
)

Diálogos de cores

6.x

Java
Kotlin
browser.setDialogHandler(new DialogHandler() {
    @Override
    public CloseStatus onColorChooser(ColorChooserParams params) {
        params.setColor(params.getColor());
        return CloseStatus.OK;
    }
    ...
});
browser.setDialogHandler(object: DialogHandler {
    override fun onColorChooser(params: ColorChooserParams): CloseStatus {
        params.setColor(params.сolor)
        return CloseStatus.OK
    }
})

7.0

Java
Kotlin
browser.set(SelectColorCallback.class, (params, tell) ->
        tell.select(params.defaultColor()));
browser.set(SelectColorCallback::class.java, 
    SelectColorCallback { params, tell -> 
        tell.select(params.defaultColor())
    }
)

Diálogos de certificados SSL

6.x

Java
Kotlin
browser.setDialogHandler(new DialogHandler() {
    @Override
    public CloseStatus onSelectCertificate(CertificatesDialogParams params) {
        X509Certificate x509Certificate = ...;
        PrivateKey privateKey = ...;
        params.setSelectedCertificate(new Certificate(x509Certificate, privateKey));
        return CloseStatus.OK;
    }
    ...
});
browser.setDialogHandler(object: DialogHandler {
    override fun onSelectCertificate(params: CertificatesDialogParams): CloseStatus {
        val x509Certificate: X509Certificate = ...
        val privateKey: PrivateKey = ...
        params.setSelectedCertificate(Certificate(x509Certificate, privateKey))
        return CloseStatus.OK
    }
    ...
})

7.0

Java
Kotlin
private static final Path CLIENT_CERT_FILE = Paths.get("<cert-file>.p12");
private static final String CLIENT_CERT_PASSWORD = "<cert-password>";
...
browser.set(SelectClientCertificateCallback.class, (params, tell) ->
        tell.select(ClientCertificate.of(CLIENT_CERT_FILE,
                CLIENT_CERT_PASSWORD, KeyStoreType.PKCS12)));
private val certFile = Path("<cert-file>.p12")
private val certPassword = "<cert-password>"
...
browser.set(SelectClientCertificateCallback::class.java, 
    SelectClientCertificateCallback { params, tell -> 
        tell.select(ClientCertificate.of(certFile,
                certPassword, KeyStoreType.PKCS12))
    }
)

Menu de contexto

Manipulação do menu de contexto

6.x

Java
Kotlin
browser.setContextMenuHandler(new ContextMenuHandler() {
    @Override
    public void showContextMenu(ContextMenuParams params) {
    }
});
browser.setContextMenuHandler(object: ContextMenuHandler {
    override fun showContextMenu(params: ContextMenuParams) {
    }
})

7.0

Java
Kotlin
browser.set(ShowContextMenuCallback.class, (params, tell) -> {
    tell.close();
});
browser.set(ShowContextMenuCallback::class.java,
    ShowContextMenuCallback { params, tell -> tell.close() }
)

Leia mais sobre como lidar com o menu de contexto.

Impressão

Configurando a impressão

6.x

Java
Kotlin
browser.setPrintHandler(new PrintHandler() {
    @Override
    public PrintStatus onPrint(PrintJob printJob) {
        PrintSettings printSettings = printJob.getPrintSettings();
        printSettings.setPrinterName("Microsoft XPS Document Writer");
        printSettings.setLandscape(true);
        printSettings.setPrintBackgrounds(true);
        ...
        return PrintStatus.CONTINUE;
    }
});
browser.setPrintHandler(object: PrintHandler {
    override fun onPrint(printJob: PrintJob): PrintStatus {
        val printSettings = printJob.printSettings
        printSettings.setPrinterName("Microsoft XPS Document Writer")
        printSettings.setLandscape(true)
        printSettings.setPrintBackgrounds(true)
        ...
        return PrintStatus.CONTINUE
    }
})

7.0

A funcionalidade que permite configurar a impressão foi removida. Em vez disso, é possível apresentar uma caixa de diálogo normal de Pré-visualização da impressão, na qual se podem introduzir as definições necessárias:

Java
Kotlin
browser.set(PrintCallback.class, (params, tell) -> tell.showPrintPreview());
browser.set(PrintCallback::class.java,
    PrintCallback { params, tell -> tell.showPrintPreview() }
)

Suspendendo a impressão

6.x

Java
Kotlin
browser.setPrintHandler(new PrintHandler() {
    @Override
    public PrintStatus onPrint(PrintJob printJob) {
        return PrintStatus.CANCEL;
    }
});
browser.setPrintHandler(object: PrintHandler {
    override fun onPrint(printJob: PrintJob): PrintStatus = 
        PrintStatus.CANCEL
})

7.0

Java
Kotlin
browser.set(PrintCallback.class, (params, tell) -> tell.cancel());
browser.set(PrintCallback::class.java,
    PrintCallback { params, tell -> tell.cancel() }
)

Cache

Limpar o cache HTTP

6.x

Java
Kotlin
browser.getCacheStorage().clearCache(new Callback() {
    @Override
    public void invoke() {
        // A cache de disco HTTP foi limpa.
    }
});
browser.cacheStorage.clearCache(object: Callback {
    override fun invoke() { 
        // A cache de disco HTTP foi limpa.
    }
})

7.0

Java
Kotlin
engine.httpCache().clearDiskCache(() -> {
    // A cache de disco HTTP foi limpa.
});
engine.httpCache().clearDiskCache {
    // A cache de disco HTTP foi limpa.
}

Cookies

Acessando os cookies

6.x

Java
Kotlin
List<Cookie> cookies = browser.getCookieStorage().getAllCookies();
val cookies = browser.cookieStorage.allCookies

7.0

Java
Kotlin
List<Cookie> cookies = engine.cookieStore().cookies();
val cookies = engine.cookieStore().cookies()

Processo de renderização

Iniciado/Terminado

6.x

Java
Kotlin
browser.addRenderListener(new RenderAdapter() {
    @Override
    public void onRenderCreated(RenderEvent event) {}

    @Override
    public void onRenderGone(RenderEvent event) {
        TerminationStatus status = event.getTerminationStatus();
    }
});
browser.addRenderListener(object: RenderAdapter {
    override fun onRenderCreated(event: RenderEvent) {}
    override fun onRenderGone(event: RenderEvent) {
        val status: TerminationStatus = event.terminationStatus
    }
})

7.0

Java
Kotlin
browser.on(RenderProcessStarted.class, event -> {});
browser.on(RenderProcessTerminated.class, event -> {
    TerminationStatus status = event.status();
});
browser.on(RenderProcessStarted::class.java) { event -> }
browser.on(RenderProcessTerminated::class.java) { event -> 
    val status = event.status()
}

Chromium

Switches

A biblioteca não suporta todos os possíveis switches do Chromium. Ela permite configurar o Chromium com os switches, mas não garantimos que os switches aprovados funcionem corretamente ou funcionem de um modo geral. Recomendamos que verifique esta funcionalidade antes de utilizá-la.

6.x

Java
Kotlin
BrowserPreferences.setChromiumSwitches(
        "--<switch_name>",
        "--<switch_name>=<switch_value>"
);
BrowserPreferences.setChromiumSwitches(
        "--<switch_name>",
        "--<switch_name>=<switch_value>"
)

7.0

Java
Kotlin
Engine engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .addSwitch("--<switch_name>")
        .addSwitch("--<switch_name>=<switch_value>")
        .build());
val engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .addSwitch("--<switch_name>")
        .addSwitch("--<switch_name>=<switch_value>")
        .build())

Chaves API

6.x

Java
Kotlin
BrowserPreferences.setChromiumVariable(
        "GOOGLE_API_KEY", "My API Key");
BrowserPreferences.setChromiumVariable(
        "GOOGLE_DEFAULT_CLIENT_ID", "My Client ID");
BrowserPreferences.setChromiumVariable(
        "GOOGLE_DEFAULT_CLIENT_SECRET", "My Client Secret");
BrowserPreferences.setChromiumVariable(
        "GOOGLE_API_KEY", "My API Key")
BrowserPreferences.setChromiumVariable(
        "GOOGLE_DEFAULT_CLIENT_ID", "My Client ID")
BrowserPreferences.setChromiumVariable(
        "GOOGLE_DEFAULT_CLIENT_SECRET", "My Client Secret")

7.0

Java
Kotlin
Engine engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .googleApiKey("A minha chave API")
        .googleDefaultClientId("O meu ID de cliente")
        .googleDefaultClientSecret("O meu segredo de cliente")
        .build());
val engine = Engine.newInstance(EngineOptions.newBuilder(...)
        .googleApiKey("A minha chave API")
        .googleDefaultClientId("O meu ID de cliente")
        .googleDefaultClientSecret("O meu segredo de cliente")
        .build())

Logs

Na nova versão, a API de logs foi simplificada. Leia mais sobre como configurar os logs no guia Resolução de problemas.