How to close a popup window in a parent window? - c#

I need to close a popup window which has been loaded by a parent window.
This popup window is a Documentviewer window in my webapp.
I need to close this viewer by clicking a logout button which is in master page.
My code:
public string MySession //server side code
{
get
{
if (Session["RegID"] != null)
{
return Session["RegID"].ToString();
}
else
{
return "";
}
}
}
//client side code
$(window).load(function() {
Start();
});
function Start()
{
timedCount();
var t=setTimeout("Start()",10000);
}
function timedCount()
{
/*var out="<%=Session["RegID"]%>";*/
var out='<%=MySession%>';
if(out!="")
{
alert(out);
}else
{
window.close();
}
}
Server code is executed at very first time only.
My target is to close the popup if it is opened when user logs out.

You probably have something like this on your parent page:
window.open(...);
If you change this to:
var popup = window.open(...);
then at any time you can close it by coding:
popup.close();
http://jsfiddle.net/pimvdb/bjkNx/1/

Put your popup window in global variable:
<script>
var popupWindow;
function openw(url) {
popupWindow = window.open(url, "popup", "");
}
function closew() {
if (popupWindow) {
popupWindow.close();
}
}
</script>
open<br />
close

Related

Window open on Notification click

I have created a chat application, so when I received a message there is a notification generated so that on clicking notification my chat application should open and I did it using this code below
if (!ApplicationContext.ContactsViewModel.IsWindowOpen)
{
ApplicationContext.CurrentChatView.Dispatcher.Invoke(() =>
{
ApplicationContext.CurrentChatView.WindowState = WindowState.Normal;
ApplicationContext.CurrentChatView.Activate();
});
}
so the problem here is my application is performing all the tasks in the background but instead of appearing in the foreground
I have also tried :
ApplicationContext.CurrentChatView.Topmost=true;
but in this case, the application remains topmost even after clicking on another window.
is there any other alternative to it??
thanks in advance
You should make corrections in your method calling order. Try the following:
if (!ApplicationContext.ContactsViewModel.IsWindowOpen)
{
ApplicationContext.CurrentChatView.Dispatcher.Invoke(() =>
{
if (!Window.IsVisible)
{
Window.Show();
}
if (Window.WindowState == WindowState.Minimized)
{
Window.WindowState = WindowState.Normal;
}
Window.Activate();
Window.Topmost = true; // important
Window.Topmost = false; // important
Window.Focus(); // important
});
}
You can use window.Show() / window.Hide() methods to switch between visible and hidden mode:
private void ShowCurrentWindows()
{
foreach (Window window in Application.Current.Windows)
{
if (!window.IsVisible)
{
window.Show();
}
}
}
private void HideCurrentWindows()
{
foreach (Window window in Application.Current.Windows)
{
if (window.IsVisible)
{
window.Hide();
}
}
}

MVC in the controller decide to open a popup or continue to nextpage

I have the following scenario:
When the user click on button next, I have to do some validation that must be done in the controller.
If there is an error, it will show the error messages in a popup with a Yes to continue or No to cancel and close the popup.
But if there are no errors, user will continue to next page without showing a popup.
Here is what I have:
[ActionName(PA.FlowActionName), AcceptPost("nextAanvullen")]
[NoAsyncTimeout]
public ActionResult Pagina_nextAanvullen(OffrerenFlow flow)
{
var medewerkers = ((MedewerkersAanvullenPakket)(flow.CurrentBusinessObject)).Medewerkers;
//validate here
if (true) // for test use true
{
var blok = medewerkers.Deelnemers;
return View("DeelnemersFout", medewerkers); // This doesnt open a popup
}
else
{
// Go to next page
DoWorkEventHandler handler = (o, e) =>
{
AsyncManager.Parameters["navigation"] = Navigate(new NavigationData<OffrerenFlow>((OffrerenFlow)flow), PA.Next,
true);
};
ExecuteAsyncMethod(handler);
}
}
I am not getting an popup, the view just display the view "DeelnemersFout". I need it to be in a popup. Any suggestions are welkom
Assign a value in ViewBag inside IF block
if (true) // for test use true
{
ViewBag.ShowPopup = true;
var blok = medewerkers.Deelnemers;
return View("DeelnemersFout", medewerkers); // This doesnt open a popup
}
and on Cshtml capture this value in a javascript variable and check if there is a value in this variable or not, and show the popup accordingly.

EvaluateScriptAsync waiting in Cefsharp

I am having a problem about using EvaluateScriptAsync in Cefsharp. I want to run a javascript code with EvaluateScriptAsync and then, after this is completed I want my code continue to work, but ContinueWith isn't waiting to EvaluateScriptAsync complete. Here is my code, and don't know what's the problem:
private void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e)
{
if (e.Frame.IsMain)
{
var task = browser.EvaluateScriptAsync("(function() { function xx() { $('body').animate({scrollTop: $('body').prop(\"scrollHeight\")}, 8000, function() { var win = $(window); if ($(document).height() - win.height() == win.scrollTop()) { return true; } else { xx(); } }); }; xx(); })();");
task.ContinueWith(taskHtml =>
{
if (taskHtml.IsCompleted)
{
/* Some code working */
}
this.DialogResult = DialogResult.OK;
});
}
}
You Should use the ExecuteSciptAsyc() method of the Browser Tab Control.
1st you have to get the Current tab page Control and then call the ExecuteSciptAsyc() method from browser control.
var control = GetCurrentTabControl();
control.Browser.ExecuteScriptAsync("alert('It's Working')");

Continue executing an event after validations on modal or radwindow

