Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when calling Javascript function located in WPF WebBrowser Control from C# code

Tags:

javascript

c#

wpf

Based on this solution i tried to call a JavaScript function located in my WebBrowser - control. The .xaml looks like this

<Grid>
    <WebBrowser x:Name="browser"/>
</Grid>

But neither this code

public MainWindow()
{
   InitializeComponent();
   browser.NavigateToString("<html><script>function callMe() {alert('Hello');} document.myfunc = callMe;</script><body>Hello World</body></html>");
   dynamic doc = browser.Document;
   doc.myfunc();
}

Error

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''mshtml.HTMLDocumentClass' does not contain a definition for 'myfunc''

nor this Code

public MainWindow()
{
    InitializeComponent();
    browser.NavigateToString("<html><script>function callMe() {alert('Hallo');}</script><body>Hello World</body></html>");
    browser.InvokeScript("callMe");
}

Error

System.Runtime.InteropServices.COMException: 'Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))'

do work.

What am I missing?

like image 818
Torben Avatar asked Oct 17 '22 13:10

Torben


1 Answers

Try this:

browser.NavigateToString("<html><script>function callMe() {alert('Hello');} document.myfunc = callMe;</script><body>Hello World</body></html>");
browser.LoadCompleted += (s,e) => browser.InvokeScript("callMe");
like image 89
mm8 Avatar answered Oct 30 '22 22:10

mm8