calling Javascript from c# using awesomium - c#

I'm trying awesomium for create a basic app, I'm testing the js <----> c# communication but this doesn't seem work well...I create a local html and open it..so far so good..but when I try call js nothing happen, no error, no bug, nothing, simply this doesn't call js..
my basic js code is:
var base = {
newItem : function(item){
$("#botones").append('<div class="botonMenu">' + item + '</div>');
},
other : function(){
alert("hi!!");
}
}
if I test this inside firebug obviously I can call my functions well and the items are created or the alert box...
now..my c# code is this
//I've wrote this code inside the winForms sample..but change the code for load
//my local file and call js....
WebCore.BaseDirectory = #"C:\Documents and Settings\ME\dummytests\codes\views";
webView.LoadFile("base.html");
JSValue param1 = new JSValue("nameItem");
webView.CallJavascriptFunction("base", "other");
webView.CallJavascriptFunction("base","newItem", param1);
webView.Focus();
the file is load well but the js communication didn't work
thanks so much and I hope can help me...this awesomium really look awesome

The problem is that you're trying to call the Javascript on the page before it has finished loading. If you wait until after load has completed, you should see it execute correctly.
webView.LoadCompleted += ExecuteJavascript;
WebCore.BaseDirectory = #"C:\Documents and Settings\ME\dummytests\codes\views";
webView.LoadFile("base.html");
...
private void ExecuteJavascript(object sender, EventArgs eventArgs)
{
JSValue param1 = new JSValue("nameItem");
webView.CallJavascriptFunction("base", "other");
webView.CallJavascriptFunction("base", "newItem", param1);
webView.Focus();
}

This is a solution for Awesomium v1.7.0.5. It uses "JSObject" to get the javascript "window" object. From there it calls a javascript function that uses jQuery to dynamically set the text of a "div". This also uses jQuery to call the function when the document is ready.
One can use the JSObject.Bind method to call C# methods from javascript.
Head:
<script type="text/javascript">
function setDivText(s)
{
$("#msgDiv").text(s);
}
$(document).ready(function () {
setDivText("This is the start up text.");
});
</script>
Body:
<body>
<p>Test...</p>
<p></p>
<div id="msgDiv"></div>
</body>
C#:
This uses WPF WebControl with Name of "webView" inside a Button Click event handler.
using Awesomium.Core;
...
private void Button1_Click(object sender, RoutedEventArgs e)
{
JSObject window = webView.ExecuteJavascriptWithResult("window");
if (window == null)
return;
using (window)
{
window.InvokeAsync("setDivText", "You pressed button 1.");
}
}

Related

Automatically sign out from Forms Authentication in ASP.NET when browser is closed

