I have to write a c# class that gets an html page's content (the page is public) and trigger a javascript function that downloads a file.
My goal is to download the file and save it in a folder
The page is a public html page that does not require login.
The link looks like this :
href="javascript:__doPostBack('lbtSpreadsheet','')" style="font-weight: 700">Export Results</a>
the doPostBack function contains the following code:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
when you click the link manually, it submits the form and returns an excel sheet, the download dialog box opens to ask you where you need to save it.
I want to do this automatically to get the excel sheet and then process it.
I found out that I can find the links on a page like this:
HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(/* url */);
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[#href]"))
{
}
but how can I trigger the javascript in the link and save the file returned?
Thank you
I don't think you can. C# server side web clients such as HtmlWeb or WebClient only understand HTTP/HTML, they aren't full-fledged web browsers capable of executing javascript the same way that IE, Firefox or Chrome could.
If you want the file download to start automatically during the onload of the page without the Export Results link triggering the file download then you can write the below js script that calls your js function __doPostBack which in turn does the form submission.
window.onload = function() {
__doPostBack (param1, param2);
};
Or as your question title says 'trigger javascript function using c#' then you can access Javascript function from C# code using ScriptManager class which is part of System.Web.UI
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "FileDownload", "Javascript:__doPostBack (param1, param2);", true);
}
Related
Is it impossible to gather information from page (and databaes), create csv file from given information, download created file and refresh page?
Currently user sees a table with rows, select rows by checking checkboxes, press Export button and CSV file is created and downloaded to users computer. The problem is with Page Refresh.
Currently on button click CSV is created and downloaded in the following way:
//here is create csv function and then the result is outputed
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=DataTable.csv")
Response.Charset = ""
Response.ContentType = "application/text"
Response.Output.Write(CsvFile.ToString(), 0)
Response.Flush()
Response.End()
This soultion makes problems with Page refresh after csv file is downloaded.
1) This link:
Redirecting to another page after Response.End() has been called in C#
suggests `Response.AddHeader("Refresh", "3; url=index.html"); that should refresh page.
This doesn't work, no redirect happens.
2) Another sollution suggested is creating some additional URL and allow user to download file from given URL. This doesn't fit my situation, because File is created from data on the page.
3) Is there any other solution that fits needs (button click creates csv and downloads it, page is refreshed)?
Can you give me some clues, please?
You are going to need to use some javascript on the client to get the results you want. I have taken the basics from here https://stackoverflow.com/a/4168965/1002621 which is an example with a php back-end.
The code you need on the client will look something like this the basic premise is that you use jquery to intercept your download buttons click event so a token can be injected into the form post which you can then send back in the response to know the file download is done and then do your own form submit / whatever.
<script type="text/javascript">
function DownloadAndRefresh() {
//get form and inject a hidden token input
var form = $(this).closest('form');
var tokenInput = $('input[name=token]');
if (tokenInput.length == 0) {
tokenInput = $('<input />').prop('type', 'hidden').prop('name', 'token');
form.append(tokenInput);
}
//create a unqiue token we can watch for and set the hidden inputs value
var token = new Date().getTime();
tokenInput.prop('value', token);
//watch for the token to come back in the documents cookie (this is set on server)
var tokenInterval = setInterval(function () {
//check to see if the cookie contains the token yet
if (document.cookie.indexOf(token) != -1) {
//submit the form again now the file has been downloaded (this causes a standard postback)
form[0].submit();
window.clearInterval(tokenInterval);
}
}, 200);
//wait up to 60 seconds for the token then stop the interval because something probably went wrong
setTimeout(function () { window.clearInterval(tokenInterval); }, 60000);
//allow the current post action to continue
return true;
}
$(document).ready(function () {
//call the DownloadAndRefresh function before posting to the server
$('#<%= DownloadButton.ClientID %>').on('click', DownloadAndRefresh);
});
</script>
<asp:Button runat="server" ID="DownloadButton" Text="Download Button" onclick="Download_Click" />
The server code is pretty simple and just needs to pull the token out of the request form and put it in the response cookie.
protected void Download_Click(object sender, EventArgs e)
{
Response.Clear();
//set the response token cookie to be the token sent in the form request
Response.SetCookie(new HttpCookie("token", Request.Form["token"]));
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=file.txt");
Response.ContentType = "text/plain";
Response.Output.Write("some text");
Response.End();
}
I am making simple bot which will take values from script then it will put them into the textboxes of another website and then perform click on button so the bot can log in another website I have written the code, but I want to call it when page is fully loaded. I tried <body onload> but it doesn't work.
Is this possible that we could call our javascript function from our c# code file under the documentcompleted event or any other way?
<script type="text/javascript">
function myf() {
document.getElementsByTagName("INPUT")[1].setAttribute("value", "userabc");
document.getElementsByTagName("INPUT")[2].setAttribute("value", "passwordabc");
document.getElementsByTagName("INPUT")[3].click();
}
</script>
//C# Code file
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("https://www.iauc.co.jp/auction/prelogin01_en.jsp?timestamp=1360652615774");
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
//Can we call javascript function here
}
I did not fully understand you but if you want to run a script when the document has been fully downloaded on the client web browser, then you can user jQuery's document ready event.
Add jQuery to your web page and then add the following script block to the page after the jQuery reference.
<script type="text/javascript">
$(function () {
// write your JavaScript code here
myf();
});
</script>
This script block will get triggered when the DOM for the page has been fully loaded.
You have to write the complete java script including script tag in a string variable.
Then you can Response.Write() the string variable.
string script = "<script type="" language=""> YOUR JAVASCRIPT </script>";
Response.Redirect(script);
Try this
// here's will be your script
string script = "";
ClientScriptManager clientScript = Page.ClientScript;
clientScript.RegisterStartupScript(typeof(Page), "a key", script);
UPDATE :
this will check it if its fully loaded and then do what you want
$(document).ready(function()
{
//page is fully loaded and ready, do what you want
}
i have a web page in c#, in the codebehind i generate a url, on the aspx page i want to update an iframe to show this url.
after looking a while for the means to do this, i found i can register javascript to force the refresh of the iframe, but now i am experiencing a trouble.
no matter what i try, the url seems to never change, remaining at the on load defined url.
let me show you some of the code so you can see what i am doing and maybe help me with thi issue.
i have this string, who handles the url i want to go
public String currentMap = "google.com";
this is the function who registers the javascript
protected void Page_Load(object sender, EventArgs e)
{
UtilityClass utility = new UtilityClass();
this.Page.ClientScript.RegisterStartupScript(
this.GetType(),
"StartupScript",
"Sys.Application.add_load(MyLoad);",
true);}
this registers the javascript function, this function is suppoused to load a modified url, like this
<script type="text/javascript">
function MyLoad(sender) {
$get('maps').innerHTML += "<%= currentMap %>";
}</script>
while i can see how i the inner html updates (you can see i use the =+ operator, because i wanted to see if i was adding something to the page), but the value for currentMap is always the same, and the iframe does not gets updated.
i launch a function, when i click an object in a gridview, this function does something like this.
currentMap = "<iframe src=\"somepages.html" id=\"viewerframe\" width=\"100%\" height=\"450\"></iframe>"\"";
i can see the iframe updating, but the value remains at http://google.com (a test value hard coded).
how can i update the div so it shows the correct url in the iframe?
thank you for the help
To update the src of an iframe you can use this code:
//Set upload frame source
var uploadUrl = '/Profile/upload.aspx?id=' + $.url().param('id').replace('/', '');
$('#uploadFrame').prop('src', uploadUrl);
How to refresh the parent window while closing the popup window(child window).
We are calling the java script functions in code behind to refresh the parent window by using page.ClientScript.RegisterStartupScript().But t is working fine in IE(internet explorer) but not working in Mozilla Firefox and Google Chrome.
In the Mozilla Firefox the pop up value is saving in the database but it is not updating into the parent page.If i did refresh manually the value is getting updating into the parent page. If i put debugger in RefreshPage()(javascript function) function in IE it is firing but not in Firefox.
The below code for call the javascript function in .cs class.
page.ClientScript.RegisterStartupScript(this.GetType(), "PopupSave", "<script>javascript:alert('" + dsMessage.Tables[0].Rows[0]["ErrorMessage"].ToString() + "');window.open('','_self','');window.close();window.document.forms[0].submit();</script>");
The above code RefreshPage() is the javascript function to refresh the page
i.e.
function RefreshPage() { window.document.forms[0].submit(); }
Please help me i tried with different scenarios but no output.
instead of RefreshPage() i used different functions
like reload(),
window.opener.forms[0].submit(),
likewise but still no output anyone knows please help me.
Try this function
on submit button click run this script
<script language='javascript'> window.opener.frames.location='somepage.aspx';window.close();</script>
this will help you !!!
Before trying to make js calls between windows.
Set 'document.domain' to the same value on both pages.
protected void ButtonClick(object sender, EventArgs e)
{
string closeAndRefreshScript = #"<script type='text/javascript'>
window.opener.location.reload();
window.close();
</script>";
base.Response.Write(closeAndRefreshScript);
}
I am using [script.js][1] as async script loader along with my master page. The pages on the root are working fine using the master page file as it's master page. When it comes to web pages that are inside folders like below then the path does not work fine. Script loader loads the files from wrong url. How do i make it load from correct url regardless of the path.
Admin
-users
-createuser.aspx
The contents of the loader file
//show the path to load scripts files from
$script.path("/js/");
//load jquery first and then load the dependent scripts
$script.order(["jquery.min","slider"],function(){
//load the application specific file
$script("app");
});
how do i get the path to web application on client side for example path should resolve to
http://domainname/virtualdirectory/js/
Are you looking for somthing like this?
<%= Page.ResolveClientUrl("~/Scripts/test.min.js") %>
This will resolve the url for you from the HTML side. I am not familiar with $script.path, but I am wondering if you can do somthing like $script.path('<%=Page.ResolveClientUrl("~/Scripts/test.min.js") %>');
It seems like $script.path("~/js"); would be better. Also, please, write down the wrong path here, i'll try to guess why it is wrong
try this out:
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
string script;
script = "function getURL(which){ if(which=='1') { return '" + ResolveUrl("~/Default.aspx") + "'; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "MyFunction", script, true);
}
JAVASCRIPT-With JQuery:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
alert(getURL('1'));
});
</script>
you will have to know which URL to load, but it works like a charm. Good luck!