如何处理webview中的回调 [英] How to handle callbacks in webview

查看:658
本文介绍了如何处理webview中的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在一个Android项目,并有一个问题,如何做回调在不同的网络视图。我对我的项目也使用JSInterface。这里我有2个网页视图。一个有一个索引页,另一个是一个覆盖层(仍然是一个HTML页面)。我想做的是,如果任何用户点击覆盖层上的一些链接,它应该启动一个回调函数写在java文件中的索引页通过JSInterface连接到。这可能听起来很混乱,但我已经绘制了一些东西来帮助清楚!



谢谢!

解决方案

您可以使用像myurl:功能为您的功能链接。然后为WebView的shouldOverrideUrlLoading事件编写一个事件处理程序,您可以在其中决定如何处理URL:指示Webview加载它,或者执行一些自定义操作。

  @Override 
public boolean shouldOverrideUrlLoading(WebView view,String url)
{
if(url.startsWith(myurl://))
{
//进一步解析提取函数并执行自定义操作
}
else
{
//通过webview
视图加载页面。 loadUrl(url);
}
return true;
}

我使用startsWith检查这个快速和脏的例子的URL,应该考虑使用android.net.Uri.parse解析URL。



这应该允许你调用Java函数foo(),而不必通过第一个WebView。



如果你想通过第一个webview,那么你可以这样调用JSInterface上的一个函数(其中webView1是通过findViewById检索的第一个WebView) p>

  webView1.loadUrl(javascript:myjsinterface.myjsfunc();)
pre>

I am working on an android project right now and have a question about how to do callbacks in different webviews. I used JSInterface for my project too. Here I have 2 webviews. One has an index page, anther is a overlay(still a html page though.) What I want to do is if any user clicks on some links on the overlay, it should fire a callback function which is written in the java file where the index page was connected to through JSInterface. It might sound confusing, but I have draw something to help make it clear!

Thanks!

解决方案

You can use a custom URL scheme like myurl://function for your functionality links. Then write an event handler for the WebView's shouldOverrideUrlLoading event in which you decide how to process the URL: either instruct the webview to load it, or do some custom action.

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)  
{  
    if (url.startsWith("myurl://"))  
    {  
        // Parse further to extract function and do custom action  
    }
    else  
    {  
        // Load the page via the webview
        view.loadUrl(url);  
    }  
    return true;  
}  

I used startsWith to check the URL for this quick and dirty example, but you should consider using android.net.Uri.parse for parsing URLs.

This should allow you to call the Java function foo() without having to go through the first WebView.

If you want to go through the first webview, then you can call a function on the JSInterface like this (where webView1 is the first WebView retrieved through findViewById):

webView1.loadUrl("javascript:myjsinterface.myjsfunc();")

这篇关于如何处理webview中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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