get javascript variable into webbrowser control winforms
InvokeScript will return the value which the javascript function returns. You just need to be a bit careful about it's type. Numbers and strings will be returned a c# strings.
Modifying Javascript Variables Within A WebBrowser Control
You can inject any JavaScript code using JavaScript's eval, it works with any IE version. You'd need to make sure the page has at least one <script>
tag, but this is easy:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call WebBrowser1.Navigate("http://example.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'
' use WebBrowser1.Document.InvokeScript to inject script
'
' make sure the page has at least one script element, so eval works
WebBrowser1.Document.Body.AppendChild(WebBrowser1.Document.CreateElement("script"))
WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { window.newDate=new Date('03 Oct 2013 16:04:19'); })()"})
Dim result As String = WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { return window.newDate.toString(); })()"})
MessageBox.Show(result)
End Sub
End Class
Alternatively, you can use VB.NET late binding to call eval
directly, instead of Document.InvokeScript
, which might be easier to code and read:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call WebBrowser1.Navigate("http://example.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'
' use VB late binding to call eval directly (seamlessly provided by.NET DLR)
'
Dim htmlDocument = WebBrowser1.Document.DomDocument
Dim htmlWindow = htmlDocument.parentWindow
' make sure the page has at least one script element, so eval works
htmlDocument.body.appendChild(htmlDocument.createElement("script"))
htmlWindow.eval("var anotherDate = new Date('04 Oct 2013 16:04:19').toString()")
MessageBox.Show(htmlWindow.anotherDate)
' the above shows we don't have to use JavaScript anonymous function,
' but it's always a good coding style to do so, to scope the context:
htmlWindow.eval("window.createNewDate = function(){ return new Date().toString(); }")
MessageBox.Show(htmlWindow.eval("window.createNewDate()"))
' we can also mix late binding and InvokeScript
MessageBox.Show(WebBrowser1.Document.InvokeScript("createNewDate"))
End Sub
End Class
access global javascript variable in c# webbrowser
Does giving the hidden field an id and calling this work? mapWebBrowser.Document.GetElementById("distance").InnerHtml
(where distance is the id)
C# - Get variable from webbrowser generated by javascript
I found easy solution. Just finding the right part of string in HTML code:
foreach (HtmlNode link in root.SelectNodes("//script"))
{
if (link.InnerText.Contains("+a+"))
{
string[] strs = new string[] { "var a='", "';document.write" };
strs = link.InnerText.Split(strs, StringSplitOptions.None);
outMail = System.Net.WebUtility.HtmlDecode(strs[1]);
if (outMail != "")
{
break;
}
}
}
Make javascript variable global scope in C# web browser
You still can use Visual Studio Debugger to debug JavaScript in a custom application hosting the WebBrowser
control, as described here.
Another option is to type and execute WebBrowser.InvokeScript
(WPF) or WebBrowser.Document.InvokeScript
(WinForms) directly from the debugger's QuickWatch window.
E.g., set a variable:
webBrowser.InvokeScript("execScript", "window.myGlovalVar = myLocalVar")
Query it later (will return the value myLocalVar
remembered above):
webBrowser.InvokeScript("eval", "window.myGlovalVar")
WPF Webbrowser with javascript use variable defined in c#?
The easiest solution i found is to invoke a javascript function with paramaters to update my graph and pass a serialised array as parameter
HTML :
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
function UpdateGraph(json) {
var data = JSON.parse(json);
// Update My Graph with new data
// This allow me to use data like the serialised array - data[0] ...
}
</script>
C# :
Added System.Web.Extension in référence to do script sérialisation
private void UpdateValueInJavascriptGraph()
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(MyArrayOfData);
object result = this.WBTimeGraph.InvokeScript("UpdateGraph", new object[] { json });
}
Pass value from JavaScript to VBA using Web Browser
For your userform:
'You don't need a separate class if you're working in an
' "object" module (a form or sheet module for example)
Private WithEvents txt As MSHTML.HTMLInputElement
'This is triggered when the 'onchange' event fires for
' the input in the hosted webbrowser control
Private Function txt_onchange() As Boolean
MsgBox "Value from web page:" & txt.Value
End Function
Private Sub UserForm_Activate()
Dim html As String
Dim i As Integer
With Me.wb1
.Navigate "about:blank"
WaitFor wb1
html = "<html><body>"
For i = 1 To 5
html = html & "<a href='#' id='txtHere' " & _
"onclick='SendVal(this);return false;'>Value " & i & "</a><br>"
Next i
html = html & "<input type='hidden' id='txtOutput' size='10'>" 'for sending data out
html = html & "<script type='text/javascript'>"
'set the input value and trigger its change event
html = html & "function SendVal(el) {var txt=document.getElementById('txtOutput');" & _
"txt.value = el.innerText;txt.fireEvent('onchange');}"
html = html & "</script></body></html>"
.Document.Open "text/html"
.Document.Write html
.Document.Close
WaitFor wb1
Set txt = .Document.getElementById("txtOutput") 'set up event capture
End With
End Sub
'utility sub to ensure page is loaded and ready
Sub WaitFor(IE)
Do While IE.ReadyState < 4 Or IE.Busy
DoEvents
Loop
End Sub
Retrieve return value of a Javascript function in the WebBrowser control in vb6
- Assign return value of your JavaScript function to JavaScript variable.
- Use
execScript
method ofWebBrowser.Document.ParentWindow
to
call your JavaScript code. Now retrieve value of the variable via
WebBrowser.Document.Script.<JavaScript variable name, case-sensitive>
in VB6.Private Sub cmdJsFunc_Click()
Dim retVal As String
Call WebBrowser1.Document.parentWindow.execScript("v = function(){return 3.14;}; tempJsVar=v();")
retVal = WebBrowser1.Document.Script.tempJsVar
MsgBox retVal
End Sub
Related Topics
Code with Undefined Behavior in C#
Is There Pointer in C# Like C++? Is It Safe
Mono: Is Remote Debugging Possible with Monodevelop
C#: Referencing or Using .So Files in .Net Core on Linux
Plink Returning Unwanted Characters via C#
Compiling C# + Wpf on Linux in Order to Run on Windows
String.Format Alternative in C++
Why Can't Reference to Child Class Object Refer to the Parent Class Object
How to Get The Checkboxlist Selected Values, What I Have Doesn't Seem to Work C#.Net/Visualwebpart
Scraping Data Dynamically Generated by JavaScript in HTML Document Using C#
How to Share an Enum Declaration Between C# and Unmanaged C++
How to Password Encrypt SQLite Database
Why Can't I Retrieve an Item from a Hashset Without Enumeration
How to Determine a Timezone by The Utc Offset