Change page from an Iframe to the Main Window - javascript

I'm working inside an iframe and when i finish my job I want to change page (NOT inside iframe) but out side of this iframe, in the main window.
For this I use the following Sub:
Public Sub ChangePage(sender As Object, e As EventArgs)
Dim myNewAsp As New AspNetSqlProvider
Dim dbHandler As New DBHandler
Dim srvHandler As New ServerHandler
Dim aspProvider As New MyAspNetSqlMembershipProvider
Dim errAnswer As New Register
Dim assit As New Assistance
Dim currentUser As MembershipUser = Nothing
Dim message As String = Nothing
Dim msg As String = Nothing
Try
Dim url As String = "/Pages/Account/Login.aspx"
Dim postWindow As Object ' "/Pages/Account/Assistance.aspx"
Dim startWindow As Object ' "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim myServerName As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
url = myServerName + url
startWindow = Me.GetType().FullName
postWindow = Assistance.PageUrlType
msg = "Hellow World"
'msg = "<script type='text/javascript'> $(document).ready(function(){ window.location.href='" + url + "'; }); </script>"
Dim script As Type = Me.Page.GetType() ' Assistance.PageType.BaseType
Dim postmsg As String = "ChangePage('" & startWindow & "', '" & postWindow & "', '" & msg & "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "sendMessage") Then
Page.ClientScript.RegisterStartupScript(script, "sendMessage", postmsg)
End If
Catch eq As SqlException
srvHandler.ErrorAnswer = DBHandler.GetError(1, Nothing, Nothing, eq, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword "
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
Catch Ex As Exception
srvHandler.ErrorAnswer = DBHandler.GetError(3, Ex, Nothing, Nothing, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword"
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
End Try
End Sub
I use the following script in the Page inside the iFrame:
<script type="text/javascript">
function ChangePage(startPage, sendPage, message) {
var sPage = document.getElementById(startPage);
sPage.contentWindow.postMessage(message, sendPage);
}
</script>
I also use the following script in the Page I want to change (parent Page):
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
event.origin !== message;
event.source.postMessage("'" + message + "'", event.origin);
return;
}
what I got from the above is to have the desired page (the message in the example) BUT inside of the frame.
The scrip in the Help01.aspx page is executed just fine. But in this window, and not in the parent one (Assistance,aspx)
As a result I can't get out of the iFrame (which is inside of a table).
Is someone to know what to do about it?

I think you'll need to use something like postMessage here. It depends on the browsers you need to support, but support is pretty good. That will let you "talk" between the main window and the iFrame.
That link will walk you through how to set it up, but the gist of it is that you'll need to attach an event listener to the main window and then post a message from the iFrame to the outer window. Then do your redirect in the outer window when the message comes in.
So where you have Dim msg As String... you'll want that to be some code that posts a message to the outer frame. Something like window.postMessage(..)

Related

Create javascript Alert before response.end() vb.net

I have a button to generate rar file then download it , i want to create an alert javascript if download success or file is exist in directory.. My code :
Using zip As New ZipFile
Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Download/" & "/" & NameFolder))
Dim files As New List(Of ListItem)()
zip.AlternateEncodingUsage = ZipOption.AsNecessary
zip.AddDirectoryByName("MyRarFileName")
For Each filePath As String In filePaths
files.Add(New ListItem(Path.GetFileName(filePath), filePath))
zip.AddFile(filePath, "MyRarFileName")
Next
Response.Clear()
Response.BufferOutput = False
Dim zipName As String = [String].Format("MyRarFileName_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
Response.ContentType = "application/zip"
Response.AddHeader("content-disposition", "attachment; filename=" + zipName)
zip.Save(Response.OutputStream)
Dim ls_Dir As New IO.DirectoryInfo(Server.MapPath("~/Download" & "/" & NameFolder))
Dim ls_GetFile As IO.FileInfo() = ls_Dir.GetFiles()
Dim ls_File As IO.FileInfo
For Each ls_File In ls_GetFile
File.Delete(ls_File.FullName)
Next
ls_Dir.Delete(True)
Response.End()
End Using
I want to call an alert javascript like below :
If DataExist > 0 Then
'My Alert
Using zip As New ZipFile
'Code for generate and download rar
End Using
End If
I have tried :
Dim myScript As String = "window.alert('Download Success !');"
ClientScript.RegisterStartupScript(Me.GetType(), "myScript", myScript, True)
and call javascript function :
<script>
function MyMessage(){
alert('Download Success');
}
</scipt>
ClientScript.RegisterStartupScript(Me.GetType(), "MyMessage", MyMessage(), True)
But alert still doesn't appears, any suggest ?
Thanks you

Where find URL in return of an ASHX returning RedirectFromLoginPage

I have an ashx receiving login/password and send error message if it's wrong but if it's good make a RedirectFromLoginPage.
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
FormsAuthentication.SignOut()
Dim LesDatas As New MyEntities
Dim username As String = GetParamURL("UserName")
Dim password As String = GetParamURL("Password")
If Not IdentifyCollab(username, password, LesDatas) Then
FormsAuthentication.SignOut()
context.Session.Abandon()
HelperJournal.Log("Echec de connexion :" & username)
loginStatut = LoginFailed(GetIPAddress, LesDatas)
context.Response.ContentType = "text/plain"
context.Response.Write(loginStatut.Msg)
Else
FormsAuthentication.RedirectFromLoginPage(ConnectedUser.Login, False)
End If
End Sub
If You use directly the ashx in browser url zone : http://localhost:5959/login/login.ashx?UserName=toto&Password=MyPass, you're directly redirect in the default page http://localhost:5959//choix.aspx
But If I call it from JS :
$.post("/Login/Login.ashx?UserName=" + mdp1 + "&Password=" + mdp2, {},
function (response,tt,ti) {
if (response.indexOf("html") === -1) $("#ResultConnexion").html(response); else {
window.history.pushState("", "", '/choix.aspx');
var newWindow = window.open("", "_self");
newWindow.document.write(response);
}
});
I need to use pushState to correct the url in browser, and window.open/write to display the defaultpage. But like you can see, I write in hard "/choix.aspx", cause the url are not modify and stay on referer URL (my login page http://localhost:5959/Login/login.html)
But If I can have automaticly the good URL when I use in browser my ashx, it's seems the URL information is sent.
In function use in response of $post I note severals parameters : response,tt,ti
response is the text to display page in return
tt="success"
ti is an object with lot of informations... but I don't see where is URL.
If someone can help me.
I just find a way here
In my masterpage
Private Sub Choix_Init(sender As Object, e As EventArgs) Handles Me.Init
Response.AppendHeader("X-MONAPPLI", HttpContext.Current.Request.Url.PathAndQuery)
End Sub
and in login.js
$.post("/Login/Login.ashx?UserName=" + mdp1 + "&Password=" + mdp2, {},
function (response, tt, xhrreq) {
if (response.indexOf("html") === -1) $("#ResultConnexion").html(response); else {
window.history.replaceState("", "", xhrreq.getResponseHeader("X-MONAPPLI"));
var newWindow = window.open("", "_self");
newWindow.document.write(response);
}
});
I use replaceState instead of pushstate cause I've secyrity error

Define and call Wscript function inside Javascript file to run in Windows Script Host

I need exactly like I asked in question title.
I have a javascript file for calculating Thanksgiving date for every year, provided the year value input.
Now I want this javascript to be executable by Windows Script Host and also allowed to create as many InputBoxes as possible without changing the file type or extension.
I tried below code but it gives me error expected ;:
ws = WScript.CreateObject('WScript.Shell');
var myDate = new Date();
myDate.setHours(0, 0, 0, 0);
// Function WSHInputBox(Message, Title, Value)
// ' Provides an InputBox function for JScript
// ' Can be called from JScript as:
// ' var result = WSHInputBox("Enter a name", "Input", test);
// WSHInputBox = InputBox(Message, Title, Value)
// End Function
strYear = GetUserInput( "Enter some input:" )
ws.Popup('Year ?'+strYear);
//var strYear = WSHInputBox("Enter the year", "Thanksgiving Year")
myDate.setYear(parseInt(strYear));
// Determine November 1.
myDate.setDate(1);
myDate.setMonth(10);
// Find Thursday.
var thursday = 4;
while(myDate.getDay() != thursday) {
myDate.setDate(myDate.getDate() + 1);
}
// Add 3 weeks.
myDate.setDate(myDate.getDate() + 21);
ws.Popup('Result: ' + myDate);
Function UserInput( myPrompt )
' This function prompts the user for some input.
' When the script runs in CSCRIPT.EXE, StdIn is used,
' otherwise the VBScript InputBox( ) function is used.
' myPrompt is the the text used to prompt the user for input.
' The function returns the input typed either on StdIn or in InputBox( ).
' Written by Rob van der Woude
' http://www.robvanderwoude.com
' Check if the script runs in CSCRIPT.EXE
If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
' If so, use StdIn and StdOut
WScript.StdOut.Write myPrompt & " "
UserInput = WScript.StdIn.ReadLine
Else
' If not, use InputBox( )
UserInput = InputBox( myPrompt )
End If
End Function
Function GetUserInput( myPrompt )
' This function uses Internet Explorer to
' create a dialog and prompt for user input.
'
' Version: 2.11
' Last modified: 2013-11-07
'
' Argument: [string] prompt text, e.g. "Please enter your name:"
' Returns: [string] the user input typed in the dialog screen
'
' Written by Rob van der Woude
' http://www.robvanderwoude.com
' Error handling code written by Denis St-Pierre
Dim objIE
' Create an IE object
Set objIE = CreateObject( "InternetExplorer.Application" )
' Specify some of the IE window's settings
objIE.Navigate "about:blank"
objIE.Document.title = "Input required " & String( 100, "." )
objIE.ToolBar = False
objIE.Resizable = False
objIE.StatusBar = False
objIE.Width = 320
objIE.Height = 180
' Center the dialog window on the screen
With objIE.Document.parentWindow.screen
objIE.Left = (.availWidth - objIE.Width ) \ 2
objIE.Top = (.availHeight - objIE.Height) \ 2
End With
' Wait till IE is ready
Do While objIE.Busy
WScript.Sleep 200
Loop
' Insert the HTML code to prompt for user input
objIE.Document.body.innerHTML = "<div align=""center""><p>" & myPrompt _
& "</p>" & vbCrLf _
& "<p><input type=""text"" size=""20"" " _
& "id=""UserInput""></p>" & vbCrLf _
& "<p><input type=""hidden"" id=""OK"" " _
& "name=""OK"" value=""0"">" _
& "<input type=""submit"" value="" OK "" " _
& "OnClick=""VBScript:OK.value=1""></p></div>"
' Hide the scrollbars
objIE.Document.body.style.overflow = "auto"
' Make the window visible
objIE.Visible = True
' Set focus on input field
objIE.Document.all.UserInput.focus
' Wait till the OK button has been clicked
On Error Resume Next
Do While objIE.Document.all.OK.value = 0
WScript.Sleep 200
' Error handling code by Denis St-Pierre
If Err Then ' user clicked red X (or alt-F4) to close IE window
IELogin = Array( "", "" )
objIE.Quit
Set objIE = Nothing
Exit Function
End if
Loop
On Error Goto 0
' Read the user input from the dialog window
GetUserInput = objIE.Document.all.UserInput.value
' Close and release the object
objIE.Quit
Set objIE = Nothing
End Function
WScript.Quit();
Can someone help out as I am stuck at how to include both types of code in this same Javascript file, I know there is some way, but what's that ?
Problem
Developer VickyDev wants to run a MSFT VBScript function within a MSFT JScript file
InputBox is a VBScript function and not a JScript function
// Function WSHInputBox(Message, Title, Value)
// ' Provides an InputBox function for JScript
// ' Can be called from JScript as:
// ' var result = WSHInputBox("Enter a name", "Input", test);
// WSHInputBox = InputBox(Message, Title, Value)
// End Function
Solution
Combine VBScript and JScript together using windows script host file with language declaration on script tags.
Make sure to declare all the VBScript functions first before declaring the JScript
Example
<?xml version="1.0"?>
<package>
<job id="uu244trumpehant">
<script language="vbscript">
<![CDATA[
Function HelloWorldVB
msgbox "hello world from VB"
End Function
]]>
</script>
<script language="jscript">
<![CDATA[
HelloWorldJS();
HelloWorldVB();
//HelloWorldVBTwo(); // this one will error
// function defined below
function HelloWorldJS(){
WScript.Echo("hello world from JS");
}
]]>
</script>
<script language="vbscript">
<![CDATA[
Function HelloWorldVBTwo
msgbox "hello world from VBTwo"
End Function
]]>
</script>
</job>
</package>

Getting confirm value in code behind

i have a pop up on the index change of a combo box and i need to get the result of the confirm box in the code behind:
Protected Sub service_list_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles service_list.SelectedIndexChanged
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "confirm", x.javaMsg("Do you
want to choose a date?"), True)
If user clicks ok
GridView1.DataSource = x.selectCNT(service_list.SelectedValue)
GridView1.DataBind()
End Sub
this is my function:
Public Function javaMsg(ByVal message As String) As String
Dim sb As New System.Text.StringBuilder()
sb.Append("window.onload=function(){")
sb.Append("confirm('")
sb.Append(message)
sb.Append("')};")
Return sb.ToString()
End Function
note that i'm using asp.net with vb.net
Here is a link that shows how to do it: Call VB method from JavaScript
It basically says there are 2 ways, Ajax or Postback. Here is the postback method:
aspx file:
<script type="text/javascript">
<!--
function callServersideFunction()
{
var someValueToPass = 'Hello server';
__doPostBack('CustomPostBack', someValueToPass);
}
// -->
</script>
aspx.vb file:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Insure that the __doPostBack() JavaScript method is created...
Me.ClientScript.GetPostBackEventReference(Me, String.Empty)
If Me.IsPostBack Then
Dim eventTarget As String
Dim eventArgument As String
If ( (Me.Request("__EVENTTARGET") Is Nothing)
eventTarget = String.Empty
Else
eventTarget = Me.Request("__EVENTTARGET"))
If ( (Me.Request("__EVENTARGUMENT") Is Nothing)
eventArgument = String.Empty
Else
eventArgument = Me.Request("__EVENTARGUMENT"))
If eventTarget = "CustomPostBack" Then
Dim valuePassed As String = eventArgument
' Call your VB method here...
End If
End If
End Sub

Javascript posting to VB.Net page multiple times

Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.
I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)
I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.
Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.

Categories

Resources