简体   繁体   中英

Cannot get javascript innerHtml to work on WebView

I am using a WebView with a javaScript interface. All I want to do is change the inner html of a span if some checkboxes are ticked.

Below is a snippet of a String I have in strings.xml. The form will call this function onSubmit and should not continue if it does not pass. The problem is that I can't get the innerHtml working (is returns true everytime).

This works

<script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        return javaInterface.checkboxPass();
        /*
        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;
        */
    }
</script>

This returns true everytime

<script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        var passed= javaInterface.checkboxPass();

        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;

    }
</script>

This is the span in the body of the document

<span id=\"txtInstructions\">%1$s</span>

What am I doing wrong?

I can't tell why the code doesn't behave like you want it to, but I can tell that you are trying to do this in a way too complicated fashion. Storing your JavaScript and HTML in an XML file seems like a genuine bad idea. I guess it is legal JavaScript, but naming a variable the same as it's parent function just seems wrong, in general you shouldn't use such scope subtleties, it's good for nothing but obfuscation.

I still think that your method is returning something that isn't strictly a boolean. I would try doing something like this:

<script type="text/javascript" language="javascript">
function pass() {
    var passed= javaInterface.checkboxPass();

    if(JSON.parse(passed)) {
        //change the instructions
        document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
    }

    return passed;

}
</script>

This will rule out the possibility of the "boolean" being wrapped in quotes or something else lame. If this truly is a Java interface, it probably is converting the boolean to a string.

I don't think that booleans can be passed as real boolean values, especially since javascript and java work differently under the hood. You could use eval, but it's not good practice because if it were a function, it would run it.

IE doesn't have an parse function, so you'll have to use this:

https://github.com/douglascrockford/JSON-js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM