wpf的webbrowser與javascript互動
阿新 • • 發佈:2020-07-14
JS呼叫C#程式碼
HTML程式碼:
<button onclick="window.external.Test('called from script code')">
call client code from script code
</button>
WPF程式碼中的C#程式碼:
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
WPF和JavaScript之間的通訊需要完全信任,因此您需要新增以下程式碼:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class MainWindow
{
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
}
也經常這麼幹
//webbrowser設定一個腳本回調的上下文 mywebbrowser.objectForScription = nwe scriptCallBackContext();
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public calss scriptCallBackContext
{
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
}
c#呼叫 JS方法
private void Window_Loaded(object sender, RoutedEventArgs e) { string curdir = Directory.GetCurrentDirectory(); webBrowser.Navigate(String.Format("file:///{0}/test.html", curdir)); webBrowser.LoadCompleted += (ss, ee) => { var jsCode = "fillData('data...');"; dynamic doc = webBrowser.Document; webBrowser.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" }); }; }
myscripts.js:
function fillData(data)
{
//document.getElementById("uname").value = data;
var oVDiv = document.getElementById("uname");
//oVDiv.setAttribute("vaue", data);
oVDiv.value = data;
//oVDiv.value = data;
//document.write(data);
}