1

Updated

I tried to use the BrowserComponent on an Android device: if I touch the back button of the device, the app does nothing (with the following code).

In this question I copy the part of code that is relevant.

My question is if somebody can provide me an example of working code that executes a javascript function declared in the page when the back button is pressed (in particular, a function that goes to the previous page). Please take attention that I need the setBrowserNavigationCallback (as in the following code).

I also appreciate if somebody can correct the code to use the setURLHierarchy correctly, because it crashes the Simulator and it doesn't load "/community.html" on a real device.

Thank you very much for any help.


Update: this is the last version of my code

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("Community", new BorderLayout());

    // Suppress Android native indicator
    Display.getInstance().setProperty("WebLoadingHidden", "true");

    // Create the BrowserComponent
    browser = new BrowserComponent();

    // Set user-agent
    browser.setProperty("useragent", appAgent);

    // Set the start page - TO CORRECT, it's messy
    if (Display.getInstance().isSimulator()) {
        // I added this condition because opening a local html page
        // causes that the Simulator crashes
        browser.setURL(startPage_development);
        Log.p("BrowserComponet setUrl: " + startPage_development);
    } else {

        try {
            if (!Display.getInstance().isSimulator()) {
                browser.setURLHierarchy("/community.html");
            } else {
                browser.setURLHierarchy("/testing.html");
            }
            Log.p("BrowserComponet setURLHierarchy successfully");
        } catch (Exception err) {
            Log.e(err);
            browser.setURL(startPage);
            Log.p("BrowserComponet setUrl: " + startPage);
        }
    }

    // Javascript Bridge for back command
    JavascriptContext context = new JavascriptContext(browser);
    // JSObject document = (JSObject) context.get("document");
    JSObject window = context.getWindow();
    hi.setBackCommand(new Command("Back") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            //window.call("goBackButton()");
            window.call("eval", new Object[]{"history.go(-1);"});
        }
    });

    // Allow browsing only inside my domains
    browser.setBrowserNavigationCallback((url) -> {
        if (url.startsWith("javascript")
                || url.startsWith(url_Root_development)
                || url.startsWith(url_Root_production)
                || url.startsWith(loginRoot)) {
            return true; // the BrowserComponent should navigate
        } else {
            Display.getInstance().callSerially(() -> {
                // it opens the url with the native platform
                Boolean can = Display.getInstance().canExecute(url);
                if (can != null && can) {
                    Display.getInstance().execute(url);
                }
            });
            return false; // the BrowserComponent shouldn't navigate
        }
    });

    hi.add(BorderLayout.CENTER, browser);
    hi.show();
}

2 Answers 2

1

Use setBackCommand to override the back button behavior and set up any business logic you might have including a call to JavaScript code.

7
  • Thank you for the suggestion, however I need more help, please. I've just updated the question, adding the code that I've tried and that doesn't work. Aug 27, 2017 at 18:40
  • What doesn't work? Is it still minimized? Is the code reached? You can reproduce this in the Android skin by pressing escape
    – Shai Almog
    Aug 28, 2017 at 3:40
  • After a lot of hours of tries and errors, I completly update the question and the code. Pressing the back button does nothing with my code: can you please read the updated version of my question? Thank you Aug 29, 2017 at 3:34
  • That means the back command code was reached. If you place a breakpoint in the simulator it should work. Why don't you just invoke back() on the browser component?
    – Shai Almog
    Aug 29, 2017 at 4:12
  • 1
    I suggest filing issues. That's not an answer to a question it's a rant and I doubt anyone will see it other than me. One of these issues can be resolved just by using "Update Client Libs" in Codename One settings as we updated the resource file format recently but I can't "answer your answer" so this isn't really helpful. Pressing the escape button should generate trigger the back command but it's possible the browser widget is grabbing key input, Codename One can only go so far... Web content isn't as portable as our code and if it misbehaves there are limits to what we can do.
    – Shai Almog
    Aug 31, 2017 at 4:31
