C# - Using Awesomium to Interact with Gmail - c#

I'm able to navigate to gmail, but then I want to do something as simple as enter the credientials and click the login button.
private void btnSubmit_Click(object sender, EventArgs e)
{
btnSubmit.Enabled = false;
webGmail.LoadURL("http://www.gmail.com");
webGmail.LoadCompleted += ExecuteSomething;
}
private void ExecuteSomething(object sender, EventArgs eventArgs)
{
webGmail.ExecuteJavascript(#"<script src = 'http://code.jquery.com/jquery-latest.min.js' type = 'text/javascript'></script>");
webGmail.ExecuteJavascript(#"$('#Email').val('foo');");
webGmail.ExecuteJavascript(#"$('#Passwd').val('bar');");
webGmail.ExecuteJavascript(#"$('#signIn').click();");
}
Nothing happens. I know using developer tools with Chrome that you cant modify anything on the page. But is there a way of filling in forms?
Are there any other better headless browsers? I actually need one that supports a web control that I can put into my form so that I can see what is going on. This is mandatory

The problem is that the script tag is not javascript - it's HTML - so executing it as javascript will just throw an error. To load a script with the ExecuteJavascript method, you'd need to create a script element in javascript and inject it into the page head.
See here for an example:
http://www.kobashicomputing.com/injecting-jquery-into-awesomium

I recently came across a similar problem. I tried cefsharp, awesomium, open-webkit-sharp, geckofx. The most advanced was, oddly enough, WebBrowser. It allows you to perform almost all activities directly with C#. For example, click on a submit button in C# you could only in WebBrowser. If you still want to use an alternative engine, I recommend the open-webkit-sharp - it is the most advanced of them (although it has the same problem with the click of buttons).

WatiN has an Javascript implementation for Webkit, which Awesomium is based on, the source code is free and can be downloaded at their homepage. Good luck.
Maybe this question could help you too, calling Javascript from c# using awesomium.

Related

Awesomium: Execute javascript, click on element

I'm trying to execute some piece of javascript in my awesomium WebControl wb.
An element exampleDiv shall be clicked when the user clicks on a button on my GUI.
private void button_Click(object sender, RoutedEventArgs e)
{
if (wb.IsDocumentReady)
{
wb.ExecuteJavascript("document.getElementById('exampleDiv').click();");
}
}
If I execute this piece of javascript in Chrome everything works fine.
If I execute this in awesomium nothing happens.
Simple things like alert('Hello'); works fine but I didn't get anything else to work.
I also found this article executing javascript in awesomium to click on a div but it didn't help too.
I'm using the latest awesomium build (1.7.3).
I'm not certain if the issue is the version of chrome loaded with 1.7.3 or if its something else however i think what you should be doing is this:
document.getElementById('exampleDiv').onclick()
I tested something similar to your example with 1.7.3 using the attached debugger and i got the error:
TypeError: Object #<HTMLSpanElement> has no method 'click'
That span has a wired click event on it, and i can trigger it using:
document.getElementById('mySpan').click()
with chrome, but had to use .onclick() in awesomium.
Testing the same in the current version of chrome it works just fine. My guess is its most likely chrome 18, but I do not have the time at the moment to install it and verify.
If you are using jQuery then you could also use $('#exampleDiv').click();
You can simply do this
dynamic submit = document.getElementById("exampleDiv");
submit.Invoke("click");
and this piece of code will be inside webcontrol -> loadingframeComplete section. Works 100% for me.

Deciding whether javascript is disabled/enabled and execute a server side code [duplicate]

This question already has answers here:
redirect to another page if javascript is disabled [duplicate]
(5 answers)
Closed 2 years ago.
I've an aspx page which loads several images after detecting client's screen size. Here is how I do this:
In jquery code, I first detect user screen size, then depending on the size, I do some calculations to decide the number of images to be fetched from database. Then with the use of jquery ajax, I call up a web service which returns json response. Code picks up json and creates page.
Now, if user has disabled javascript, this approach doesn't work. Now I have to create page using c# code on code behind. The problem is, I can't detect if javascript is disabled from code behind (I think this is not possible). I do not want to display a button at the top says something "Javascript is disable in your browser. Please click here to display this page". I can put this button in noscript tags. But I do not want user have to click a button before seeing images on page.
What I want, if javascript is disabled, system should detect it and immediately run a function from code behind. (IN this case page size would be fixed and won't vary according to user screen) I can not use a hidden field or cookie to detect it since they both will need a postback before detecting javascript is diabled. (We know that js code can't run before any page life-cycle event).
Well I don't have much hope that my problem could be resolved, but still I want to give it a try. May be someone already have a solution. It would be extremely helpful if you could give your views or suggestion to change/update logic.
Any help would be greatly appreciated.
Thanks and Regards
Praveen
1.) Use JavaScript to set a cookie, and then test for that cookie using server-side scripting upon subsequent page views; deliver content appropriately.
How to detect if JavaScript is disabled?
2.) You can use <noscript> tag.
The <noscript> tag: can be used to provide an alternate content for users that have disabled scripts in their browser or have a browser that doesn’t support client-side scripting.
<noscript>
....
</noscript>
3.) Detect if JavaScript is enabled in ASPX
protected void Page_Load(object sender, EventArgs e)
{
if (Session["JSChecked"] == null)
//JSChecked -indicates if it tried to run the javascript version
{
// prevent infinite loop
Session["JSChecked"] = "Checked";
string path = Request.Url + "?JScript=1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='" + path + "';", true);
}
if (Request.QueryString["JScript"] == null)
Response.Write("JavaScript is not enabled.");
else
Response.Write("JavaScript is enabled.");
}
Make default version without javascript and redirect to javascript version if javascript enabled. How to redirect if javaScript is disabled?

