Javascript Android Webview触摸内容
我想以字符串形式获取我在webview中触摸到的标签的内容 假设我有5个段落,我触摸其中一个段落,然后我想要那个段落的内容是字符串。 我怎样才能做到这一点?Javascript Android Webview触摸内容,javascript,android,Javascript,Android,我想以字符串形式获取我在webview中触摸到的标签的内容 假设我有5个段落,我触摸其中一个段落,然后我想要那个段落的内容是字符串。 我怎样才能做到这一点? 谢谢这很简单,但您需要分部分完成,并且需要JavaScript 1.-在webview中启用JavaScript web.getSettings().setJavaScriptEnabled(true); //"web" is the object of type WebView 2.-在WebView和Html之间创建JavaScrip
谢谢这很简单,但您需要分部分完成,并且需要JavaScript 1.-在webview中启用JavaScript
web.getSettings().setJavaScriptEnabled(true); //"web" is the object of type WebView
2.-在WebView和Html之间创建JavaScript接口
public class JavaScriptInterface {
private Handler myHandler = new Handler();
public void getParagraph(final String paragraph){
myHandler.post(new Runnable() {
@Override
public void run() {
//Do something with the String
}
});
}
}
注意:在方法运行中,您将使用从Html检索的字符串添加需要处理的任何内容。该类可以在创建WebView的类中创建,如果要从其他活动中使用相同的行为,则可以作为单独的类创建
3.-将界面发送到WebView
web.addJavascriptInterface(new JavaScriptInterface(), "android");
/* In this case "android" is the name that you will use from the Html to call
your methods if is not too clear yet, please keep reading */
4.-您需要将onClick事件处理程序添加到每个p标记中
<p onclick="android.getParagraph(this.innerText);">Text inside the paragraph</p>
/*android was the name we set for the interface in step 3, getParagraph is the name
of the method created on step2,"this.innerText" retrieves the text inside the paragraph*/
段落内的文本
/*android是我们在步骤3中为接口设置的名称,GetParague是名称
在步骤2创建的方法中,“this.innerText”检索段落内的文本*/
注意:您在我的示例中看到的所有名称都可以更改,但是如果您更改java类的名称,请记住更改html中的所有调用我确实阅读了文档。但是我只使用过一次这个方法,它是为了一些稍微不同的东西,我想当类型为
UNKNOWN\u type
时,额外的可能包含段落字符串。但我没有时间来测试这个理论,所以我想我会和OP分享它,以防它能帮助他们。不管是谁,这看起来是一个很好的解决方案,谢谢分享。你的欢迎,我知道你这么做是出于好意:D