How do I put javascript programmatically into <head> block? - javascript

I need to put some javascript absolutely in the <head> block of the page -- it must execute before the rest of the page because a possible outcome of the script is to redirect to a different page.
However, when I use RegisterClientScriptInclude (to put some jQuery in there) and RegisterClientScriptBlock for my code which uses the jQuery, it puts it near the top of the <body> block, and it does not execute. I can't see a way to programmatically put this javascript into the <head> block -- it must be programmatically because sometimes I don't want it there, and sometimes I do.
I've tried to see if I can directly reference Content1, the ID of the asp:Content element corresponding to the <head> block, but no go.
Just in case anyone thinks that RegisterStartupScript might work: it doesn't. It puts it lower in the <body> block than everything else. Oddly enough.
Want some code? Here:
Type csType = this.GetType();
ClientScriptManager clientScript = Page.ClientScript;
if (!clientScript.IsClientScriptIncludeRegistered(jqueryScriptName))
{
clientScript.RegisterClientScriptInclude(jqueryScriptName, "~/Scripts/jquery-1.7.1.min.js");
}
if (!clientScript.IsClientScriptBlockRegistered(citrixDetectorScriptName))
{
clientScript.RegisterClientScriptBlock(csType, citrixDetectorScriptName, citrixDetectorScriptText, true);
}
By popular demand, how I detect the ActiveX component. This is JScript.
try {
var icaObj = new ActiveXObject("Citrix.ICAClient");
var CitrixVersion = icaObj.ClientVersion.split(".");
var MajorMinorVersion = CitrixVersion[0] + "." + CitrixVersion[1];
if (MajorMinorVersion == "11.0") {
// Citrix is OK
}
else {
window.navigate("WrongCitrix.aspx?Citrix=" + MajorMinorVersion);
}
}
catch (e) {
window.navigate("NoCitrix.aspx");
}
If the ActiveX component is not present, then redirection is a page that tells the user they need to install it. If the ActiveX component is any other version than 11.0, then the redirect is to a page that explains this and how to deal with the situation (backrevving for example).
An prior check during page load checks to make sure they have Internet Explorer v4 thru v9, because any other version will not work with the product (and IE10+ will crash if it even tries to load v11.0 of the ActiveX component).

If I understand your question, you can insert PlaceHolder control wherever you want inside the page.
<%# Page Language="C#" AutoEventWireup="True"
CodeBehind="Default.aspx.cs" Inherits="WebApplicationTelerik.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl(
"<script type=\"text/javascript\"> alert('here'); </script>"));
}

document.GetElementsByTagName("head")[0].appendChild( newScriptNode );
or jQuery
$("head")[0].append( newScriptNode );

If you really must insert JavaScript into the head tag, you can just make it an ASP.NET control and insert a control into it's child collection.
E.g. In the ASPX file:
<head runat="server" id="header">...</head>
In the code behind:
header.Controls.Add(new Literal("<script type='text/javascript'>...</script>"));
Although I do think you need to think about your process, it would be more efficient to redirect the user in the back-end before the page is rendered.
Oh and RegisterStartupScript correctly places your JavaScript after your html for increased load performance.

Related

Adding ASP.Net tags from javascript, why does this work?

I got an ASPX page with the folowing code behind
public partial class test : Page
{
protected void test(object sender, EventArgs e)
{
throw new Exception("test");
}
}
And the following ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Thumbnail</title>
</head>
<body>
<form id="form1" runat="server">
<div id="buttonTarget">
</div>
</form>
</body>
</html>
If I run the following javascript a button is added to the page:
$('#buttonTarget').html('<asp:Button runat="server" ID="tst" CssClass="buttons" OnClick="Test" Text="Test"/>');
The buttons shows the same way as an asp tag shows in element inspector.
And when I click the button the server sided function is called and the site breaks with the "test" exception
I know this isn't good practice but I want to know why this works. Why does this button call the server sided function and why is it displayed as a normal button ?
--EDIT--
The aspx code was a simplified version. The actual code used a gridview control and used javascript to insert rows in the table. These rows hold the tags.
Expanding on what #Mamun was probably saying, when the page is executing on the server, it's seeing the asp tag in the JS string and translating it into the appropriate HTML. If you view source on your page in the browser, you'll probably see something like this instead of the ASP tag in your JS call:
$('#buttonTarget').html('<input type="submit" name="ctl00$MainContent$tst" value="Test" id="MainContent_tst" class="buttons" />');

Firefox Fail - After using document.write and update to location.hash causes page refresh