0

I thanks Shai for the suggestions, but they weren't enough to get a working code and a working simulator (in which pressing escape does nothing, and I didn't understood the meaning of using a breakpoint in this case). Just invoke back() on the browser component isn't what I need, because I need to use a more complex approach, that is to invoke a javascript function written by me that makes the browser goes back only if the Internet connection is available yet (or it shows a message that Internet is not more available).

So, that's why I'm trying to answer the question by myself, decomposing the problem in several steps. I've spent several days and a lot of effort to solve a so simple problem (call a javascript pressing the back button), primarily because the lack of documentation (the Codename One JS Bridge package includes several examples in the API, but not this case) and the crashes (and strange behaviors) of the Codename One Simulator, as reported in the following text.

I hope to help other people sharing what I've done.

Step 1: Load a local page with the BrowserComponent

I created a new empty Codename One project with Netbeans, I gave it the name "myBrowser", package name "it.galgani.demos.mybrowser", main class name "MyBrowser", theme "native", template "Hello world (bare bones)".

I modified the default start() method so:

   public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("MyBrowser", new BorderLayout());

        // Create the BrowserComponent
        BrowserComponent browser = new BrowserComponent();

        try {
            // Load a web page placed in the "html" package
            browser.setURLHierarchy("/index.html");
            Log.p("setURLHierarchy executed");
        } catch (IOException ex) {
            Log.e(ex);
        }

        hi.add(BorderLayout.CENTER, browser);
        hi.show();
    }

Then I created a new "Java package" inside the "Source packages" with the name "html". In my case, the created folder is: "/home/francesco/NetBeansProjects/myBrowser/src/html"

Inside the html folder, I created this index.html (selecting "New File", Category "Other", file type "HTML", file name "index"):

<!DOCTYPE html>
<html>
    <head>
        <title>BrowserComponent setURLHierarchy test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>Hello world</div>
    </body>
</html>

Then I clicked on "Clean and Build Project" (no errors, it's good), then on "Run Project": it works, my "Hello world" is shown correctly. Now the next step...

Step 2: create other html pages

I modify the index.html so:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="page1.html">Page 1</a><br />
        <a href="page2.html">Page 2</a><br />
        <a href="page3.html">Page 3</a><br />
    </body>
</html>

and then I created page1.html, page2.html and page3.html with this code (changing the h1 according to the page):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Page 1</h1>
    </body>
</html>

I tried all in the simulator and it was ok. To go back from a page to the previous one, in the simulator there is an option accessible by clicking with the right button of the mouse on the page.

The log reported two java exception, the first one when the simulator is opened, the second one when it's closed, however they didn't influence the simulator functionality:

java.io.UTFDataFormatException: malformed input around byte 64
    at java.io.DataInputStream.readUTF(DataInputStream.java:656)
    at java.io.DataInputStream.readUTF(DataInputStream.java:564)
    at com.codename1.ui.util.Resources.loadTheme(Resources.java:1270)
    at com.codename1.ui.util.Resources.openFileImpl(Resources.java:303)
    at com.codename1.ui.util.Resources.openFile(Resources.java:269)
    at com.codename1.ui.util.Resources.<init>(Resources.java:189)
    at com.codename1.ui.util.Resources.open(Resources.java:768)
    at com.codename1.ui.util.Resources.open(Resources.java:688)
    at com.codename1.impl.javase.JavaSEPort$4.run(JavaSEPort.java:1720)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1056)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:873)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
[EDT] 0:0:1,396 - Codename One revisions: 14b404a993fcb91cfe25e26ce4d64ee044952b39

[EDT] 0:0:1,444 - setURLHierarchy executed
Exception in thread "JavaFX Application Thread" java.lang.IncompatibleClassChangeError
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)

