How do I capture the input value on a paste event? - javascript

On my site users can paste text (in this case a url) into an input field. I'd like to capture the value of the text that was pasted using jQuery. I've got this to work in FF using the code below, but it doesn't work in IE (I don't think IE supports the "paste" event).
Anyone know how to make this work across all modern browsers? I've found a few other answers to this on SO but most are FF-only and none seemed to offer a complete solution.
Here's the code I have so far:
$("input.url").live('paste', function(event) {
var _this = this;
// Short pause to wait for paste to complete
setTimeout( function() {
var text = $(_this).val();
$(".display").html(text);
}, 100);
});
JSFiddle: http://jsfiddle.net/TZWsB/1/

jQuery has a problem with the live-method with the paste-event in the IE; workaround:
$(document).ready(function() {
$(".url").bind('paste', function(event) {
var _this = this;
// Short pause to wait for paste to complete
setTimeout( function() {
var text = $(_this).val();
$(".display").html(text);
}, 100);
});
});
Fiddle: http://jsfiddle.net/Trg9F/

$('input').on('paste', function(e) {
// common browser -> e.originalEvent.clipboardData
// uncommon browser -> window.clipboardData
var clipboardData = e.clipboardData || e.originalEvent.clipboardData || window.clipboardData;
var pastedData = clipboardData.getData('text');
});

Listen for the change event as well as paste. change will reliably fire on a changed field before submission, whereas paste only happens on browsers that support it on an explicit paste; it won't be triggered by other editing actions such as drag-and-drop, cut-copy, undo-redo, spellcheck, IME substitution etc.
The problem with change is that it doesn't fire straight away, only when editing in a field is finished. If you want to catch all changes as they happen, the event would be input... except that this is a new HTML5 feature that isn't supported everywhere (notably: IE<9). You could nearly do it by catching all these events:
$('.url').bind('input change paste keyup mouseup',function(e){
...
});
But if you want to definitely catch every change quickly on browsers that don't support input, you have no choice but to poll the value on a setInterval.

Even better is it to use e.originalEvent.clipboardData.getData('text'); to retrieve pasted data;
$("input").on("paste", function(e) {
var pastedData = e.originalEvent.clipboardData.getData('text');
// ... now do with pastedData whatever you like ...
});
This way you can avoid timeouts and it is supported on all major browsers.

Maybe try using the onblur event instead. So the user c/p into the input and when they leave the field the script checks what's there. This could save a whole lot of hassle, since it works for mouse and key c/p as well as manually entered input.

Related

How to programmatically copy asynchronous dependent content to the clipboard following a click?

