I just read this question: Full Screen Page by pressing button instead of F11
The op asked to replace F11 with other hot keys, so I'm wondering that maybe I can simulate press F11 to get things work.
I learned that I can use trigger in JQuery to simulate key press event, so I do something like this:
$("body").keyup(function (e) {
alert(e.which);
});
var e = $.Event("keyup");
e.which = 122; // # Key code of F11
$("body").trigger(e);
When I run this, I got the alert says 122, but it seems that it doesn't give the hoped result. Is there a restriction there?
I made a fiddle here: http://jsfiddle.net/ap295/5/
I think this is the one :) to detect it ...
$(document).keyup(function(e){
if(e.which==122){
e.preventDefault();//kill anything that browser may have assigned to it by default
//do what ever you wish here :)
alert('F11 pressed');
return false;
}
});
but triggering it (NOT POSSIBLE)
But you will not prevent the browser from full screen :) ...
Reson given is that , lets say I have full screened it somehow, and wish to toggle out of it using F11 but u are preventing me, I would have to restart PC, [computer illiterates] which poses security risk as you are preventing a user from doing something he is expecting to do, and they may think PC is broken or something :) so ...there you are.
You can not do this. The linked answer in that question provides a way with jQuery to simulate key-presses, within the jQuery event framework.
You simply can not trigger or fake keypresses. So the answer of this question is:
No, this is impossible
You won't be able to override the browser's built-in hotkeys from within a web page.
You might be able to do it in a browser extension, but that's would surely be serious overkill just to change the application's hotkeys.
In any case, why would you even want to override the standard keyboard shortcuts? I don't get that. They've been standard for a long time; most users will be familiar with them, and will find it very odd if they've been changed to something else.
Don't look at is as a question of "How do I trigger F11?" - look at is as "How do I trigger or simulate full-screen?"
With older versions of IE you can open a new window straight into full-screen:
window.open(someURLorOther, '', 'fullscreen=yes, scrollbars=auto');
Or you can use window.open to open a new window of a specific size.
Or you can try to resize the current window to fill the screen:
moveTo(0,0);
resizeTo(screen.availWidth,screen.availHeight);
However just because you can doesn't mean you should. You should never resize the current window - this annoys practically everyone. Opening a new window to a size you choose is more reasonable, though if it's too big it can be annoying, and on a normal web page (where by "normal" I probably mean not some kind of browser-based data-entry app) it is nicer not to open new windows.
Related
Hi I would like to customize my pop up for leaving a page, is there any simple way to do that?
I am using simple jQuery
$(document).ready(function() {
var myPopUp = $('#pop-up').css('display', 'block');
$(window).bind('beforeunload', function(){
return 'load my pop up here instead of the default browser message';
});
});
my html for the pop up is which is hidden by default
<div id="pop-up">
<h2>Are you sure wanna leave</h2>
Leave
Stay
</div>
Thanks
Short answer: You can't.
Longer answer:
For rather obvious "security" reasons it is very limited what you can do when a user tries to navigate away from a page / close a tab or in any other way leave the site.
The reason is that browsers want to make absolutely sure that you cannot prevent the user from closing a tab or window that he / she wants to close.
Therefore the onbeforeunload javascript event - and by extension the beforeunload jQuery event - are extremely limited in what they can do. One of the things they definitely cannot do is prevent the page from closing - except using one very standardized and rather boring method the browser (usually) allows.
Some browsers allow you to specify a message, while others (including firefox) do not even allow you to change the message (because you might trick the user by asking "Can I adopt your unborn son?")... AFAIK most browsers allow you to specify a string of your choosing in addition to a standard message that cannot be changed. Some browsers (no major desktop browsers) even lack the event completely.
What you want to achieve is basically to force the user to stay on your page, and then show a nice pop-up asking them to confirm... and while this could definitely improve the user experience in a lot of cases, you don't have to think very hard to imagine how it could be abused to simply not allow the user to ever leave.
Think about how annoying sites that break the back-button are, then imagine they could even remove your ability to close a tab!
I stumbled on this rather amusing forum question from a user who has spent an extensive amount of time trying to prevent even what little annoyance can be added - a short excerpt:
I do not like onunload and onbeforeunload. I do not think they should
EVER be fired on my firefox installation. I do not think there is any
useful application of these events, not even the benevloent "you have
unsaved work!" popups. When I tell my web browser to close a web page,
I do not want a web page to prevent (or delay) the browser from
closing it--at all ever.
And just to add a little bit of somewhat official information:
mozilla.org: WindowEventHandlers.onbeforeunload:
Since 25 May 2011, the HTML5 specification states that calls to
window.alert(), window.confirm(), and window.prompt() methods may be
ignored during this event. See the HTML5 specification for more
details.
This question have been asked and answered in several stackoverflow posts such as this one
If you can also elaborate on what the circumstances of leaving the "page", you could probably get a better and proper answer.
If you want to warn that user should save before then checkout the top post of the link. If you just want to warn before you leave the page,
try this answer that user Hunter left:
<script type='text/javascript'>
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
</script>
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility
its is not possible to have a custom popup see the link specified
I have a link that opens a new window using window.open. The pop up works fine, however the normal web page stops loading objects (images, scripts, ajax scripts) and sometimes the page doesn't load at all.
Here is my code:
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
Is there anything I am doing wrong?
Thanks,
Peter
First of all, please be more specific: tell us more about your browser and which version, and possible your OS. It could be more related to the browser than to the web content.
Then on to the possible problem; you start with saying "I have a link that ...".
To me that sound like you use <a href="javascript:DoSomething()">. Or perhaps <a href="#" onclick="DoSomething()">.
I tried both in some modern browsers: Chrome v37, IE v11. Both browsers did not produce what you describe:
- Chrome v37 will happily keep on loading, even if I immediately click a "window.open()"-link on top of a (huge) webpage;
- IE v11 will someshow show "false", which is strange, but still not what you got.
In some cases I also got to deal with the popup blocker.
A general tip might be to NOT USE <a href> for things like this. Behaviour seems inconsistent across browsers, also these days there are better alternatives, such as <span onclick="">...</span> and <button onclick="">...<button> or by using JQuery or other frameworks (which I do not know much about).
Although this many not be a conclusive answer, maybe this can help you experiment on your own, and think about possible causes or alternative ways of doing things.
The behaviour you describe should definitely NOT normally happen. This is confirmed by robbmj's JSFiddle, that fails to reproduce the problem. That's evidence that something is going on in the main page that is not plain vanilla page loading, or your "link opening" has something unusual to it. Apart from the syntax error (you use four parameters, not three).
Since you do not supply information on either of these points (how do you load the main page? How do you trigger the popup-opening code?), we do not even know if the problem
might be browser-related; I'd start and try to test things in IE, Chrome and Mozilla to see
whether anything changes; this might provide some useful insights.
One possibility
A very strong possibility is that your inadvertent fourth parameter goes into the window.open() "replace" parameter, which is a boolean, and triggers undefined behaviour or simply an error that stops everything. You should have things somewhat working in IE and not working at all in Firefox.
You should also be able to see whether this is the case by using Firefox and the Firebug extension, or the Web Developer Console in Chrome.
Another possibility
A more esoteric possibility is that the way you define the link might make the browser believe you've actually moved on to another page, so that there's no point in continuing loading the current page. Depending on the browser, this might have to do with how the link is defined and could be remedied by defining it some other way.
For example it could conceivably happen if you had
...
which I suspect is what led user Tomzan to ask, "is the link something like javascript:...?"
So if this is the case, try with this instead (this works for me in IE9/Chrome/FF):
link
function openPopup() {
MyWindow = window.open('player.php', 'Player', 'width=500, height=300');
// Also try the following. You won't probably like the results (it should send the
// popup window behind), but if it works, it proves we're dealing with a browser
// issue there.
// Blur and refocus
// MyWindow.blur();
// window.focus();
// Just focus
// window.focus();
return false;
}
Workaround
A possibly acceptable workaround could be to disable the link altogether (or hide it via CSS), and only reactivate/show it upon main document being ready. This sidesteps the problem, even if user experience could be somewhat worse due to a longer wait.
But if it's so likely that a user clicks on the link before waiting for the whole page to load, I'd also consider not automatically loading the rest of the page at all, and reorganize information to provide a more streamlined navigation. Or maybe distribute it on two sequential pages. Again, unfortunately you did not supply enough information to do more than guess.
As you probably know, JavaScript is single threaded. Every event is queued until there is idle time for it to be executed.
In the case of window.open, both windows must share a single context to keep it thread-safe because the opened window can access to it's parent using window.opener.
I don't know how browsers implements it, but we can guess two possibilities:
Idle time is shared between the two windows. It means if the popup does many blocking statements, it can freeze the main window's events.
Only one of the two windows can be active, which depends on which one has the focus. In that case, all events may be paused in the main window when you're using the popup.
If you want a more precise answer, I need more details about your code.
document.addEventListener("DOMContentLoaded", function () {
//whatever the code
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
}, false);
Try to wrap the code in SetTimeout
setTimeout(function () {
window.open( .. )
}, 0);
Your document should be loaded first, then popup should be open, So write your javascript code in the scope of $(document).ready().
enter code here
$(document).ready(function(){
$("#clickme").click(function(e){
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
});
});
UPDATE: there is something going on with the page I am trying to have the onbeforeunload work on. I set it up in the layout and it pops up for every page besides that one... So there has to be some broken javascript, or a javascript file that redefines onbeforeunload. Since it can only be defined once
I am working on a Rails project and I am setting up a pop up to alert the user that their data will be lost if they leave the page without saving. So I am using window.onbeforeunload
I set it up on one page by adding this script code to the top of the view file
var saving = false;
window.onbeforeunload = function(){
if(!saving)
return 'Are you sure you don\'t want to save before you leave?';
};
where saving is set to true if the user hits the save button, which redirects them to a separate page.
The problem is coming up when I try to set up the EXACT same thing on a separate view file, that also needs the same functionality.
Except when I drop the code above into the file no pop up is given, at all... at any point. So then I looked around at other available options to set up the onbeforeunload function.
So I currently have it set up as:
var saving = false;
window.onbeforeunload = displayConfirm();
function displayConfirm(){
if(!saving){
if(confirm('If you leave without saving, your changes will be lost. Press cancel to go back to save')){
confirmExit();
}
}
}
on the second page. My issue is the pop up here doesn't work the same as the first implementation. Even weirder, the pop up shows up on window load... NOT before window unload.
I have been looking around and messing around with this for a few hours now. I am starting to get really irritated since this should have been an easy addition. Seeing as how it is already set up on a separate page, and working correctly. Any insight onto what maybe going wrong, or if I am making a stupid mistake, would be greatly appreciated.
Thanks,
-Alan
1) window.onbeforeunload = displayConfirm(); -- you're firing the function, instead of assigning it
2) onbeforeunload is great, but it's unsupported in a lot of ways. Some browsers don't even have it, period (all but the most recent Opera, for example), so if you're doing this for a wide audience, or you need it to work 100% cross-browser, onbeforeunload is sadly not enough on its own.
Try with
window.onbeforeunload = displayConfirm;
You are actually calling the function right away and assigning the return value of displayConfirm() to window.onbeforeunload.
Update
But you are limited to exactly one return statement in your onbeforeunload-function, see here. So calling "confirm" or some other custom function does not work.
Recently i was working on a project using this event, so i did do some search on the net.
There are few thing need to be taken into consideration when using the onbeforeunload event.
It is not supported by all browser. Opera, especially older version.
Some support it partially, such as not firing when refresh button is pressed.
Using this event will cause the page will not be cached.
Here is an article that is more thorough about the onbeforeonload event by Patrick Hunlock.
is there a way differentiate between refresh and close in Javascript? i use window.onbeforeunload now which works great in IE. To void this being called anywhere but close, i set a flag on EVERY button ...this seems like a difficult, hacky solution, but after searching for hours on google, it was the best i could find.
Isn't there an onclose event for IE????? or onclick?
I only need to support IE, not FF, so please don't post anything FF related, I can't use it.
Thanks!
As far as I know there is no way to trap in JavaScript the click of the X (close) button in any browser. In my opinion this is due to security concern... JavaScript can't (an will never be able to) listen to OS messages like the close of the current window.
The only solution I know (which is what you seem to use) is:
<body onunload="alert('Fired');">
But as you find out if fires on close and on reload. Again this is normal behavior because, AFAIK, for the JS engine a reload is the same as a close then a reopen of the same page.
AFAIK, no there is no IE specific onclose event.
This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 6 years ago.
After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser.
I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or Alt-F4.
My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem.
Thank you.
Aggregated Responses of OP
------
Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or Ctrl-R. My requirement is to make a variable false on Refresh. I am just able to do it on F5, but all other ways are still out of my reach. The same would be applied to Back button.
Hi ppl, Thanks for all who replied at least. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code:
document.onclick = function() {
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc.
Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on every link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again.
Is there no one who can think of a solution here!!! where are all the experts???
The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator.
What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response.
Bottom line is not only can what you are trying do not be done it should not be done.
I think you need to go back to your seniors and explain to them that a Web UI is a guest hosted by a browser on a client machine. This guest status is an important one.
Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No?
Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs.
Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place.
All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.
Add this script to your HTML:
window.onbeforeunload = function (e)
{
e = e || window.event;
var y = e.pageY || e.clientY;
if (y < 0){
return "Do You really Want to Close the window ?"
}
else {
return "Refreshing this page can result in data loss.";
}
}
In your function:
document.onclick = function()
{
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
blnShowMsg will be true for any click on your page except sometimes when the user click a link. I say sometimes because if event.srcElement.tagName doesn't work in some browser it will allways be true. And you have to add lots of cases to to allow using form controls etc... Some browsers can even automatically reload a page, and I'm not sure if onload events will run then or not.
But popping a warning about leaving the page (or similar) all the time is sure to annoy a lot of people, and they'll probably leave permanently...
If you're making for instance a online program where it's critical that something is saved before leaving, I'll say that catching the before unload event is a little too late, better to make some kind of autosave (see Gmail) and/or some kind of non-obtrusive warning when the user mouseover the navigation menues without saving.
But you can't force stupid users not to do anything stupid, on a web interface this is even more true because you have less controll: if the user want to terminate the program before saving they will find a way to do so, and they will call you and complain when the unsaved data dissapears ;P
I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every postback.
I believe there was some ways to do this in some browsers (and probably not very reliably) some years ago. Because I remember those awful massive spam-popups that spawned more popups as you closed one. But that's why it's not a good idea to allow scripts to detect this, and why browsers should prevent it and most modern browsers probably does.
I was asked to do something similar for a survey invitation script; they wanted to ask the visitor if they would like to answer a survey about their website, and then the survey should pop up when they leave the site. The solution I found was to (repeatedly) explain the management that this was probably impossible, or at best very unreliable; and instead the survey should popup immediately (if the visitor agreed to take the survey) and the intro page should tell the visitor to leave this window open and go back to it after reviewing the page.
onunload and onbeforeunload are not meant for this, so will naturally be unreliable.
A better solution is to change the problem. Have the client send a heartbeat, periodically telling the server the page is still active. When the hearbeat stops, you know you can clean up the server.
You might find this interesting: https://stackoverflow.com/a/3586772/1483977
Or this: Identifying Between Refresh And Close Browser Actions
"Thanks buddy, but I have already gone through that and didn't find much help there
too. My seniors are not happy with that solution as putting a flag on evry link of my
application is a complicated job and they fear of breaking the application. Any other
suggestions would be appreciated. Thanks once again."
If you use jQuery, you can add link flags automatically. The way I would handle your problem is when the user performs the "dangerous" actions, iterate all the page links that are "dangerous" and then bind events to them.
$("#dangerbutton").click(function(){
$("a").not( safeList ).click(function()
{
var dest = $(this).attr('href');
someWarningFunction(function(){
/* Stay where we are because user opted to stay */
},function(){
/* Continue Following Link because user didn't mind */
window.location= dest;
});
return false;
});
});
This way will only fire on link clicks on your page. Users have to get used to the fact that "close window == cancel everything" logic, because many use and trust that facility.
You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.
Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.
Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.