在Android的单元测试中,使用java脚本从WebView中获取内容

Getting content out of WebView In a unit test Android, using java script

本文关键字:WebView 获取 脚本 使用 Android 单元测试 java      更新时间:2023-09-26

我已经能够使用javascript和loadUrl()方法从注入WebView的javascript字符串调用的接口获得内容。问题是,这只适用于我当loadUrl()方法存在于onPageFinished()方法在WebView客户端。我想做的是我想从WebView中获取内容(内容已经加载)。WebView是在一个活动仪表测试用例,我可以使用findAll()方法,这工作得很好。出于某种原因,我不能使用loadUrl()并获得所需的行为(这是注入javascript并在接口的帮助下从WebView中获取内容)。

请帮助。

感谢

编辑:只是添加代码来显示我正在做的事情:

是的,我理解,但我的问题是,我试图这样做,在一个测试用例:

public void testWebView() throws Exception {
    solo.sleep(3000); // wait for views to load on the screen
    WebView a=null;
    ArrayList<View> views = solo.getCurrentViews(); // I am using solo object to get views for the screen currently loaded
    for(View s:views)
    {
        if (s instanceof WebView)
        {
            a = (WebView)s; // this is where I get my WebView
        }
    }
    Instrumentation inst = getInstrumentation();
    inst.runOnMainSync(new Runnable()
    {
        public void run()
        {
         int d =a.findAll("something"); // this method runs fine on the object and i get the desired result
         WebSettings settings = a.getSettings(); 
         settings.setJavaScriptEnabled(true);
         a.loadUrl("javascript:document.location = document.getElementById('google').getAttribute('href')"); // this javascript is never executed and that is my problem
        }
    });

}    

你可以在加载的页面中注入javascript,就像在桌面浏览器中一样——通过在导航栏中输入内联javascript。

  1. 绑定一些Java对象,以便可以通过WebView从Javascript调用它:

    addJavascriptInterface(javaObjectExposed, "JSname")
    
  2. 在现有页面中强制执行javascript

    WebView.loadUrl("javascript:window.JSname.passData("some data from page");");