Reputation: 447
I have the following JS, currently it's just before my closing body tag
<script type='text/javascript' src='https://www.mydomain.com/jtrack.js'></script>
<script type='text/javascript' >
if (typeof trackPage == 'function') trackPage();
</script>
Part of this script sets a cookie, which I need to read in the Page_Load event of my asp.net page. But that event is firing before the cookie is set. How can I change this so the script runs first?
Thanks
Upvotes: 0
Views: 2985
Reputation: 53
Use JS setTimeout Eg.
ScriptManager.RegisterStartupScript(this, this.GetType(), "TestMessageModal", string.Format("setTimeout(function(){{swal('{0}','{1}');}},{2});", type, CommonUtils.RemoveSpecialCharacters(Message), timeout), true);
Upvotes: 0
Reputation: 13735
Simple answer, you can't. It is technically impossible.
If you look at the ASP.NET page lifecycle overview then you'll see that the page load event occurs before the page begins to render - which would make it completely impossible for the client to have executed JavaScript on the page at this point, the user agent (browser) hasn't even began to have received the page. With the sole exception of unload, all of the ASP.NET page lifecycle events happen on the server and before any response has been sent to the user.
The unload event is highly unlikely to ever execute after your JavaScript, unless you are streaming a response to the user, had the JavaScript (without dependencies) at the first possible point on the page, and were building a really complicated page response. Even if the JavaScript did somehow execute before the unload event fired, it wouldn't matter, as cookies are sent with the page request and that has already happened. The cookie will not be sent until the next request from that domain (although it doesn't have to be a page that is requested, images, scripts or stylesheet requests will all include the cookie in their request headers).
You can have your JavaScript set the cookie on the first request which will then be available to all subsequent requests in the Load event handler, and use an Ajax request (if necessary) to log that initial page and the assigned cookie value - which will be sent (assuming it has been set at that point) in the headers for the Ajax request.
What you can't do is set a cookie on the browser of a user before the user has visited your site, execute JavaScript before it has been sent to the user, or send new request data part way through a response.
Upvotes: 3