The only true bad thing is that the text has a readable size using the iPhone3gs.skin, but it's very very small (quite unreadable) using other skins like SamsungS7.skin. I don't know why, I hope that the text will be correctly sized on real devices with a good-readable default font size.

Step 3: associate a command with the back button

In this case, to simplify and to test the back button, I didn't use the Javascript Bridge, but the back() method of the BrowserComponent class. I tried the Javascript Bridge in the next steps. I added at the end of the start() method of MyBrowser (just before hi.show()) this code:

hi.setBackCommand(new Command("BackButton") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            browser.back();
        }
    });

In the simulator, the hardware Back button is not reactive and no back arrow is shown in the toolbar. After several tries, I realized that the setBackCommand method is implemented in the Form class and in the Toolbar class, with different behaviors. This article explains the difference: https://www.codenameone.com/blog/toolbar-back-easier-material-icons.html

The following was the final code of this step, that worked correctly in the simulator and in my real Android device (in which I tested both the hardware back button and the material icon back arrow):

   public void start() {
        if (current != null) {
            current.show();
            return;
        }
        Form hi = new Form("MyBrowser", new BorderLayout());

        // Create the BrowserComponent
        BrowserComponent browser = new BrowserComponent();

        try {
            // Load a web page placed in the "html" package
            browser.setURLHierarchy("/index.html");
            Log.p("setURLHierarchy executed");
        } catch (IOException ex) {
            Log.e(ex);
        }

        hi.add(BorderLayout.CENTER, browser);

        Command backCommand = new Command("BackButton") {
            @Override
            public void actionPerformed(ActionEvent evt) {
                browser.back();
            }
        };

        hi.getToolbar().setBackCommand(backCommand);
        hi.show();
    }

Step 4: use the Back Button with Javascript Bridge

I changed the backCommand as follow to call a simple writeln function, but the new code worked only few times, other times it crashed the simulator or it simply did nothing:

   // Javascript Bridge
    JavascriptContext context = new JavascriptContext(browser);
    JSObject document = (JSObject)context.get("document");

    Command backCommand = new Command("BackButton") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            // browser.back();
            document.call("writeln", new Object[]{"Hello world"});
        }
    };

I have the suspect that the JavascriptContext is not loaded correctly all the times, but I'm not sure about that. The log wasn't helpful to understand the problem:

[EDT] 0:0:0,18 - setURLHierarchy executed
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f3a04f944d1, pid=3730, tid=0x00007f3a07cdf700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_144-b01) (build 1.8.0_144-b01)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.144-b01 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libjfxwebkit.so+0x11334d1]  checkJSPeer(long, int, OpaqueJSValue*&, OpaqueJSContext const*&)+0x41
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/francesco/NetBeansProjects/myBrowser/hs_err_pid3730.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Java Result: 134

After a (very very long) list of trial and errors to solve this strange behavior, finally I changed the code in a way that works correctly in the simulator and in my real Android device (note that I didn't use anymore the JavascriptContext class):

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("MyBrowser", new BorderLayout());

    // Create the BrowserComponent
    BrowserComponent browser = new BrowserComponent();

    try {
        // Load a web page placed in the "html" package
        browser.setURLHierarchy("/index.html");
        Log.p("setURLHierarchy executed");
    } catch (IOException ex) {
        Log.e(ex);
    }

    hi.add(BorderLayout.CENTER, browser);

    // Create a command for the Back button
    Command backCommand = new Command("BackButton") {
        @Override
        public void actionPerformed(ActionEvent evt) {
             browser.execute("document.writeln('Hello world!');");
        }
    };

    hi.getToolbar().setBackCommand(backCommand);
    hi.show();
}

The trick is the use of the (few documented) execute method of BrowserComponent, instead of the JavascriptContext + JSObject classes. A brief explanation of this method is inside the StackOverflow question: Clarification on Codename One's BrowserComponent execute(String javaScript) method.

Step 5: use my goBackButton() javascript function

