How Can Execute Javascript Commands via GeckoFX - c#

I try to execute a javascript command like alert('test message') via GeckoFX and C#
but I can not.
I try without results with Navigate and with ExecuteCommand
My code is
int i=0;
GeckoWebBrowser webBrowser
webBrowser.Navigate("alert('"+i.ToString()+"');");
webBrowser.ExecuteCommand("alert('" + i.ToString() + "');");
Can anyone help me?

You can use AutoJSContext to run javascript with geckofx.
Something like:
GeckoWebBrowser browser = ....;
using (AutoJSContext context = new AutoJSContext(browser.JSContext))
{
string result;
context.EvaluateScript("3 + 2;", out result)
}
See EvaluateScript unittests for more info and examples.
If you are using a super old version of geckofx you may need to get a later version - geckofx

for the new versions instead of geckoWebBrowser1.JSContext you should write geckoWebBrowser1.Window
my code is working and I've answered with sample in another old post here

You can use Navigate method to avoid AccessViolatoinException during calling document js function:
webView.Navigate("javascript:$$external.consoleLog('message text');");

Related

Why doesn't the CientScript.RegisterStartupScript method call the javascript function in Firefox?

I have a code in which I am calling the javascript function from the cs(codebehind) file using the ScriptManager.RegisterStartupScript method.
Though, this works in Google Chrome and Internet Explorer, it doesn't work in Firefox (even the latest one FF 61). But, when i replace the function name with the whole function as it is, it works in Firefox.
I have tried using all the possible alternatives Page.ClientScript, ClientScriptBlock, RegisterStartupScriptBlock etc., only in vain.
Kindly help me.
P.S: I hope I made my question clear.
Check that your javascript function call is being launched when your page has been rendered completly.
The script you are registering in
ScriptManager.RegisterStartupScript
Should be decorated inside a snippet like this:
string script= #"window.onload = function(){
// your call to the function...
};"

Using Javascript for Google Maps API from WPF

I am creating an application that interfaces with Google's Maps API v3. My current approach is using a WebBrowser control by WebBrowser.Navigate("Map.html"). This is working correctly at the moment; however, I am also aware of WebBrowser.InvokeScript(). I have seen this used to execute a javascript function, but I would like to have something like the following structure:
APICalls.js - Contains different functions that can be called, or even separated out into a file for each function if necessary.
MapInterface.cs
WebBrowser.InvokeScript("APICalls.js", args) - Or control the javascript variables directly.
I have seen the InvokeScript method used, but none of the examples gave any detail to the source of the function, so I'm not sure if it was calling it from an html file or js file. Is it possible to have a structure like this, or a similarly organized structure, rather than creating an html file with javascript in each one and using Navigate()?
Additionally, are there any easier ways to use Google Maps with WPF. I checked around, but all of the resources I found were at least 2-3 years old, which I believe is older than the newest version of the maps API.
I can't suggest a better way of using Google Maps API with WPF (although I'm sure it exists), but I can try to answer the rest of the question.
First, make sure to enable FEATURE_BROWSER_EMULATION for your WebBrowser app, so Google Maps API recognizes is it as modern HTML5-capable browser.
Then, navigate to your "Map.html" page and let it finish loading. Here's how it can be done using async/await (the code is for the WinForms version of WebBrowser control, but the concept remains the same).
You can have your APICalls.js as a separate local file, but you'd need to create and populate a <script> element for it from C#. You do it once for the session.
Example:
var scriptText = File.ReadAllText("APICalls.js");
dynamic htmlDocument = webBrowser.Document;
var script = htmlDocument.createElement("script");
script.type = "text/javascript";
script.appendChild(htmlDocument.createTextNode(scriptText));
htmlDocument.body.appendChild(script);
Then you can call functions from this script in a few different ways.
For example, your JavaScript entry point function in APICalls.js may look like this:
(function() {
window.callMeFromCsharp = function(arg1, arg2) {
window.alert(arg1 + ", " +arg2);
}
})();
Which you could call from C# like this:
webBrowser.InvokeScript("callMeFromCsharp", "Hello", "World!");
[UPDATE] If you're looking for a bit more modular or object-oriented approach, you can utilize the dynamic feature of C#. Example:
JavaScript:
(function() {
window.apiObject = function() {
return {
property: "I'm a property",
Method1: function(arg) { alert("I'm method 1, " + arg); },
Method2: function() { return "I'm method 2"; }
};
}
})();
C#:
dynamic apiObject = webBrowser.InvokeScript("apiObject");
string property = apiObject.property;
MessageBox.Show(property);
apiObject.Method1("Hello!");
MessageBox.Show(apiObject.Method2());