Here is some HTML (Fiddle):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test Write</title>
<script>
function test() {
if (window.location.hash == '#test') {
alert('The hash is already set!');
} else {
document.open();
document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\
<html>\
<head>\
<title>Hello There!</title>\
<script>\
function test() {\
window.location.hash="test";\
}\
</'+'script>\
</head>\
<body>\
<button onclick="test()">Test Hash Now</button>\
</body>\
</html>');
document.close();
}
}
</script>
</head>
<body>
<button onclick="test()">Click to write new page</button>
</body>
</html>
If you run this - then click "Click to write new page" - it will write a new HTML fragment onto the document. This time there is a button to "Test Hash Now" - when you click all it does is update the window.location.hash.
In FireFox the page tries to reload again unexpectedly. In all other browsers it works fine. In Fiddle you will see an error message {"error": "Please use POST request"} if you create a HTML file it will work better, you'll see the "Click to write new page" button appear again after clicking "Test Hash Now" which is (or should be) wrong.
Why is this happening?
My use case is simple - I have a bootstrap page that contains a javascript that fetches a bunch of data using AJAX. It then generates a large HTML string (including doctype/head/body/etc) and then it just needs to render that HTML string.
In this case I am using an inline HTML as a constant - but in the real case it is generating it using some logic. I am trying to simulate what the server will respond with and eliminate any server side requirements for the client.
I would just have a bunch of HTML and JS files zipped up into one file, and I could give that to anyone (developer or not) to run without any need for a server or database. Then they could see the page as if it were the real-deal. That's my goal. If I simply put the HTML into an existing element on the page (such as just manipulating the body of the current page) - it won't behave EXACTLY the same as if the entire document were generated. Plus I want the bootstrap HTML file to be really small (with just one javascript include at the top).
Everything seems to work - except Firefox is the only one that fails. It all works unless there is a script referenced inside the page that needs to write something to the window.location.hash - then it tries to reload the whole page... Uggg...
Any better way to accomplish this?
I tried to create an iframe and using the same document.open();document.write(html);document.close() - but the same exact issue happens.
Try this code to push the hash state:
if (history.pushState) {
history.pushState(null, null, '#test');
}
else {
location.hash = '#test';
}
but I haven't tested it myself.
Added: Try naming your functions test1() and test2(). This won't fix it necessarily, but it may help to debug/discover what is happening.

How to tell if a page unload in ASP is a PostBack

This seems like a common question but search is not returning anything.
I have the following code that executes before the page unloads.The problem is if the unload is a postback i do not want to fire my warning to the user but i can't figure out how to differentiate between a postback and a user navigating to another page for example.
// This is executed before the page actually unloads
$(window).bind("beforeunload", function () {
if (prompt) {
//prompt
return true;
}
else {
//reset our prompt variable
prompt = true;
}
})
Running script in the code behind i.e. if Page.IsPostBack then set prompt is not an option.
Any ideas?
EDIT:
Here is the solution I ended up with:
function DoNotPrompt() {
prompt = false;
}
I then added this to all the controls where the user could do something that result in a post back.
OnClientClick="DoNotPrompt()
Then checked this flag and only returned a string in "beforeunload" if the user was really moving away from the page i.e. not a postback.
I also had to use this code:
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
prompt = false;
}
The reason being i had a custom user control that was a list box and I could not add the above method. So used this to catch that event and set the flag to false.
Not the most elegent solution.
Thanks,
Michael
You can capture the submit and reset the onbeforeunload as:
jQuery(function($) {
var form = $('form'), oldSubmit = form[0].onsubmit;
form[0].onsubmit = null;
$('form').submit(function() {
// reset the onbeforeunload
window.onbeforeunload = null;
// run what actually was on
if(oldSubmit)
oldSubmit.call(this);
});
});
This is a tested code from my pages :)
This may not cover all of the postback situations, but you can tell if the page was posted back by an ASP control by interrogating the __EVENTTARGET hidden input.
This input is set by ASP when the page is posted back by an ASP control.
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
}
JavaScript runs on the client; as far as the client is concerned, a page does not maintain state from one view to the next. Postbacks are entirely an ASP.NET concept.
You can get around this by running some code on the server-side which defines a JavaScript variable based on whether or not Page.IsPostBack is true.
Example:
<%# Page Language="C#" AutoEventWireup="true" %>
<!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>Page.IsPostBack -> client</title>
<script type="text/javascript">
var isPostback = <%= Page.IsPostBack %>;
console.log("IsPostBack: " + isPostback);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnTest" Text="Click me..." />
</div>
</form>
</body>
</html>