I have the following scenario: A user makes a click on a button inside an asp page. Because of security reasons, during the click event execution the system determines that it is necessary to apply some validations before continuing with the execution of the fired event.
Those validations are shown in a window (in this case a Telerik RadWindow). Inside this RadWindow, there is a web user control (WUC) containg validations like a Captcha, or security code, secret questions, etc. After the user writes the captcha text or the necessary validations (it implies postbacks inside the WUC), the WUC should continue with the execution of the fired event from the botton which opened the RadWindow.
How can I do this? Any idea? Is it possible?
When you call your RadWindow, make sure the set the OnClientClose event. If you are creating your RadWindow from code-behind:
RadWindow newWindow = new RadWindow();
newWindow.OnClientClose = "onRadWindowClosed";
...
If you are opening your RadWindow through javascript, you can use the add_close() method:
...
getRadWindow().add_close('onRadWindowClosed');
...
In either case, you need to create a new event handler script on your calling page for the OnClientClose event:
function onRadWindowClosed(sender, eventArgs) {
var returnValue = eventArgs.get_argument();
if (returnValue != null) {
if (returnValue == "continue") {
// Continue doing work
}
else {
// Throw an error
}
}
}
On your WUC, in the btnContinue click event:
protected void btnContinue_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "closeScript", "getRadWindow().close('continue');", true);
}
This function is used on both pages:
function getRadWindow() {
var oWindow = null;
if (window.radWindow)
oWindow = window.radWindow;
else if (window.frameElement.radWindow)
oWindow = window.frameElement.radWindow;
return oWindow;
}
UPDATE TO THE EXISTING ANSWER
On your calling page, add a function to get the RadAjaxManager (assuming you already have on the page. If not, you'll need one):
function get_ajaxManager() {
return $find("<%= Telerik.Web.UI.RadAjaxManager.GetCurrent(this.Page).ClientID %>");
}
Modify your OnClosed javascript function (from the calling page):
function onRadWindowClosed(sender, eventArgs) {
var returnValue = eventArgs.get_argument();
if (returnValue != null) {
if (returnValue == "continue") {
// This call will invoke a server side event
get_ajaxManager().ajaxRequest("continue~");
}
}
}
In your code-behind, handle the server-side event that gets called:
protected void RadAjaxManager1_Request(object source, Telerik.Web.UI.AjaxRequestEventArgs e)
{
try
{
if (e.Argument.Trim().Length == 0)
{
// Show a message when debugging, otherwise return
return;
}
string argument = (e.Argument);
String[] stringArray = argument.Split('~');
switch (stringArray[0])
{
case "continue":
// Continue performing your action or call a specific method
ServerSideMethodCall();
break;
}
}
catch (Exception ex)
{
RadAjaxManager.GetCurrent(this.Page).Alert("Unable to complete operation at this time: " + ex.Message);
}
}
As previously mentioned, you'll need a RadAjaxManager on the page if you don't already have one, and you'll need to tie the AjaxRequest handler to it.
<telerik:RadAjaxManager runat="server" ID="RadAjaxManager1" OnAjaxRequest="RadAjaxManager1_Request"></telerik:RadAjaxManager>
Sorry for the long-winded answer. Let me know if that gets you what you need.

C# WebBrowser Button Click, then go to another page

I need to click an html button and navigate to another page. After click I need to wait for page loading, and go to the new page only when the old page loaded.
Here is the code, that click a button:
element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");
webBrowser has got a IsBusy property, but it don`t works after button click:
element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");
if(webBrowser1.IsBusy)
{
MessageBox.Show("Busy"); // Nothing happens, but page is not full loaded.
}
If I add System.Threading.Thread.Sleep(1000) the page loads and I can go to next page, but page loading time on other computers can be more.
What can I do to load another page only after the previous page has loaded?
P.S: I am from Russia, so sorry for bad English.
If your webpage has any javascript blocks, you won't be able to solve the problem using the WebBrowser control itself. You should wait for a document.ready event using javascript code and let know your C# program about it.
Previously, I made a javascript block that provides the webpage state. It looks like this:
var isBusy = true;
function getIsScriptBusy () {
return isBusy;
}
// when loading is complete:
// isBusy = false;
// document.ready event, for example
and a C# code that waits for it to return true:
void WaitForCallback(int timeout) {
Stopwatch w = new Stopwatch();
w.Start();
Wait(delegate() {
return (string)Document.InvokeScript("getIsScriptBusy") != "false"
&& (w.ElapsedMilliseconds < timeout || Debugger.IsAttached);
});
if(w.ElapsedMilliseconds >= timeout && !Debugger.IsAttached)
throw new Exception("Operation timed out.");
}
void Wait(WaitDelegate waitCondition) {
int bRet;
MSG msg = new MSG();
while(waitCondition() && (bRet = GetMessage(ref msg, new HandleRef(null, IntPtr.Zero), 0, 0)) != 0) {
if(bRet == -1) {
// handle the error and possibly exit
} else {
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
Thread.Sleep(0);
}
}
There are lots of events exposed by the WebBrowser control. You might try Navigated or DocumentCompleted.
Nick
WebBrowser.Navigated is the browser event you are seeking.
Use this ,
You might just be able to use this once
br1.DocumentCompleted += br1_DocumentCompleted;
Application.Run();
Call
void br1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br1 = sender as WebBrowser;
if (br1.Url == e.Url)
{
Console.WriteLine("Natigated to {0}", e.Url);
Application.ExitThread(); // Stops the thread
}
}
Replace br1 with your webbrowser name
Hope this helps

Categories