Is there a way to force ASP.NET to sign out from it's authentication when the browser is closed or the user types in a new address?
If the browser is left open then I need to keep the user authenticated, so a long timeout on the authentication ticket is preferable.
Not sure if this is still an issue but this resolved the issue for me. Just add the following to the Page_Load event of your Start Page:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null || string.IsNullOrEmpty(Request.UrlReferrer.AbsolutePath))
{
Session.Abandon();
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
}
I've been working on this for some time, reading around and seeing various posts and answers, conjecture and speculation.
This solution does have a significant caveat - Popup windows ("BURN HIM!!!" I hear you cry) are required, as is JavaScript. However, given that you have a need to implement this so securely, I'd hazard a guess that the users would accept this to maintain security, and you could code for JavaScript being enabled.
STEP 1 - Verify that popups are enabled - If not, redirect to instructions on how to enable
in the Global.asax
Setup a session variable to verify if popups have been checked:
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["popupsChecked"] = false;
}
in Page.aspx / masterPage.master
Check the session variable, if false (first visit to the site this session), inject the JavaScript to check for popup availability:
if (!IsPostBack)
{
if (!(bool)Session["popupsChecked"])
{
Page.Header.Controls.Add(new LiteralControl("<script src=\"/js/popupCheck.js\" type=\"text/javascript\"></script>"));
}
}
The popupCheck.js file (The file "enablePopups.aspx" is instructions on how to enable popups for the site in question)
$(function () {
result = window.open("/static/popupCheck.aspx", "popped", "width=10, height=10, location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no");
if (result != null) {
// Not blocking
if (window.location.pathname != "/static/enablePopups.aspx") {
window.location = "/";
};
}
else {
//blocking
if (window.location.pathname != "/static/enablePopups.aspx") {
window.location = "/static/enablePopups.aspx";
};
}
});
And finally, the popupCheck.aspx
<head runat="server">
<title>Popup Checker</title>
<script language="javascript" type="text/javascript">
window.close();
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Popup windows are enabled, please close this window.
</div>
</form>
</body>
</html>
With the following in the codebehind - This will stop any further checks to see if popup windows are enabled:
protected void Page_Load(object sender, EventArgs e)
{
Session["popupsChecked"] = true;
}
So at this point we now have "forced" the user to enable popups for this site - As said, the site content should justify this annoyance in my opinion
STEP 2 - Check for where they're going, if they're off, popup the logoff
In your main javascript block, file, data, or however you're doing it now days
var siteLinkClicked = false;
var isAuthenticated = false;
$(function() {
// Check if user is authenticated
if ($("#someElementThatOnlyAppearsWhenLoggedIn").length) { isAuthenticated = true; };
// Check if any of the links clicked are in the site
$("a, input").click(function () { // -- You may need more then "a" and "input" tags, or exceptions
siteLinkClicked = true;
});
$(window).bind("beforeunload", function (event) {
if (siteLinkClicked == false && isAuthenticated == true) {
// popup the logout page
window.open("/popupLogout.aspx", "popupLogout", "status=0,location=0,directories=0,menubar=0,scrollbar=0,resizable=0,width=400,height=200")
};
});
});
And the popupLogout.aspx
We have some javascript to check for the parent (opener) location, if it's the same as this popup (i.e. the user has clicked refresh - Or you've missed an element for siteLinkClicked) then just close the window without doing anything:
$(function () {
setTimeout(checkParent, 5000); // Give some time for the new window to load if they've navigated away - A counter could be added, logging off in 5... 4... 3... You get the idea.
window.blur(); // And stick this to the back
});
function checkParent() {
var openerLocation = null;
try {
openerLocation = window.opener.location.hostname
} catch (e) {
openerLocation = null;
}
if (openerLocation == window.location.hostname) {
window.close();
} else {
$("#<%= cmdLogout.ClientID %>").click();
// setTimeout(window.close(), 1000); // Removed and add a redirect to static "loggedOut.html page
};
};
If the location is different / undefined then fire off a button click, then close the window:
<asp:Button Text="logout..." runat="server" ID="cmdLogout" OnClick="cmdLogout_click" />
And the button then triggers the following code:
protected void cmdLogout_click(object sender, EventArgs e)
{
System.Web.Security.FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("~/static/loggedOut.htm"); // Added, can self close if needed in the HTML
}
Final limitation reiteration
Without JavaScript or popups this method will not work, and for me at least, I'll be working in a controlled environment where security is paramount so this solution is worth the annoyance of the end users.
If you have to go to these extreme ends, then I can only assume that the data and application are sensitive enough to force the users to have to enable javascript and have to enable popups.
It seems like you could set a long expiration time and also set it not to persist to get the exact behavior you seem to be looking for. For example:
FormsAuthentication.SetAuthCookie("username", true);
This sets it to persist so that when you close your browser, it will preserve the cookie so that even if they close their browser and load your site again, it will make it so that they don't have to login so long as the expiration time hasn't occurred.
On the other hand:
FormsAuthentication.SetAuthCookie("username", false);
This sets the cookie to not persist. When you close your browser, the cookie is deleted thereby forcing a login the next time you load it whether the expiration time happened or not. For more info here, see FormsAuthentication.SetAuthCookie

Using Window.Open instead of Response.Redirect to open new window?