I'm trying to programmatically use the execCommand in Chrome (Build 43) to copy the result of an asynchronous JSONP request to the clipboard. Here is a snippet of the logic :
loadContent()
function loadContent(callback) {
$.getJSON('http://www.randomtext.me/api/lorem/p-5/10-20?&callback=myFunc',function(result){
console.log('result=',result.text_out);
$("#container").html(result.text_out);
if (callback) {
callback();
}
});
}
function copyAjax() {
loadContent(copy);
}
function copy() {
var copyDivText = $('#container').text();
console.log('copyDivText=',copyDivText);
executeCopy(copyDivText);
}
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("copy").onclick = copy;
});
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("copyAjax").onclick = copyAjax;
});
// Copy text as text
function executeCopy(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
document.execCommand('Copy');
input.remove();
}
I know that starting build 43 of Chrome you code use the execCommand with clipboard. The problem, however is that you need to do it in within the execution of a user originated event (In which the permissions are elevated).
This is a similar restriction that ZeroClipboard flash based solution has.
Except from getting an answer that it is not possible (which is what I ponder about now), these are the other options I thought of doing as last resort(warning, they are all Hail Mary Passes):
Since JSONP cannot be synchronous, turn it to something that uses regular AJAX call and make sure that AJAX call is synchronous within the execution context of the user event. This goes against my deeply rooted belief we should not do synchronous XHR calls since it degrades user experience.
As the user approaches with the mouse to the copy button, we preemptively send the server request and hope it's fast enough before the user clicks the button. This is an obvious race condition which might not part of the time and will not work for certain when the use wants to do a Ctrl/Command-C instead of clicking the copy button.
Perform a two step process. One click to trigger the call, when the content is available, show a message the content is available and press another click on the msg area to copy to clipboard. It does not seem like the best UX interaction ever. I've created this example with this alternative.Triggering a click programmatically does not constitute a user issues event.
There might be a way to create a simple Chrome extension, and let the user set the permission for that extension to copy to the clipboard. This involves but the end user having to install and extension and change local browser settings. Not sure that many users will be capable/willing to do so.
I've already looked into Stackoverflow questions such as this, but they do not address an asynchronous scenario.
Please let me know if you can find any other workable solution (or a tweak on the existing one).
This is working timeout approach based on your snippet:
HTML:
<div id="container">
Enter Text To Copy</br>
<textarea id="clipboard"></textarea>
</div>
<input type="button" value="Copy" id="copy"/>
JS:
var timeout = 600; // timeout based on ajax response time
var loaded = false;
function loadContent() {
loaded = false;
$.getJSON('http://codepen.io/gkohen/pen/QbvoQW.js',function(result){
document.getElementById("clipboard").value = result.lorem;
loaded = true;
});
}
// Copy text as text
function copy() {
clipboard = document.getElementById("clipboard");
if (!loaded || clipboard.value.length == 0) {
alert("Ajax timeout! TIP: Try to increase timeout value.");
return;
}
clipboard.focus();
clipboard.select();
if (document.execCommand('Copy'))
alert("Successfuly coppied to clipboard!");
// set defaults
clipboard.value = "";
loaded = false;
}
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("copy").onmousedown = loadContent;
document.getElementById("copy").onclick = function() {
setTimeout(copy, timeout); // wait for ajax
}
});
The main issue is execCommand specification. There are some restrictions about security and trusted actions. So you have to make event calling copy and ajax call aparte. This can be done dirty way - by fixed timeout (code above) or proper way - by breakable sleep. New sleep feature is mentioned here and maybe can be modified to breakable variant via clearTimeout, but I did not try.

Copy to Clipboard for all Browsers using javascript

I was trying to make "Copy to Clipboard" work on all browsers but no luck.
Am using javascript and I don't want to use Zero Clipboard to do.
Please let us know what wrong in my code.
Appreciate for your help.
Below is the code (Currently my code is working only on IE browser):-
<script type="text/javascript">
function copyToClipboard(s)
{
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes['#mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes['#mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
var copytext=meintext;
str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
</script>
<textarea id='testText' rows="10" cols="100">Enter your Sample text</textarea><br />
<button onclick="copyToClipboard(document.getElementById('testText').value);" >clipboard</button><br /><br />
<textarea rows="10" cols="100">Paste your text here</textarea><br />
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body).
It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).
The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.

How to get copied value from ctrl+v key event in javascript