Webbrowser, scripts and possible alternatives

I have a situation where a rather clever website updates the latest information on the site via Shockwave Flash through a TCP connection. The data received is then updated onto the page via JavaScript so in order to get the latest data a browser is required. If attempts are made to hit the website with continual requests then a) you get banned and b) you're not actually getting the latest data, only the last updated base framework.
So I need to run a browser with scripts enabled.
My first question is, using the standard WPF WebBrowser in .NET I get the following warnings which I don't get in standard IE, Chrome or Firefox. What is causing this and how do I supress/allow it but still allowing scripts for the site to be run?
My second question relates to is there a better way do to this or are there any better alternatives to the WebBrowser control that will
Allow scripts to run
can access the DOM or html and scripts returned in at least text format
is compatible with WPF
can hide the browser as I don't actually want it displayed.
So far I've looked into WebKit.NET which doesn't seem to allow access to the DOM and didn't like WPF windows when I tested and also Awesomium but again didn't appear to allow direct access to the DOM without javascript.
Are there any other options (apart from hacking their scripts)?
Thank you
set WebBrowser.ScriptErrorsSuppressed = true;
Ultimately I ended up keeping the WPF control and used this code to inject a JavaScript script to disable JavaScript errors. The Microsoft HTML Object Library needs to be added.
private const string DisableScriptError = #"function noError() { return true;} window.onerror = noError;";
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
InjectDisableScript();
}
private void InjectDisableScript()
{
HTMLDocumentClass doc = webBrowser1.Document as HTMLDocumentClass;
HTMLDocument doc2 = webBrowser1.Document as HTMLDocument;
IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT");
scriptErrorSuppressed.type = "text/javascript";
scriptErrorSuppressed.text = DisableScriptError;
IHTMLElementCollection nodes = doc.getElementsByTagName("head");
foreach (IHTMLElement elem in nodes)
{
HTMLHeadElementClass head = (HTMLHeadElementClass)elem;
head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
}
}
WPF WebBrowser does not have this property as the WinForms control.
You'd be better using a WindowsFormsHost in your WPF application and use the WinForms WebBrowser (so that you can use SuppressScriptErrors.) Make sure you run in full trust.

call clientside javascript from asp.net c# page

I have a c# asp.net page and an update function which will update the database. In this function I would like to call some client side javascript. I've read a lot about registering a start up script in page_load() but this is always trigger on page load (funny that!)
How would I register then call a script inside my update function? Triggered when a user clicks the "update" button. I have tried the following (inside my function)
protected void doUpdate(object sender, EventArgs e) {
string jScript;
jScript = "<script type=text/javascript>alert('hello');<" + "/script>";
ClientScript.RegisterStartupScript(GetType(), "Javascript", jScript);
}
but it isn't fired. Any ideas? Many thanks.
[update]
It's now working - the function looks like this
protected void doUpdate(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(),"Javascript", "cleanup();",true);
}
Cleanup() is the javascript function in my HTML. Thanks for the help guys :)
If the control causing the postback is inside an UpdatePanel you need to use
ScriptManager.RegisterStartupScript
You can't 'execute' client side scripts from the web server (the client knows who the server is, but not the other way around).
The only way to overcome this limitation is by a. create a long-polling process that requests something from the server, the server doesn't complete the request till it has something to return (then client side it makes another request).
What you are really looking for is websocket (duplex) enabled communication. You can check out alchemy websockets or SignalR (has a pretty nice library with dynamic proxy generation).
The reason why that 'script always works on Page_Load' is because it effectively injects your script tag into the html returned for the page requested.
Your Update button is likely using the standard ASP Button behavior, meaning it is type="submit" when it is rendered. Since that's the case, you can just use:
Page.ClientScript.RegisterOnSubmitStatement
Keep in mind that will register a script for every postback, not just the Update button. So, if you only want some javascript run on clicking Update, you would need to check if the EventTarget is UpdateButton.ClientID. Also, RegisterOnSubmitStatement always adds the <script> tags, so don't include those in the javascript statement.
An even easier solution, the ASP Button itself also has an OnClientClick property. This will run client-side code (javascript) when the button is clicked in the browser.

RadControl DateTimePicker Selecting new time doesn't remove highlight from previous selection

This is not browser specific - the behavior exists in Firefox and IE. The RadControl is being used within a User Control in a SiteFinity site.
Very little customization has been done to the control.
<telerik:RadDateTimePicker ID="RadDateTimePicker1" runat="server"
MinDate="2010/1/1" Width="250px">
<ClientEvents></ClientEvents>
<TimeView starttime="08:00:00" endtime="20:00:00"
interval="02:00:00"></TimeView>
<DateInput runat="server" ID="DateInput"></DateInput>
</telerik:RadDateTimePicker>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadDateTimePicker1.MinDate = DateTime.Now;
}
}
[Disclaimer, I work for Telerik]
I don't specifically know what the issue is, however here are some general troubleshooting steps that might help unearth the issue:
Check for Javacript errors - (Firefox's Error Console would do it)
Isolate the RadDateTimePicker control from Sitefinity - (Create a normal ASPX page and place the RadDateTimePicker control on this page. Does it work in this environment?)
Check for stylesheet issues using Firebug and/or remove stylesheets (backup first).
In general, keep simplifying until it starts working then re-add complexity until it breaks again. This normally tells me where the problem is.
Alternately, you could send your project/code to Telerik support. Best of luck.
Can you try changing MinDate to use:
RadDateTimePicker1.MinDate = System.DateTime.Parse(String.Format("{0}/{1}/{2}", System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Year - 1))
And tell me if the behavior changes.
Also, is the new highlight being shown as well, or is it stuck on the old highlighting completely?

Categories

Resources