My page code looks like this:
<asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click"/>
My method looks like this:
protected void btnSearch_Click(object sender, EventArgs e)
{
var value = lblGraphicNameValue.Text.ToString();
Response.Redirect("Search.aspx?txtGraphicName=" +
value);
}
Currently, when the user press the 'Search' button the page refreshes and loads the Search.aspx page. What I'd like to happen is have the Search.aspx open in a new window, instead. I've looked at using Window.Open, but I'm not sure if this is the correct route, or if I can use the same method of passing in my variable (querystring). Can someone point me in the right direction? What I have works, I just want it to open in a new page while leaving the prior page alone.
EDIT: I should mention that I cannot use javascript (secure environment, every browser has javascript disabled).
From what I'm reading, it seems to indicate that opening a new web page from within an asp.net page and having parms passed in is not do-able without javascript? Is this correct?
This code below ultimately does exactly what I needed it to:
<a href="<%= this.ResolveUrl("Search.aspx?id=" + lblGraphicNameValue.Text.Remove(lblGraphicNameValue.Text.Length -4)) %>"
target="_blank">Search Related</a>
This code does three things:
1) Opens Search in new page.
2) Truncates the search value by four
characters (I only needed part of the search string)
3) Passes in
parameter to new page.
This accomplished exactly what I needed without resorting to custom classes or javascript, although it did make me have to use a link instead of a button.
Use this class.
ResponseHelper .Redirect("popup.aspx", "_blank", "menubar=0,width=100,height=100");
public static class ResponseHelper {
public static void Redirect(string url, string target, string windowFeatures) {
HttpContext context = HttpContext.Current;
if ((String.IsNullOrEmpty(target) ||
target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
String.IsNullOrEmpty(windowFeatures)) {
context.Response.Redirect(url);
}
else {
Page page = (Page)context.Handler;
if (page == null) {
throw new InvalidOperationException(
"Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures)) {
script = #"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else {
script = #"window.open(""{0}"", ""{1}"");";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page,
typeof(Page),
"Redirect",
script,
true);
}
}
}
I think your on the right track, but you're confusing server side code, and client side code. window.open is a Javascript function which works on the client side. So you'll need to render some Javascript from C# to make the window popup. Try:
protected void btnSearch_Click(object sender, EventArgs e)
{
var value = lblGraphicNameValue.Text.ToString();
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('Search.aspx?txtGraphicName={0}');</script>", value));
}
That will re-render the page, and then add a script on pageload that will popup the window. A little warning, this will probably be blocked by a browser popup blocker. If you want to get around that, you can probably achieve this without posting back to the server by using Javascript.
A better option would be to create a javascript function like:
function PreviewPOSTransaction(Id)
{
if (Id != null)
{
window.open('POSTransReport.aspx?TransID=' + Id);
return true;
}
}
</script>
and call this function on button "OnClientClick" event like:
OnClientClick="PreviewPOSTransaction(1);

Changing the value of a hidden field without postbacking

I have a link button, that calls the c# function 'send_Click' when clicked. here is the function:
void send_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "text_alert()", true);
Response.Write(hidAcrobat.Value);
}
as you can see, it calls a javascript function "text_alert()" which looks like this:
function text_alert() {
var person = prompt("Additional Comments:", "");
if (person != null && person != "") {
document.getElementById('hidAcrobat').value = person;
}
}
which pops a prompt box accepting a user input and setting the value of the hidden field 'hidAcrobat' to this value.
then back to c#, the next line is Response.write(hidAcrobat.Value);
It writes the default value of the hidAcrobat and NOT the new value which was assigned to it in the prompt box.
I assume its because the page isn't postbacked,
How can I solve this?
This is easily implemented by Jquery Like that
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#MainContent_lnkAddToList').live("click", function() {
var person = prompt("Additional Comments:", "");
$('[id*="hidAcrobat"]').val(person);
});
});
After that you can use your hidden field value in any server side event.
For Jquery add reference
Hope It helps you.
Handle onclick event of link button on client side (using javascript) and call text_alert() method from the handler.
After executing the client-side event handler, the page posts back and on the server side you can access the hidden variable as you are doing in send_Click event handler.
You can easily create a prompt like effect using ModalPopUp and then easily grab the value on server side.

calling web method on window onbeforeunload event

I am working on basic ASP.net website and i want to execute server side function when user try to go away from page. For this i am using onbeforeunload event of window. I have check box on my page and when user checked this check box, i am executing sverside "checkedchange event". Issue is whenever user click on this check box my web method is also get called, which should not get called as only postback is happen, user is not leaving my page. can any one suggest me to avoid web method call when postback happen.
I wnat to execute web method only in following scenarios:
1) When user closes the browser.
2) On click of “Find more matches” button, when user landed on search results page with no school listed.
3) when user changes the url from browser's address bar
Code on aspx page:
function GetMessage() {
var urlstring = document.URL;
{
PageMethods.Message( document.URL);
}
}
</script>
Code on aspx.cs page
[System.Web.Services.WebMethod]
public static void Message()
{
string x="a";
}
This link should hold the answer you are looking for: How to capture the browser window close event?
I think the following code from that link is what you are looking for.
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
//TODO: Execute some code before unload here
//returnValue = "Message to display before the user leaves the page.";
}
eventObject.returnValue = returnValue;
return returnValue;
});

Inject JavaScript with jQuery at runtime into WebBrowser

I have desktop application with WebBrowser control and try to inject JavaScript into loaded page.
For this I added two script elements:
private static void AddJQueryElement(HtmlElement head)
{
HtmlElement scriptEl = head.Document.CreateElement("script");
IHTMLScriptElement jQueryElement = (IHTMLScriptElement)scriptEl.DomElement;
jQueryElement.src = #"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head.AppendChild(scriptEl);
}
private static void AddScriptElement(HtmlElement head)
{
HtmlElement scriptEl = head.Document.CreateElement("script");
IHTMLScriptElement myScriptElement = (IHTMLScriptElement)scriptEl.DomElement;
myScriptElement.src = #"file:///c:\JScript.js";
head.AppendChild(scriptEl);
}
how you can see first is reference to jQuery because I use it in my script. When I try to invoke function from my script using _webBrowser.Document.InvokeScript WebBrowser throws
Script Error :"Object expected". and points to the line where i try to use jQuery (var tags = $("Body").find("*");).
How can I prevent this error?
Another interesting thing: if I add something like alert("hello"); to start of my function all works fine.
Haven't got correct answer, but have solved the problem by using local copy of jquery.min.js.
It's possible you aren't specifying your script to run on load. alert("hello") is buying that time needed to download the script/finish building the HTML.
$(document).ready(function() {
// Handler for .ready() called.
});

Categories

Resources