Can't click a button in WebView via Javascript in Android Studio

61 Views Asked by At

I'm creating an Android app with WebView to show a webpage. I want to link a button in my app's layout (triggerButton) to activate a button (btn1) on the webpage when pressed. However, I'm struggling to figure out how to make this work.

public class MainActivity extends AppCompatActivity {

    WebView myWeb;
    Button triggerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myWeb = findViewById(R.id.myWeb);
        myWeb.getSettings().setJavaScriptEnabled(true);
        myWeb.getSettings().setDomStorageEnabled(true);
        myWeb.loadUrl("myUrl");

        myWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                triggerButton = findViewById(R.id.triggerButton);
                triggerButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //view.evaluateJavascript("document.getElementById('btn1').style.backgroundColor = 'red';", null); //this works
                        view.evaluateJavascript("document.getElementById('btn1').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));", null); //this doesnt work
                    }
                });
            }
        });

    }

}

I can change the style of btn1 (background color) with this command:

view.evaluateJavascript("document.getElementById('btn1').style.backgroundColor = 'red';", null);

but I can't seem to press the button with the same format

view.evaluateJavascript("document.getElementById('btn1').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));", null);

At first I tested ".click()" in Chrome console, didn't work. With ChatGPT's help, used "document.getElementById('btn1').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));", which works consistently in the console, but not in my app.

I tried the exact same thing on Stackoverflow.com to click the login button, and it worked flawlessly with the same method I applied in my app. I suspect it might have something to do with the security or privacy settings of the website I'm working with (raspberry pi webiopi).

0

There are 0 best solutions below