This method detects ctrl + v event but I couldnt find how to get the value of it ?
Thanks in advance,
$(".numeric").keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
switch (event.keyCode) {
case 86:
if (event.ctrlKey) { // detects ctrl + v
var value = $(this).val();
alert(value); // returns ""
}
break;
}
All you have to do it hook into the paste event, let it finish by breaking the callstack and then read the value.
It might seem ugly but it is very crossbrowser friendly and saves you creating a lot of crappy code just to read the actual clipboard.
$(".numeric").bind('paste', function (event) {
var $this = $(this); //save reference to element for use laster
setTimeout(function(){ //break the callstack to let the event finish
alert($this.val()); //read the value of the input field
},0);
});
See it in action here: http://jsfiddle.net/Yqrtb/2/
Update:
Since i just recently had to do something similar, i thought i'd share my final implementation, it goes like this:
$('textarea').on('paste',function(e) {
//store references for lateer use
var domTextarea = this,
txt = domTextarea.value,
startPos = domTextarea.selectionStart,
endPos = domTextarea.selectionEnd,
scrollTop = domTextarea.scrollTop;
//clear textarea temporarily (user wont notice)
domTextarea.value = '';
setTimeout(function () {
//get pasted value
var pastedValue = domTextarea.value;
//do work on pastedValue here, if you need to change/validate it before applying the paste
//recreate textarea as it would be if we hadn't interupted the paste operation
domTextarea.value = txt.substring(0, startPos) + pastedValue + txt.substring(endPos, txt.length);
domTextarea.focus();
domTextarea.selectionStart = domTextarea.selectionEnd = startPos + pastedValue.length;
domTextarea.scrollTop = scrollTop;
//do work on pastedValue here if you simply need to parse its ccontents without modifying it
}, 0);
});
It's very much browser dependent. The data is in the event passed to your handler. In safari/chrome, we are listening for the paste event on the input and then doing
event.clipboardData.getData('text/plain')
in the callback and it seems to work ok. You should use your favorite debugger and put a breakpoint into your paste event handler, and look at the event that is passed in.
You need a hack. I've detailed one on Stack Overflow a few times before:
How can I get the text that is going to be pasted in my html text editor?
Pasting into contentedittable results in random tag insertion
JavaScript get clipboard data on paste event (Cross browser)
It's very simple, code below works fine, in my case takes text contained on clipboard.
function onPaste(info) {
var copied = event.view.clipboardData.getData("Text");
alert(copied);
}
In this case variable called copied contains the value that you need.

Copy to clipboard without Flash

