开发者

How to run JavaScript or jQuery script before page is rendered

开发者 https://www.devze.com 2023-02-08 04:03 出处:网络
How do I run a JavaScript or jQuery script before the page is rendered? Specifically, I want to check if certain cookies exist.

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 q开发者_高级运维uestion 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?


Don'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("Welcome 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.
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消