【问题标题】:Inject javascript with jquery in webview android在 webview android 中使用 jquery 注入 javascript
【发布时间】:2020-03-05 15:43:57
【问题描述】:

我想在 android WebView 中使用 jquery 注入一些 javascript 函数。

我真正想做的是, 我在 android WebView 中加载了一个 URL,并且我想用我已经拥有的 jquery 注入一些 javascript 函数。

我不想用 javascript 添加任何 HTML。

下面的函数,我想在WebView中注入。

$("form").each(function (index) {
        $(this).find("input").not(":input[type=radio]").not(":input[type=checkbox]").each(function (index) {
//enter code here
            });
    });

【问题讨论】:

    标签: android android-webview


    【解决方案1】:
                       webView.settings.javaScriptEnabled = true
                       webView.webViewClient = object : WebViewClient() {
                          override fun onPageFinished(view: WebView, url: String) {
                            injectJS()
                         }
                       }
                       webView.loadUrl("https://www.google.com")
    
    
    
    
    
    >   **We will use JavaScript to change some of the UI properties for
    > google.com website, so the obvious thing we need to do is to allow
    > webView to use JavaScript.**
    
    
            function () {
              document.getElementById("hplogo").src = "https://android.com.pl/images/user-images/2017/03/android-developer2.png";
              document.bgColor = "#454343";
              document.getElementById("lst-ib").value = "Some random text";
            }
    

    我们的JS函数真的很简单。使用 DOM 可以改变一些 几行代码中的网站属性!在Java中我们通常使用 这用于读取 XML 文件,但如果您不熟悉它 - 请检查 本教程。在网站之后调用injectJS() 非常重要 已满载,因为在这种情况下 JS 函数是基于已经 创建网站的元素。但是,这并不妨碍您 使用 jQuery 或您熟悉的任何其他 JS 框架。

            private fun injectJS() {
                    try {
                        val inputStream = assets.open("style.js")
                        inputStream.bufferedReader().use(BufferedReader::readText)
                    } catch (e: Exception) {
                        null
                    }?.let { webView.loadUrl("javascript:($it)()")  }
                }
    
    

    【讨论】:

    • 这注入了纯javascript函数。检查我更新的问题。
    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多