码迷,mamicode.com
首页 > 编程语言 > 详细

wpf的webbrowser与javascript交互

时间:2019-02-22 11:52:02      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:button   通信   invoke   ecs   js调用   data   called   nav   loaded   

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);
}

 

wpf的webbrowser与javascript交互

标签:button   通信   invoke   ecs   js调用   data   called   nav   loaded   

原文地址:https://www.cnblogs.com/nocanstillbb/p/10417246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!