I have a system where items are locked (with a flag in the database) when a user is vieiwing that item.
Currently the item is only unlocked when a user performs a certain action.
However, when a user leaves the page through any method, I'd like to make a call to a webservice / ashx page that will unlock the item, but not stop the page from changing.
I have a system where items are locked (with a flag in the database) when a user is vieiwing that item.
Currently the item is only unlocked when a user performs a certain action.
However, when a user leaves the page through any method, I'd like to make a call to a webservice / ashx page that will unlock the item, but not stop the page from changing.
Share Improve this question asked Feb 16, 2009 at 15:59 cjkcjk 46.5k9 gold badges83 silver badges113 bronze badges5 Answers
Reset to default 3What about using a "heartbeat" function to keep the lock alive while the page is loaded? Make a server call every, say, 15 seconds or so to renew the lock. Program your server-side code so that a lock will time out after 20 seconds if it hasn't heard the "heartbeat" from the page. When the user navigates away from the page, the heartbeat will stop, and the lock will be released a maximum of 20 seconds later.
What you are describing is not possible. The JavaScript thread/runtime lives within the scope of the loaded page, so when the page unloads the JavaScript is unloaded as well. When the asynchronous call returns and the browser has moved away from the page, the user will get a JS error.
You can make your web service/AJAX call synchronous and block until the server returns a response, but of course that means the page will wait for the response before unloading.
I managed to get this working in IE7 and Firefox 3 by using the body onbeforeunload event. I make a call using XmlHttpHandler to an asp http handler that unlocks the query. I had to set the state changed event handler to be null so there was no javascript error when it returned.
The event fires and the page changes, not delaying the user.
This can be solved using the Beacon API.
More about it here
I think you should be able to do a synchronous XHR call to your server.
If you're using jQuery:
$.ajax({
async:false,
url:"your_page.html",
data:"unlock=true",
type:"POST"
}).responseText;
Because it's not async, in theory it should pause browser execution until the results of this call is returned.