記錄一下如何在 WebView 中加入一個 JavaScript Method 並讓網頁回傳參數給 App…
WebView 的使用範例在以前的文章有出現過…
網路上也有不少範例可以看…所以僅簡單的記錄在 WebView 中新增一個 JsCallBack 物件…
並且讓顯示的網頁可以直接使用該物件內的 Method…
public class MainActivity extends Activity
{
public Handler mHandler = new Handler();
public WebView m_wv;
public TextView m_lbl;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_wv = (WebView)findViewById(R.id.webview);
m_lbl = (TextView)findViewById(R.id.lbl);
WebSettings webSettings = m_wv.getSettings();
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
JsCallBack pCallBack = new JsCallBack();
m_wv.addJavascriptInterface(pCallBack, "JsCallBack");
}
@Override
public void onStart()
{
super.onStart();
m_wv.loadUrl("http://aaa.bbb.ccc/ExtObjTest.html");
}
private class JsCallBack
{
public void ResponseResult(final String result)
{
mHandler.post(new Runnable()
{
@Override
public void run()
{
m_lbl.setText("Web Response :: " + result);
}
});
}
}
}
以下是 ExtObjTest.html 的內容…
<html>
<head>
<script type="text/javascript">
<!--
function Response()
{
JsCallBack.ResponseResult(document.getElementById('resParam').value);
}
//-->
</script>
</head>
<body>
<input type="text" id="resParam" value="Ascii"/>
<br><br>
<!-- 按下按鍵後 App 內的 TextView 即會顯示 Web Response :: Ascii -->
<input type="submit" value="Send to Client" onclick="Response();"/>
</body>
</html>
Howdy would you mind letting me know which webhost you're utilizing?
回覆刪除I've loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot
faster then most. Can you suggest a good hosting provider at a honest price?
Many thanks, I appreciate it!
Feel free to visit my homepage: How Much Do Optometrists Work