emulating a browser programmatically in C# / .Net

We would like to automate certain tasks in a website, like having a user 'login', perform some functionality, read their account history etc.
We have tried emulating this with normal POST/GETs, however the problem is that for example for 'login', the website uses javascript code to execute an AJAX call, and also generate some random tokens.
Is it possible to literally emulate a web-browser? For example:
Visit 'www.[test-website].com'
Fill in these DOM items
DOM item 'username' fill in with 'testuser'
DOM item 'password' fill in with 'testpass'
Click' button DOM item 'btnSubmit'
Visit account history
Read HTML (So we can parse information about each distinct history item)
...
The above could be translated into say the below sample code:
var browser = new Browser();
var pageHomepage = browser.Load("www.test-domain.com");
pageHomepage.DOM.GetField("username").SetValue("testUser");
pageHomepage.DOM.GetField("password").SetValue("testPass");
pageHomepage.DOM.GetField("btnSubmit").Click();
var pageAccountHistory = browser.Load("www.test-domain.com/account-history/");
var html = pageAccountHistory.GetHtml();
var historyItems = parseHistoryItems(html);
You could use for example Selenium in C#. There is a good tutorial: Data Driven Testing Using Selenium (webdriver) in C#.
I would suggest to instantiate a WebBrowser control in code and do all your work with this instance but never show it on any form. I've done this several times and it works pretty good. The only flaw is that it makes use of the Internet Explorer ;-)
Try JMeter, it is a nice too for automating web requests, also quite popularly used for performance testing of web sites
Or just try System.Windows.Forms.WebBrowser, for example:
this.webBrowser1.Navigate("http://games.powernet.com.ru/login");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
HtmlDocument doc = webBrowser1.Document;
HtmlElement elem1 = doc.GetElementById("login");
elem1.Focus();
elem1.InnerText = "login";
HtmlElement elem2 = doc.GetElementById("pass");
elem2.Focus();
elem2.InnerText = "pass";

Call default browser with URL and set a target

I don't know if there is a mechanism to do this: normally one would simply call process start with a URL as the string parameter - has anyone any knowlege or sugestions as to how to add a target?
Google has been singularly unhelpful or else my queries have been a tad useless.
As in the behavior you get with :
link in a new window
Try selenium and WebDriver for C#.
What is the harm in launching the default browser ?
you may do this but what if firefox is not available ! !
ProcessStartInfo proc1 = new ProcessStartInfo("firefox.exe");
proc1.Arguments = "http://www.w3schools.com/tags/att_a_target.asp";
//"http://stackoverflow.com";
Process.Start(proc1);

Parse JavaScript code in C#

I have the following JavaScript code as a string literal:
var $Page = new function()
{
var _url= 'http://www.some.url.com';
this.Download = function()
{
window.location = _url;
}
}
Is there a way I could get the value of the _url variable from my C# code? An open source library perhaps? I did this using a Regular Expression, but I was hoping for a more elegant way.
You should take a look at the open-source Javascript .NET (http://javascriptdotnet.codeplex.com/) on Codeplex.
This sample of code should help you:
Javascript context = new JavascriptContext();
context.Run("var _url= 'http://www.some.url.com';") // You put your javascript in the function run
String url = (String)context.GetParameter("_url"); // You get your url from javascript
That's it.
There is an open-source JavaScript interpreter in C# at http://jint.codeplex.com, if you need more than just getting the value.
This is now moved to GITHUB
You could execute the javascript function using the DLR and/or MyJScript.
You could use a javascript parser, but parsing javascript for just that one value is probably way overkill.

Categories

Resources