I already had implemented the goBackButton() function in the web pages that I intend to use in my app. I want to call that method only if it's already loaded by the javascript engine, because: «BrowserComponent.execute(String) will execute the provide JS snippet in the current page of the browser at the time that you make the call. If your snippet references things that aren't loaded yet, then the javascript will result in an error.» (citation)

That's why I changed the code so:

// Create a command for the Back button
String jsCode = "function goBack() {                        "
        + "    if (typeof goBackButton == 'function') {     "
        + "        window.goBackButton();                   "
        + "    return 'I\\'m invoking goBackButton()';      "
        + "    } else {                                     "
        + "        window.history.go(-1);                   "
        + "        return 'goBackButton() is not available';"
        + "    }                                            "
        + "}                                                "
        + "goBack();                                        ";
Command backCommand = new Command("BackButton") {
    @Override
    public void actionPerformed(ActionEvent evt) {
        Log.p(browser.executeAndReturnString(jsCode));
    }
};

To do a basic test, I implemented a fake goBackButton() in page1.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script>
            function goBackButton() {
                // My js code
                // ...
                history.go(-1);
            }
        </script>
    </head>
    <body>
        <h1>Page 1</h1>
    </body>
</html>

Then I tapped the back button on page1.html and page2.html. The resulting log is as expected:

[EDT] 0:0:0,28 - setURLHierarchy executed
[EDT] 0:0:4,395 - I'm invoking goBackButton()
[EDT] 0:0:7,736 - goBackButton() is not available

Step 6: use setBrowserNavigationCallback

I used the setBrowserNavigationCallback to allow the browsing only inside my domains: in my original bugged code, I experienced that if I use JavascriptContext + JSObject classes then I have to use the condition if(url.startsWith("javascript")), because the NavigationCallback was called by tapping the back button (don't ask me why, I don't know). Instead using BrowserComponent.execute(String) I don't need to check if the url starts with "javascript", because the NavigationCallback is never called by javascript.

I added two links to index.html to do some checks:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="page1.html">Page 1</a><br />
        <a href="page2.html">Page 2</a><br />
        <a href="page3.html">Page 3</a><br />
        <a href="https://www.google.com/">WebPage 1 (domain not allowed)</a><br />
        <a href="https://www.utiu-students.net/">WebPage2 (domain allowed)</a>
    </body>
</html>

The following code seems correct, but indeed it crashed the simulator every time that I clicked on the "WebPage 1" link (that is the Google page):

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("MyBrowser", new BorderLayout());

    // Create the BrowserComponent
    BrowserComponent browser = new BrowserComponent();

    try {
        // Load a web page placed in the "html" package
        browser.setURLHierarchy("/index.html");
        Log.p("setURLHierarchy executed");
    } catch (IOException ex) {
        Log.e(ex);
    }

    hi.add(BorderLayout.CENTER, browser);

    // Create a command for the Back button
    String jsCode = "function goBack() {                        "
            + "    if (typeof goBackButton == 'function') {     "
            + "        window.goBackButton();                   "
            + "    return 'I\\'m invoking goBackButton()';      "
            + "    } else {                                     "
            + "        window.history.go(-1);                   "
            + "        return 'goBackButton() is not available';"
            + "    }                                            "
            + "}                                                "
            + "goBack();                                        ";
    Command backCommand = new Command("BackButton") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            Log.p(browser.executeAndReturnString(jsCode));
        }
    };

    hi.getToolbar().setBackCommand(backCommand);

    // Allow browsing only inside my domains
    String myDomain1 = "127.0.0.1"; // for local server (using simulator)
    String myDomain2 = "utiu-students.net";
    String myDomain3 = "login.uninettunouniversity.net";
    browser.setBrowserNavigationCallback((url) -> {
        Log.p("URL loaded: " + url);
        String domain = ""; // the domain of the url loaded by BrowserComponent
        if (url.startsWith("http")) {
            try {
                domain = (new URI(url)).getHost();
                domain = domain.startsWith("www.") ? domain.substring(4) : domain;
            } catch (URISyntaxException ex) {
                Log.e(ex);
            }
        }
        Log.p("Domain of the URL: " + domain);
        if (url.startsWith("file") 
                || domain.equals(myDomain1)
                || domain.equals(myDomain2)
                || domain.equals(myDomain3)) {
            Log.p("the BrowserComponent can navigate");
            return true; // the BrowserComponent can navigate
        } else {
            Display.getInstance().callSerially(() -> {
                // it opens the url with the native platform
                Boolean can = Display.getInstance().canExecute(url);
                if (can != null && can) {
                    Display.getInstance().execute(url);
                }
            });
            Log.p("the BrowserComponent cannot navigate");
            return false; // the BrowserComponent cannot navigate
        }
    });

    hi.show();
}

