在 WebView 中注入 JavaScript onclick() 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18187654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:01:02  来源:igfitidea点击:

Injecting JavaScript onclick() event inside WebView

javascriptandroidwebviewandroid-webview

提问by Chathura Wijesinghe

I have an Android app, running a WebView that loads a certain page, and also part of the app

我有一个 Android 应用程序,运行一个加载特定页面的 WebView,也是应用程序的一部分

  1. I want to generate one of button onclick() event inside the WebView page
  2. How to load JavaScript file to WebView page which is inside the Android assets?
  1. 我想在 WebView 页面内生成按钮 onclick() 事件之一
  2. 如何将 JavaScript 文件加载到 Android 资产内的 WebView 页面?

Thanks.

谢谢。

回答by Chathura Wijesinghe

Finally I found the answer...

最后我找到了答案...

webView.loadUrl("javascript:(function(){document.getElementById('buttonClick').click();})()");

here is the complete source code

这是完整的源代码

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Huddle extends Activity {
private WebView wv;
EditText editText;
TextView textView;
Button button,buttonClick;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    editText = (EditText)findViewById(R.id.titlebar);
    textView = (TextView)findViewById(R.id.txt_html);
    button = (Button)findViewById(R.id.button);
    buttonClick = (Button)findViewById(R.id.buttonClick);

    wv = (WebView) findViewById(R.id.webview);

    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setUserAgentString("Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    wv.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

    wv.setWebChromeClient(new MyChromeClient());
    wv.loadUrl("file:///android_asset/www/index.html");
    wv.requestFocus();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String txt = editText.getText().toString();
            wv.loadUrl("javascript:sayHelloFromJS('"+txt+"')");
        }
    });
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            wv.loadUrl("javascript:(function(){document.getElementById('buttonClick').click();})()");
        }
    });
}

class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    public void showHTML(final String html)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Huddle.this.textView.setText(html);
            }
        });
    }
}

class MyChromeClient extends WebChromeClient{
}

class MyWebClient extends WebViewClient {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

    }
 }
}

index.html

索引.html

add this index.html to assets\www\index.html

将此 index.html 添加到assets\www\index.html

<html>
<script language="JavaScript">
function sayHelloFromJS(value) {
  document.getElementById("namefromAndroid").value =   value;
}

function setHtml(){
  var HTML = ""+document.getElementById("namefromjs").value;
  window.HTMLOUT.showHTML(HTML);
}

function doAlert() {
 alert("JavaScript says: Hello Android !!! How are you?");

}
</script>
</head>
<body>
 <p> Enter your name here <input type="text" id="namefromjs" />
 <p> <input type="button" onclick= "setHtml()" value="Set Name in Android">
 <p> Name from Android is <input type="text" id="namefromAndroid" />

  <p> Button Click <input type="button" value="Click me" id="buttonClick" onclick= "doAlert()" />
</body>
</html>

res\layouts\main.xml

资源\布局\ main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
    >

<TextView
        android:layout_width="184dp"
        android:layout_height="22dp"
        android:id="@+id/txt_html" android:layout_gravity="left|center_vertical"/>
<EditText
        android:layout_width="161dp"
        android:layout_height="wrap_content"
        android:id="@+id/titlebar" android:layout_gravity="left|center_vertical"/>
<Button
        android:layout_width="129dp"
        android:layout_height="wrap_content"
        android:text="Add text to web"
        android:id="@+id/button"/>
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Event"
        android:id="@+id/buttonClick" android:layout_gravity="left|center_vertical"/>
<WebView android:id="@+id/webview" android:layout_width="match_parent"
         android:layout_height="match_parent"/>
</LinearLayout>

回答by Mohamed Slimane

this is for kotlin. its working for java add (;) line end

这是针对 kotlin 的。它适用于 java add (;) 行尾

wv.loadUrl("javascript:(function() {document.querySelectorAll('.class')[0].click();})()")