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

Based on this solution, I tried to call a JavaScript function located in my WebBrowser . .xaml as follows

 <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 ''

and 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 the job.

What am I missing?

Thank you for your help.

+5
source share
1 answer

Try the following:

 browser.NavigateToString("<html><script>function callMe() {alert('Hello');} document.myfunc = callMe;</script><body>Hello World</body></html>"); browser.LoadCompleted += (s,e) => browser.InvokeScript("callMe"); 
+1
source

Source: https://habr.com/ru/post/1267180/


All Articles