[Xamarin] 透過Native Code呼叫 JavaScript function
2013-09-27
上一篇我們聊到WebView Javascript with JQuery Call Native. 我們透過Javascript 來呼叫Native 的部分,這一篇我們來聊一下,關於如何在Native 中呼叫 Javascript的部分
首先,我們要參考這篇文章(使用Webview 來做APP)來建置WebView ,這邊我就不贅述了。
1.首先,我們來看看Layout部分 /Resources/Layout/Main.axml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<WebView
android:id="@+id/webviewMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:text="呼叫Javascript function"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btnCallJS" />
</LinearLayout>
預覽:
下面那一顆button(btnCallJS) 是原生的按鈕,按下去後,會呼叫在 WebView 中的Javascript function
2.製作我們來製作關於WebView 裡面的html 部分:
<html>
<head>
<title>測試從Native呼叫Javascript</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>1:2:3: </head>4: <body>5:6: <img src="no2don.jpg" id="img1" style="width: 200px" />7: <br />8: <span id="spanContent"></span>9:10: <script>11:12: //設計給 Native 呼叫13: //傳入的str 會顯示在spanContent 中14: function SetSpanContext(str) {15: $('#spanContent').html(str);16: }17:18:</script>
</body>
</html>
其中我設計一個 function 為 SetSpanContext 這樣 傳入一string 我在js code 中會將native 傳入的string 放入置 spanContent 這span 裡面
3.現在就來看Activity 中怎麼呼叫了
using System;using Android.App;using Android.Content;using Android.Runtime;using Android.Views;using Android.Webkit;using Android.Widget;using Android.OS;namespace NativeCallJavascript{[Activity(Label = "從Native呼叫Javascript", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{WebView webviewMain;
protected override void OnCreate(Bundle bundle)
{ base.OnCreate(bundle); // Set our view from the "main" layout resourceSetContentView(Resource.Layout.Main);
webviewMain = FindViewById<WebView>(Resource.Id.webviewMain);
//啟用Javascript Enable webviewMain.Settings.JavaScriptEnabled = true; // 請注意這行,如果不加入巢狀Class 會必成呼叫系統讓系統來裁決開啟http 的方式 webviewMain.SetWebViewClient(new CustWebViewClient()); //載入網址 //因為是這支app 裡面的網址 所以呼叫 file:///android_asset/檔案名稱 webviewMain.LoadUrl("file:///android_asset/index.html");var btnCallJS = FindViewById<Button>(Resource.Id.btnCallJS);
btnCallJS.Click += delegate {webviewMain.LoadUrl("javascript:SetSpanContext(\"" + "您好,我來自於Native Code." + "\")");
};
}
/// <summary> /// 巢狀Class 繼承WebViewClient /// </summary>private class CustWebViewClient : WebViewClient
{public override bool ShouldOverrideUrlLoading(WebView view, string url)
{view.LoadUrl(url);
return true;
}
}
}
}
其中最重要的就是紅色字那一行,請記住一定要在 LoadUrl後 該網頁後呼叫,這時候直接呼叫該網頁的javascript 即可。
結果:
按下button前:
按下button後:
很簡單的範例,給有需要的人參考看看
source:
