How do I run a JavaScript or jQuery script before the page is rendered?
Specifically, I want to check if certain cookies exist.
If the cookies do not exist, I do not want to show the page content, but rather redirect immediately to an authentication page.
Currently, the page content is loaded and rendered, after which the browser redirects to the authentication page.
I have tried:
<body onload="checkCookies()">
...
</body>
As well as:
<head>
<script type="text/javascript">checkCookies();</script>
...
</head>
In both cases, the page in question is loaded, and then the cookies are checked.
How can I use JavaScript (or jQuery) and have the cookie-check take place before the rest of the page is loaded?
How do I run a JavaScript or jQuery script before the page is rendered?
Specifically, I want to check if certain cookies exist.
If the cookies do not exist, I do not want to show the page content, but rather redirect immediately to an authentication page.
Currently, the page content is loaded and rendered, after which the browser redirects to the authentication page.
I have tried:
<body onload="checkCookies()">
...
</body>
As well as:
<head>
<script type="text/javascript">checkCookies();</script>
...
</head>
In both cases, the page in question is loaded, and then the cookies are checked.
How can I use JavaScript (or jQuery) and have the cookie-check take place before the rest of the page is loaded?
Share Improve this question asked Jan 31, 2011 at 12:22 Alex ReynoldsAlex Reynolds 97.1k59 gold badges250 silver badges351 bronze badges4 Answers
Reset to default 7Don't do authentication with Javascript. It's trivially easy to evade -- you just need to turn off Javascript. Do your authentication checks using server-side code before you render the page.
Just use it like below:
<script type="text/javascript">
if(checkCookie()){
document.location="./configure/network.xml"
}
</script>
And put it to the top of your scripts. It worked for me
Use server side scripting for authentication. if you want to check the cookies using javascript then use this
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Wele again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
Check it Out -->
You can use prerender event of the page.
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
//If cookie doesn't exist redirect to the authentication page.
if (Request.Cookies["UserName"] == null)
{
//redirects to the authentication page.
}
}