How to call javascript function from code-behind

I wrote a javascript with a asp.net page.
In Asp.net Page
<HTML> <HEAD>
<script type="text/javascript">
function Myfunction(){
document.getElementId('MyText').value="hi";
}
</script>
</HEAD> <BODY>
<input type="text" id="MyText" runat="server" /> </BODY>
In Code-behind
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("My")= "Hi" Then
I want to call "Myfunction" javascript function
End If
End Sub
How can I do?
One way of doing it is to use the ClientScriptManager:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
This is a way to invoke one or more JavaScript methods from the code behind.
By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked.
Next the alert will be displayed.
Next the DisableControls() method will be invoked.
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.
What you can take away from my example:
I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.
In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:
Front end code:
<div onclick="showHideModal();">
<asp:Calendar
OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server"
BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana"
Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%">
<OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle>
<DayHeaderStyle ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
<TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle>
<DayStyle BackColor="White"> </DayStyle>
<SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle>
</asp:Calendar>
</div>
Codebehind:
protected void DatepickerDateChange(object sender, EventArgs e)
{
if (toFromPicked.Value == "MainContent_fromDate")
{
fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
else
{
toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
}
asp:run javascript method
Add this line to the bottom of the page before </form> tag, at least under the js function you wrote.
the reason of doning this is avoid calling your method before your
browse knowing what is the funcion and finally do nothing.
<% Response.Write($"<script>yourfunction('{Config.id}');</script>"); %>
ps: I've tried all methods up there but nothing worked fine for me. And I figure out this easy and wonder way of calling js method on my own!

How to get scripts to fire that are embedded in content retrieved via the jquery load() method?

I have found several other questions here on S.O. (and the web in general) that ask roughly this same question, but the answers always seem to suggest other ways of structuring code that avoid the need for addressing this underlying issue.
For example, many people suggest (and a good suggestion, I agree) to put your code in the jquery load method's callback, on the calling page and not the called page. However I have unique scripts that may appear in certain resources, so I would not want to do that for every load and nor do I necessarily know what these scripts will be.
Here is a test setup to demonstrate what I'm trying to do. The short summary is that when I load partial.htm from main.htm, its script does not fire.
main.htm:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>main file</title>
</head>
<body>
<ul id="links">
<li>some page1</li>
<li>some page 2</li>
<li>some other partial page</li>
</ul>
<div id="panel" style="display:none; padding:20px; background-color:#CCC;">
LOADED CONTENT WILL GO HERE
</div>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(function(){
$('#links a').click(function() {
var $panel = $('#panel');
$panel.show();
$panel.html('Please wait...');
var href = $(this).attr('href');
$('#panel').load(href + ' #content');
return false;
});
});
</script>
</body>
</html>
OK, very simple functionality on this page. Imagine there are many more links, and some of them may require scripting while others do not.
Here is partial.htm:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>partial file</title>
</head>
<body>
<div id="content">
<p>Hey, I am the partial file!</p>
<script type="text/javascript">
alert('I am some JS in the partial file! But sadly I do not execute...');
</script>
</div>
<div>
I am some other content on the page that won't be included by jquery.load()...
</div>
</body>
</html>
Notice that my script in partial.htm does not fire. So, my question remains: how to get this to fire, excluding any answers that tell me to put this in the .load() method's callback. (This would be because I may not have the fore-knowledge of which scripts these partial pages may contain or require!)
Thank you!
Update #1:
I suppose an acceptable answer is simply "you can't." However, I'd like to know if this is definitively the case. I haven't been able to find anything that officially states this yet.
Also, when I use firebug to inspect the panel region afterwards, there is no script element present at all. It is as if it is being parsed out by load.
Update #2:
I've narrowed this down to be a problem only when using the selector as part of the href. Loading the entire "somepage.html" will execute the script, but loading "somepage.html #someregion" does not.
$panel.load('somepage.html'); // my script fires!
$panel.load('somepage.html #someregion'); // script does not fire
I'm going to try and hunt down why this may be the case in the jquery source...
Well it seems that this is by design. Apparently to make IE happy, the rest of us suffer. Here's the relevant code in the jquery source:
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
I'm wondering if, instead of just stripping out the scripts, I could modify the jquery source to include them in some other way that makes IE happy? I still have yet to find anything else on the web discussing this matter, I'm sure I'm not the only person stumped by this?
I have run across issues before with IE not running injected <script>s that didn't contain the defer attribute. This discussion thread has some good information about the topic: innerHTML and SCRIPT tag

Categories

Resources