Reputation: 834
I have a situation where I want to confirm a user is still allowed to edit a page when the page gets focus. This will prevent them from giving up editorship in one tab and then returning to edit in the original tab, or giving up editorship and then using the browser BACK button to return to the page where they could still edit. window.onfocus works perfectly for this in IE, FF, and Safari, but not in Chrome. Is this correct? Am I missing something obvious? Is there a workaround? Here is the code that works in IE, FF, and Safari:
$(window).bind('focus', function() {
$.getJSON("do_check.php", {id: 'foo'}, function(data){
if (! data.SUCCESS) {
$("#not_editor_dialog").dialog('open');
}
});
});
Note that the above binds the event with jQuery, but the jQuery-less version also fails in Chrome:
window.onfocus = function() {
etc.
};
Thanks!
Upvotes: 2
Views: 5297
Reputation: 302
None of the above seem to work. They just fire way too many times.
I believe this is also a way to go:
var focused = false;
$(window).bind('focus', function() {
if (!focused ) {
// *
// * Do stuff on focus here
// *
focused = true;
}
});
$(window).bind('blur', function() {
if ( focused ) {
focused = false;
}
} );
Should be able to do without jQuery too!
Upvotes: 1
Reputation: 322502
Works for me in Chrome.
Example: http://jsfiddle.net/KuZSu/ (click the bottom right panel to focus)
$(window).bind('focus', function() {
$('body').append('focused<br>');
});
If the getJSON()
request isn't working for you, it may be because Chrome has security issues with making AJAX request when you're hosting the page from the filesystem.
See this question: Problems with jQuery getJSON using local files in Chrome
A solution offered in a comment on that page comes from Nick Craver: "Try launching chrome via command line using --disable-web-security and see if it works?"
Upvotes: 0