如何从webView,Android中的@JavascriptInterface方法调用Javascript?

时间:2016-05-18 02:03:38

标签: javascript java android webview

以下是我的HTML网页代码:

def pdfreaddata {
driver.get("https://www....combo.pdf")
driver.manage.timeouts.implicitlyWait(50, TimeUnit.SECONDS)
val url: URL = new URL(driver.getCurrentUrl)
println(url)
val fileToParse: BufferedInputStream = new BufferedInputStream(url.openStream())
val parser: PDFParser = new PDFParser(fileToParse)
parser.parse()
val cosDocument:COSDocument  = parser.getDocument()
val pdDocument:PDDocument = new PDDocument(cosDocument)
if(pdDocument.isEncrypted()) {
  val sdm: StandardDecryptionMaterial  = new StandardDecryptionMaterial(PDF_OWNER_PASSWORD)//PDF_OWNER_PASSWORD =""
  pdDocument.openProtection(sdm) 
}
val output: String = new PDFTextStripper().getText(pdDocument)
println("pdf Value" + output)
parser.getPDDocument.close()

driver.manage.timeouts.implicitlyWait(100, TimeUnit.SECONDS)
}
}

如您所见,只有一个按钮,当我单击按钮时,它将调用@JavascriptInterface方法<script> function native_callback() { alert("Test") } </script> <button onclick='native.appVersion()'>appVersion</button> 。我想要做的是在appVersion()方法中调用javascript函数native_callback()。不幸的是,我会抓住一个java异常。

以下是我的WebView类java源代码的一部分:

appVersion()

而且,我可以从网页上抓住异常:

... // some other codes that not related getSettings().setJavaScriptEnabled(true); addJavascriptInterface(new InJavaScriptLocalObj(), "native"); ... // some other codes that not related final class InJavaScriptLocalObj { @JavascriptInterface public void appVersion() { Log.i("JsInterface","Called!") loadUrl("javascript:native_callback()"); } }

第6行是Uncaught Error: Java exception was raised during method invocation -- From line 6 of http://my web page url

顺便说一下,已经调用了鳕鱼<button onclick='native.appVersion()'>appVersion</button>,我可以看到日志。

我该怎么办?

解决方案 实际上,它必须在另一个线程中调用,但与WebView对象相同。 这是我的代码:

Log.i("JsInterface","Called!")

1 个答案:

答案 0 :(得分:6)

使用处理程序怎么样? 我检查它在我的项目中效果很好。

BP <- sort(table(A$a),decreasing=F)
BP
# Plant Letter   Tree 
#     1      2      3 

BP[1:2]
# Plant Letter 
#     1      2 

barplot(BP[1:2],main="Top Two of Ascending table",col=c("red","orange"))