I found many solutions for copying to the clipboard, but they all either with flash, or for websites side.
I'm looking for method copy to clipboard automatically, without flash and for user side, it's for userscripts and of course cross-browser.
Without flash, it's simply not possible in most browsers. The user's clipboard is a security-relevant resource since it could contain things like passwords or credit card numbers. Thus, browsers rightly don't allow Javascript access to it (some allow it with a warning shown that the user has confirm, or with signed Javascript code, but none of that is cross-browser).
I had tryed the flash solution and I don't liked too. Too complex and too slow. What I did was to create a textarea, put the data into that and use the browser "CTRL + C" behavior.
The jQuery javascript part:
// catch the "ctrl" combination keydown
$.ctrl = function(key, callback, args) {
$(document).keydown(function(e) {
if(!args) args=[]; // IE barks when args is null
if(e.keyCode == key && e.ctrlKey) {
callback.apply(this, args);
return false;
}
});
};
// put your data on the textarea and select all
var performCopy = function() {
var textArea = $("#textArea1");
textArea.text('PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.');
textArea[0].focus();
textArea[0].select();
};
// bind CTRL + C
$.ctrl('C'.charCodeAt(0), performCopy);
The HTML part:
<textarea id="textArea1"></textarea>
Now, put what do you want to copy in 'PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.' area.
Works fine for me me. You just have to make one CTRL+C combination. The only drawback is that you are going to have an ugly textarea displayed in you site. If you use the style="display:none" the copy solution will not work.
clipboard.js has just been released to copy to clipboard without the need of Flash
See it in action here > http://zenorocha.github.io/clipboard.js/#example-action
It's finally here! (As long as you don't support Safari or IE8... -_- )
You can now actually handle clipboard actions without Flash. Here's the relevant documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en
https://msdn.microsoft.com/en-us/library/hh801227%28v=vs.85%29.aspx#copy
While waiting impatiently for Xbrowser support of the Clipboard API...
This will work beautifully in Chrome, Firefox, Edge, IE
IE will only prompt the user once to access the Clipboard.
Safari (5.1 at the time of writing) does not support execCommand for copy/cut
/**
* CLIPBOARD
* https://stackoverflow.com/a/33337109/383904
*/
const clip = e => {
e.preventDefault();
const cont = e.target.innerHTML;
const area = document.createElement("textarea");
area.value = e.target.innerHTML; // or use .textContent
document.body.appendChild(area);
area.select();
if(document.execCommand('copy')) console.log("Copied to clipboard");
else prompt("Copy to clipboard:\nSelect, Cmd+C, Enter", cont); // Saf, Other
area.remove();
};
[...document.querySelectorAll(".clip")].forEach(el =>
el.addEventListener("click", clip)
);
<a class="clip" href="#!">Click an item to copy</a><br>
<a class="clip" href="#!"><i>Lorem</i></a><br>
<a class="clip" href="#!"><b>IPSUM</b></a><br>
<textarea placeholder="Paste here to test"></textarea>
All browsers (except Firefox which is able to only handle mime type "plain/text" as far as I've tested) have not implemented the Clipboard API. I.e, trying to read the clipboard event in Chrome using
var clipboardEvent = new ClipboardEvent("copy", {
dataType: "plain/text",
data: "Text to be sent to clipboard"
});
throws: Uncaught TypeError: Illegal constructor
The best resource of the unbelievable mess that's happening among browsers and the Clipboard can be seen here (caniuse.com) (→ Follow the comments under "Notes").
MDN says that basic support is "(YES)" for all browsers which is inaccurate cause one would expect at least the API to work, at all.
You can use a clipboard local to the HTML page. This allows you to copy/cut/paste content WITHIN the HTML page, but not from/to third party applications or between two HTML pages.
This is how you can write a custom function to do this (tested in chrome and firefox):
Here is the FIDDLE that demonstrates how you can do this.
I will also paste the fiddle here for reference.
HTML
<p id="textToCopy">This is the text to be copied</p>
<input id="inputNode" type="text" placeholder="Copied text will be pasted here" /> <br/>
copy
cut
paste
JS
function Clipboard() {
/* Here we're hardcoding the range of the copy
and paste. Change to achieve desire behavior. You can
get the range for a user selection using
window.getSelection or document.selection on Opera*/
this.oRange = document.createRange();
var textNode = document.getElementById("textToCopy");
var inputNode = document.getElementById("inputNode");
this.oRange.setStart(textNode,0);
this.oRange.setEndAfter(textNode);
/* --------------------------------- */
}
Clipboard.prototype.copy = function() {
this.oFragment= this.oRange.cloneContents();
};
Clipboard.prototype.cut = function() {
this.oFragment = this.oRange.extractContents();
};
Clipboard.prototype.paste = function() {
var cloneFragment=this.oFragment.cloneNode(true)
inputNode.value = cloneFragment.textContent;
};
window.cb = new Clipboard();
document.execCommand('copy') will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:
var textNode = document.querySelector('p').firstChild
var range = document.createRange()
var sel = window.getSelection()
range.setStart(textNode, 0)
range.setEndAfter(textNode)
sel.removeAllRanges()
sel.addRange(range)
document.execCommand('copy')
There is not way around, you have to use flash. There is a JQuery plugin called jquery.copy that provided cross browser copy and paste by using a flash (swf) file. This is similar to how the syntax highlighter on my blog works.
Once you reference the jquery.copy.js file all you need to do to push data into the clipboard is run the following:
$.copy("some text to copy");
Nice and easy ;)

Prevent a webpage from navigating away using JavaScript

How to prevent a webpage from navigating away using JavaScript?
Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:
window.onbeforeunload = function() {
return "";
}
Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.
In older browsers you could specify the message to display in the prompt:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.
Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.
(function () {
var location = window.document.location;
var preventNavigation = function () {
var originalHashValue = location.hash;
window.setTimeout(function () {
location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
location.hash = originalHashValue;
}, 0);
};
window.addEventListener('beforeunload', preventNavigation, false);
window.addEventListener('unload', preventNavigation, false);
})();
Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
In Ayman's example by returning false you prevent the browser window/tab from closing.
window.onunload = function () {
alert('You are trying to leave.');
return false;
}
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
JSFiddle example
altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.
That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.
In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).
A more appropriate error message might be:
window.onbeforeunload = function() {
return "If you leave this page, you will lose any unsaved changes.";
}
Or stackoverflow style: "You have started writing or editing a post."
If you are catching a browser back/forward button and don't want to navigate away, you can use:
window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});
Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});
If you need to toggle the state back to no notification on exit, use the following line:
window.onbeforeunload = null;

Categories