What is the process for invoking a Java function in Android from JavaScript when using Vue?

My project is developed using Vue.js. In order to view it on a mobile phone, I decided to create an Android app. To achieve this, I am using the WebView component. However, when I click on an element in the Vue.js app, JavaScript calls Java and some events should happen within the Android native app. Unfortunately, this is not working as expected. I suspect that the issue lies in injecting Java variables...

Corrected code

Java


import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void showInfoFromJs(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());

        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(this), "androidinfo");
        webView.loadUrl("https://jospro.ru/");
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

}

<!-- Vue -->

<template>
    <div class="align-items-center d-flex header-comp">
        <div class="header-title-comp pl-3">
            <div class="title-h1-comp" @click="showName">{{ loggedUser.firstname }}</div>
        </div>
        <div class="header-tarif-comp">Start</div>
    </div>
</template>

<script>    
    import { mapGetters }       from 'vuex'

    export default {
        name: 'ProfileHeader',

        computed: {
            ...mapGetters([ 'loggedUser' ])
        },

        methods: {          
            showName() {
                androidinfo.showInfoFromJs('js calls java');                
            }
        },
    }
</script>

Answer №1

Kindly exclude

view.loadUrl(url);

from the shouldOverrideUrlLoading method in MyWebViewClient and move it to onCreate after adding webView.addJavascriptInterface.

Answer №2

It is necessary for the showName function to have:

showName() {
                    window.androidinfo.showInfoFromJs('js calls java');<br>
                }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for modifying the properties of variables within an array using JavaScript

I have an array that holds variables used to control a specific template. divisionsListToManipulate: ['showActivitiesSection', 'hideAssignActionplanDiv', 'displayProp ...

Injecting dynamic variables into JSON objects using JavaScript

I am facing a challenge with populating values dynamically from an array of elements. Below is the primary array that I am working with. list = [{name: 'm1'}, {name: 'm2'},{name: 'm3'},{name: 'm4'},{name: 'm5&ap ...

What can be done to prevent an app from crashing when the device's font scale is adjusted?

As a newcomer to React Native, I have been facing a challenge with preventing my app from crashing when the system font scaling increases. Despite browsing through various answers across different platforms, I am yet to find a suitable solution. Can anyone ...

Creating a collection by compiling a selection of choices

Presently, I have a piece of code that identifies the Show id, then proceeds to locate the elements in the option tags below it and prints them out individually. WebElement dropDown = driver.findElement(By.id("Show")); List<WebElement> optio ...

choose an array consisting of spark structures

I'm facing a challenging issue as part of a complex problem I'm working on. Specifically, I'm stuck at a certain point in the process. To simplify the problem, let's assume I have created a dataframe from JSON data. The raw data looks ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

What steps are needed to access the Root in the setup function of a Vue 3 component?

I recently built a Vue App and incorporated Vuex for state management. Here is how I set up my app initially: import { createApp } from "vue"; import axios from "axios"; import App from "./App.vue"; import router from "./ ...

The ChromeDriver is experiencing difficulties in correctly switching between frames

Having trouble switching frames properly. The project is a maven project with the following pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.o ...

Tips on utilizing these styles as properties for the Vue component

Is there a way I can incorporate these styles as properties for this component? <template> <div> <transition-group name='fade' tag='div'> ... </div> </te ...

Is it possible to directly utilize functions from an imported JavaScript library, such as Change Case, within the template of a Vue component?

After successfully importing and using the Change Case library within the <script></script> element of a Vue component, I now seek to directly utilize the Change Case functions in the template itself. As of now, my understanding is that when d ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Is it possible to handle an item within a JSON as a string?

Currently, I'm tackling a Java project that involves handling JSON data structured like this: { "objectList" : [{...}, {...}, ...], "metadata" : {...} } My goal is to extract the object list and metadata as JSON strings. In essence, I ...

Looking for an efficient method to initiate vagrant configuration seamlessly with just a click?

When setting up different VirtualBoxes on Linux, I rely on using vagrant. My objective is to simplify the process for my colleagues by allowing them to visit an intranet site where they can choose which VirtualBox they would like installed on their machin ...

Tips for launching a React Native application with a Node.js backend on an Android device?

Currently, I'm facing an issue while trying to run my React Native app on my local Android Device. The app utilizes Node.js APIs to retrieve data from a MySQL database. However, the problem arises when my Android device is unable to access the Node.js ...

"Linking a mouse click event to a specific function within an array using

I'm faced with an issue while trying to bind a click function from an array in my code. It's not responding as expected. Here is a simple example that illustrates the problem: What can I do to solve this issue? var app = new Vue({ el: &apo ...

What is the best method to retrieve the v-model values of v-for components when iterating with numeric indices?

Within my template, I have form-group components that are being iterated over based on the value of a select element (an integer). My goal is to access the values of these iterated v-models, but I am struggling to get it right. TEMPLATE <b-form-g ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

Utilizing Cypress with Electron: A Guide to File System Operations

I have been utilizing Cypress to run tests on my Electron application. Due to Cypress operating in browser mode, the FS module is not compatible. As a result, I am encountering this error: Error in mounted hook: "TypeError: fs.existsSync is not a func ...