This is the log:

[JavaFX Application Thread] 0:0:2,86 - URL loaded: https://www.google.com/
[JavaFX Application Thread] 0:0:2,87 - Domain of the URL: google.com
[JavaFX Application Thread] 0:0:2,88 - the BrowserComponent cannot navigate
[JavaFX Application Thread] 0:0:3,815 - URL loaded: https://www.google.it/?gfe_rd=cr&ei=avGmWa-YNKnS8AfqlIGoDw
[JavaFX Application Thread] 0:0:3,815 - Domain of the URL: google.it
[JavaFX Application Thread] 0:0:3,815 - the BrowserComponent cannot navigate
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f3ec48044cf, pid=5754, tid=0x00007f3ec7be4700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_144-b01) (build 1.8.0_144-b01)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.144-b01 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libjfxwebkit.so+0xa9e4cf]  WebCore::ResourceLoader::willSendRequestInternal(WebCore::ResourceRequest&, WebCore::ResourceResponse const&)+0x53f
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/francesco/NetBeansProjects/myBrowser/hs_err_pid5754.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Java Result: 134

It's very bad. The strange thing is that the Google page was loaded two times, I guess because a redirect. If a replace the link to Google with a link to the Codename One website, the Simulator stops to crash... but it opens the page! So the BrowserNavigationCallBack() is not working.

I did two checks because this problem. The first one was the support for the native browser:

// Check if the native browser is supported (only for logging)
if (BrowserComponent.isNativeBrowserSupported()) {
    Log.p("Native Browser Supported");
} else {
    Log.p("Native Browser NOT Supported");
}

The second one was removing the code of BrowserNavigationCallBack() and replacing it with:

browser.setBrowserNavigationCallback((new BrowserNavigationCallback() {
    @Override
    public boolean shouldNavigate(String url) {
        Log.p("URL: " + url);
        return false;
    }
}));

The bad result was that the CodenameOne web site was still opened: the return value of shouldNavigate is ignored by the simulator (is it a bug?). This is the log:

[EDT] 0:0:0,44 - Native Browser Supported
[EDT] 0:0:0,59 - setURLHierarchy executed
[JavaFX Application Thread] 0:0:0,90 - URL: file:///home/francesco/NetBeansProjects/myBrowser/build/classes/html/index.html
[JavaFX Application Thread] 0:0:2,535 - URL: https://www.codenameone.com/

However, after several tries, I found a small workaround, that I suppose fine for the most use cases.

I added this code at the end of setBrowserNavigationCallback:

Log.p("the BrowserComponent cannot navigate");
if (Display.getInstance().isSimulator()) {
    // small workaround because the return value is ignored by the simulator
    browser.setURL("jar:///goback.html");
}
return false; // the BrowserComponent cannot navigate

I placed the goback.html outside the html package, in the /src:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>window.history.go(-1);</script>
    </head>
    <body>
        The link will be opened with an external browser.<br />
    <a href="javascript:window.history.go(-1);">Click here to go back</a>
    </body>
</html>

Now the simulator works (apparently) correctly: it seems to don't open a link to a not allowed domain... indeed it opens it for a very small while, then goes back automatically (and it opens it with an external browser, as I wanted).

There is also a very good news: do you remember that clicking the following link crashes the simulator (I reported the log above)? My workaround resolved also this issue: no crash, no strange behavior and the link is opened in an external browser.

<a href="https://www.google.com/">WebPage 1 (domain not allowed)</a><br />

The app runs correctly also in my real Android device.

This is the final code:

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("MyBrowser", new BorderLayout());

    // Create the BrowserComponent
    BrowserComponent browser = new BrowserComponent();

    // Check if the native browser is supported (only for logging)
    if (BrowserComponent.isNativeBrowserSupported()) {
        Log.p("Native Browser Supported");
    } else {
        Log.p("Native Browser NOT Supported");
    }

    try {
        // Load a web page placed in the "html" package
        browser.setURLHierarchy("/index.html");
        Log.p("setURLHierarchy executed");
    } catch (IOException ex) {
        Log.e(ex);
    }

    hi.add(BorderLayout.CENTER, browser);

    // Create a command for the Back button
    String jsCode = "function goBack() {                        "
            + "    if (typeof goBackButton == 'function') {     "
            + "        window.goBackButton();                   "
            + "    return 'I\\'m invoking goBackButton()';      "
            + "    } else {                                     "
            + "        window.history.go(-1);                   "
            + "        return 'goBackButton() is not available';"
            + "    }                                            "
            + "}                                                "
            + "goBack();                                        ";
    Command backCommand = new Command("BackButton") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            Log.p(browser.executeAndReturnString(jsCode));
        }
    };

    hi.getToolbar().setBackCommand(backCommand);

    // Allow browsing only inside my domains
    String myDomain1 = "127.0.0.1"; // for local server (using simulator)
    String myDomain2 = "utiu-students.net";
    String myDomain3 = "login.uninettunouniversity.net";

    browser.setBrowserNavigationCallback((url) -> {

        Log.p("URL loaded: " + url);
        String domain = ""; // the domain of the url loaded by BrowserComponent
        if (url.startsWith("http")) {
            try {
                domain = (new URI(url)).getHost();
                domain = domain.startsWith("www.") ? domain.substring(4) : domain;
            } catch (URISyntaxException ex) {
                Log.e(ex);
            }
        }
        Log.p("Domain of the URL: " + domain);
        if (url.startsWith("file")
                || domain.equals(myDomain1)
                || domain.equals(myDomain2)
                || domain.equals(myDomain3)) {
            Log.p("the BrowserComponent can navigate");
            return true; // the BrowserComponent can navigate
        } else {
            Display.getInstance().callSerially(() -> {
                // it opens the url with the native platform
                Boolean can = Display.getInstance().canExecute(url);
                if (can != null && can) {
                    Display.getInstance().execute(url);
                }
            });
            Log.p("the BrowserComponent cannot navigate");
            if (Display.getInstance().isSimulator()) {
                // small workaround because the return value is ignored by the simulator
                browser.setURL("jar:///goback.html");
            }
            return false; // the BrowserComponent cannot navigate
        }

    }
    );

    hi.show();
}

For reference, the final full source code of this (very small) browsing app is here: https://github.com/jsfan3/CodenameOne-Apps/tree/master/Browsing/myBrowser

Step 7: test the app with the real web content

Now it's the time to test the app with real content. I removed the files in the html packages and copied the ones that I want to use. Result: my javascript code doesn't run as expected in the simulator (maybe because the JavaFX limits), however the app initially works fine, as expected, in my real Android device. Then, after several minutes, the hardware back button stopped to work and the material left arrow icon disappeared... it's very frustrating, killing the app and rebooting the phone didn't restore the back button: I had to remove and to reinstall the app to get it working again (I'll investigate this issue in another episode, at the moment I'm not able to replicate it...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.