How to pass inputs to javascript functions with cefsharp
Asked Answered
G

3

7

I am trying to add a CefSharp WebView to my WPF application in place of the original WebBrowsers that we used. The WebBrowser has an InvokeScript function (http://msdn.microsoft.com/en-us/library/cc452443(v=vs.110).aspx) Which allows you to invoke a JavaScript function and optionally pass in an obj array of inputs to that JS function.

Is there any way to do something similar with the CefSharp WebView where I can pass input parameters to the JavaScript function? For example, I can do:

this.webBrowser.InvokeScript("scriptName", input0, input1, input2);

with the WebBrowser, is there any equivalent function, or multiple functions, that would allow for this with the CefSharp WebView?

Gaut answered 12/8, 2014 at 16:32 Comment(1)
I also realized that another difference is that WebBrowser.InvokeScript is designed to take a JS function name and inputs while WebViewer.Evaluate/ExecuteScript are designed to take the full script.Gaut
G
5

I figured out how to do what I wanted... and it was relatively straightforward.

If you want the functionality of the WebBrowser's InvokeScript function

this.webBrowser.InvokeScript("functionName", input0, input1, input2);

with the CefSharp WebView then you just have to do something like this:

webView.ExecuteScript(String.Format("functionName({0},{1},{2});", input0, input1, input2));

You will have to make sure to escape any string parameters correctly since you are calling a javascript function where the inputs will be filled in with your values and therefore will be treated as string literals.

If you really don't want to change your code and you are swapping out the WebBrowser with a WebView then you could make an extension method that adds "InvokeScript" to the WebView.

Gaut answered 12/8, 2014 at 22:28 Comment(1)
Moving this from the solution below by @XiaoXiao Zhang: For string inputs, need to put single or escaped double quotes on the placeholders, e.g. webView.ExecuteScript(String.Format("functionName('{0}','{1}','{2}');", input0, input1, input2));Juice
P
3

I tried out above function, didn't work. Finally figured it out, missing quotes for each placeholders.

Something like this:

webView.ExecuteScript(String.Format("functionName('{0}','{1}','{2}');", input0, input1, input2));
Perreira answered 25/5, 2015 at 6:34 Comment(1)
It depends on your inputs. My inputs were numerical so I didn't need the quotes but if you have string inputs then you will need to make sure that they are formatted appropriately (with single or escaped double quotes).Gaut
T
2

You can execute JavaScrip from webView

webView.ExecuteScript("document.getElementById...");
Tom answered 12/8, 2014 at 16:45 Comment(1)
yes, I saw that, but specifically I need to pass inputs to the javascript function. Question edited for clarification.Gaut

© 2022 - 2024 — McMap. All rights reserved.