Android的注入在web视图外部JS,执行功能,并发出警报 [英] Android Inject in webview external js, execute function, and raise an alert

查看:154
本文介绍了Android的注入在web视图外部JS,执行功能,并发出警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在web视图注入外部JavaScript并执行它的功能之一执行()。完成后引发警报和字符串返回到活动
这就是我如何做到这一点,但它似乎没有工作(的JS已经测试过)

I want to inject an external javascript in webview and execute one of its functions execute(). After completion an alert is raised and the string returns to the activity
this is how I do it but it doesn't seem to work (the js is already tested)

view.loadUrl(JavaScript的:(函数(){VAR脚本= document.createElement方法('脚本'); script.type =文/ JavaScript的; script.src =+ jsFileURL +,+ "document.getElementsByTagName('head').item(0).appendChild(script);window.HTMLOUT.showHTML(execute());})()");

这是我如何实现HTMLOUT,而警报overrided在ChromeClient

this is how I implement HTMLOUT, while the alert is overrided in ChromeClient

browser.addJavascriptInterface(新MyJavaScriptInterface(),HTMLOUT); browser.setWebViewClient(新mWebViewClient()); browser.setWebChromeClient(新mChromeClient()); browser.loadUrl(文件:/// android_asset / Travian世界comx2b.htm);

推荐答案

好了很多很多的尝试之后我发现了一个解决办法,但遗憾的是没有的解决方案。我用这个负载 view.loadUrl(JavaScript的:+ SRC +执行();+); 而源 SRC 来自一个文本文件的script.js ,其中包括我的JavaScript(包括功能和普通的命令)

Ok after many many attempts I found a workaround, but unfortunately not the "solution". I used this load view.loadUrl("javascript:" + src + " execute(); " + ""); while the source src comes from a text file script.js which includes my javascript (both functions and plain commands)

//get script
InputStream is;
        String src= "";
        try {
            is = getAssets().open("travianbot.js");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            src = new String(buffer);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

在的script.js的样本(要小心行结束;)

a sample of the script.js (be careful on line endings ";")

function addItem(v, link, x, y, result) {
    //function commands  
}
function popup() {
    alert(execute().split("@"));
}     
function execute(){  
    //function commands
    additem(...);
}
// plain commands
.......

有关远程脚本,我没有测试过一项决议,是解析远程脚本(如为InputStream的),然后把它列入为纯文本。

One resolution for a remote script, which I haven't tested it, is to parse the remote script (e.g. as inputstream) and then included it as plain text.

这篇关于Android的注入在web视图外部JS,执行功能,并发出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