Leaving Website Notification - javascript

I have this jQuery script that alerts the user when they're exiting to a third party website. Works fine when you just click on it, but if the user ctrl+clicks or right click > open new tab the warning message doesn't display. How can I amend this code to have the notification appear regardless of how the user clicks/opens the link?
// notification when exiting to third party website
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are now leaving...."))
{
// return back to page on no.
e.preventDefault();
};
});
This is a Credit Union regulation, so I'm not a butthead for doing so.

The right click that is context menu is a browser feature. You have to either disable it completely or create your own context menu using HTML.
Here is an answer to address the issue of ctrl+click.
If the key is pressed and if it is the ctrl key, just add e.preventDefault()
$(document).keydown(function (e) {
if(e.which==17)
e.preventDefault();
});
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are now leaving...."))
{
e.preventDefault();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
G

Related

Safari Extension Showing Popover Different Window

I'm trying to build a Safari Extension where when a user hits Command+B it will show the popover. Using the code below it works but always shows the popover on a different window not the current window/tab. I would like it to display the popover on the current window instead of switching to a different window and opening the popover there. It works perfectly if there is only one Safari window open but starts to have problems when multiple windows are open.
Any ideas?
Global Page File:
<script>
safari.application.addEventListener('message', function (e) {
if (e.name == 'Show Popover') {
safari.extension.toolbarItems[0].showPopover();
}
}, false);
</script>
Injected Content:
document.addEventListener("keydown", keydown);
function keydown(event) {
if ( event.metaKey && event.keyCode == 66) {
event.preventDefault();
safari.self.tab.dispatchMessage('Show Popover', {});
}
}
This is because you are manually selecting the first toolbarItem here;
safari.extension.toolbarItems[0].showPopover();
You need to determine which toolbarItem the popover needs to appear on;
Something like this;
var toolBarID = 'my_id';
var activeItem = safari.extension.toolbarItems.filter(function (button) {
return button.identifier == toolBarID && button.browserWindow == safari.application.activeBrowserWindow;
})[0];
You then use this object for the showPopover function;
activeItem.showPopover();
Hope this helps

Userscript for creating a confirmation popup whenever submitting an issue or posting a comment via pressing Ctrl+Enter(the built-in hotkey) in GitHub

Test URL: https://github.com/darkred/test/issues/new
GitHub allows in the issues area for a public repo:
submitting a new issue with just 1 character as title and no body, and
posting a comment with just 1 character .
The above happens to me quite a lot because the build-in hotkey for 'submiting an issue or comment' is Ctrl + Enter: I accidentally press that keyboard shortcut before my issue/comment text is ready.
So, I'm trying to make a script (using Greasemonkey) that would show a confirmation popup whenever I try to:
submit a new issue, or
post a comment
via pressing Ctrl + Enter:
if user presses Ok in the popup, then the script to allow the submit,
but if the user presses Cancel in the popup, then the script to stop the submit.
I've come across these two approaches:
After the helpful comment by Brock Adams I have the following code:
var targArea_1 = document.querySelector('#issue_body'); // New issue textarea
var targArea_2 = document.querySelector('#new_comment_field'); // New comment textarea
function manageKeyEvents (zEvent) {
if (zEvent.ctrlKey && zEvent.keyCode == 13) { // If Ctrl+Enter is pressed
if (confirm('Are you sure?') == false) { // If the user presses Cancel in the popup
zEvent.stopPropagation(); // then it stops propagation of the event
zEvent.preventDefault(); // and cancels/stops the submit submit action bound to Ctrl+Enter
}
}
}
if (targArea_1 !== null) {targArea_1.addEventListener('keydown', manageKeyEvents);}
if (targArea_2 !== null) {targArea_2.addEventListener('keydown', manageKeyEvents);}
Now the popup appears ok whenever I press Ctrl + Enter.
The problem is that the issue/comment is not submitted when pressing Ok in the popup (even if I haven't pressed Cancel in the popup before, at all). How to fix this?
And, how to re-allow the issue/comment submit after I have pressed Cancel in the popup once?
In other words: how to re-enable default after preventDefault() ?
Based on the help by user trespassersW here (I thank him a lot)
i.e. that my code was missing an else branch:
if (confirm('Are you sure?') == false) {
// ...
} else {
var btn = document.querySelector("#partial-new-comment-form-actions button");
if (btn) btn.click();
}
and that's because the confirm messagebox clears keyboard events queue.
(therefore the click 'Ok' action must be done by the script).
Here is a full working script:
// ==UserScript==
// #nameGitHub Confirm Create and Close issues
// #include https://github.com/*
// #grant none
// ==/UserScript==
(function () { // Self-Invoking function
function init() {
// For submitting issues in issue body textarea via Ctrl+Enter
var targArea1 = document.querySelector('#issue_body'); // New issue textarea
function manageKeyEvents1(zEvent) {
if (zEvent.ctrlKey && zEvent.keyCode === 13) {
if (confirm('Are you sure?') === false) {
zEvent.stopPropagation();
zEvent.preventDefault();
} else {
var btn1 = document.querySelector('.btn-primary');
if (btn1) {btn1.click();}
}
}
}
if (targArea1 !== null) { targArea1.addEventListener('keydown', manageKeyEvents1); }
// ------------------------------------------------------------------------------------------------
// For submitting issues in new comment textarea via Ctrl+Enter
var targArea2 = document.querySelector('#new_comment_field'); // New comment textarea
function manageKeyEvents2(zEvent) {
if (zEvent.ctrlKey && zEvent.keyCode === 13) {
if (confirm('Are you sure?') === false) {
zEvent.stopPropagation();
zEvent.preventDefault();
} else {
var btn2 = document.querySelector('#partial-new-comment-form-actions button');
if (btn2) {btn2.click();}
}
}
}
if (targArea2 !== null) { targArea2.addEventListener('keydown', manageKeyEvents2); }
}
// Page load
init();
// On pjax (because GitHub uses the History API)
document.addEventListener('pjax:end', init);
})();

External Link Notification - JavaScript or JQuery

I am looking for a way to set it up so that when an external link is clicked it will warn people that they are leaving the site. Preferably, it would darken the screen and display a message in the middle of the screen in a box with the option to click OK or Cancel.
I tried to use this code:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
and give each link a class of external but it doesn't seem to work. I don't want to use this because it means that the client will have to remember to add the class I would prefer something more automatic.
I also tried to use this code to do so but to no avail:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
I am using WordPress 3.8.1.
Thanks in advance for any help you can give.
Your filter logic should be correct, Try using the confirm function, and using jQuery instead of $.
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
I tried this out in dev tools on your site and it seems to work correctly if you use jQuery. I think you may have some plugin that is causing conflicts with $.
JSFiddle Demo
Try using confirm instead of alert since that will pause and wait for user input. You'll then need function(e){ e.preventDefault(); } to prevent the default link actions.
To identify just external links you might do something like this:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
and to catch people with a message you might use beforeunload and the confirm option
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
It worked pretty well to me. I just removed unnecesary variables, but original script worked fine.
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
http://jsfiddle.net/3dkAN/1/
EDIT
Following #user1308743's line, seems that in cgmp.framework.min.js is summoning the jQuery.noConflict() mode, that unbinds the $() function for jQuery. So please use jQuery() for any jQuery implementation

detect back button click in browser [duplicate]

This question already has answers here:
Intercepting call to the back button in my AJAX application
(12 answers)
Closed 8 years ago.
I have to detect if a user has clicked back button or not.
For this I am using
window.onbeforeunload = function (e) {
}
It works if a user clicks back button. But this event is also fired if a user click F5
or reload button of browser. How do I fix this?
So as far as AJAX is concerned...
Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.
Please try this (if the browser does not support "onbeforeunload"):
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
window.history.pushState('forward', null, './#forward');
}
});
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.
Some one knows who can i fix it?
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions:
JQuery History
Salajax
A Better Ajax Back Button

Problem with event.target in IE

I'm writing js for a status update system to be used on various pages throughout a app that I'm working. I am really just starting to get more comfortable with javascript so it has been somewhat of a challenge to get to the point where I have everything now.
The status system is basically a facebook clone. For the most part everything is supposed to function the way that facebook's status updates and status comments do. The intended behavior is that when the user clicks in the status textarea, the div under the status textarea slides out revealing the submit button as well as some other checkboxes.
If the user clicks anywhere else on the page except a link or any element that has the class prevent_slideup the div slides up hiding the submit button and any checkboxes.
I'm using a document.body click function to determine what the user clicked on so I know which form elements to hide if I should even hide them. I do not want this slideup to take place on a textarea if that textarea has focus or the user is selecting a checkbox that goes with that form. Hence the prevent_slideup class. I also do not want to bother running the slideup logic if the user has clicked on a link. I'd prefer they just leave the page without having to wait for the animation.
The code that I was using to accomplish this task can be found in the $(document.body).click(function (e) section below where I'm doing a .is('a') check on the event target.
This code works as expected in chrome and firefox, however in ie when a link is clicked for the first time it seems that the element stored in var target is actually a div instead of an anchor. What ends up happening is that the submit div slides up and the user is not taken to the link that they just clicked on. If a link is clicked a second time the user is taken to the page as you would expect.
It seems to me that there's some kind of a lag in ie as to what the current event being fired is.
The entire status module is working other than this one strange ie bug regarding the users click on the link not being carried out the first time that they click a link after opening the status textarea. Does anything jump out in this script that would explain this behavior or does anyone have any other advice?
Thanks in advance for your help.
$(document).ready(function(){
$("textarea.autoresize").autoResize();
});
$(document.body).click(function (e){
var target = e.target || e.srcElement;
console.log(target);
console.log($(target).is('a'));
if($(target).hasClass('prevent_slideup') || $(target).is('a'))
{
return true;
}
else
{
var active_element = document.activeElement;
var active_status_id = $(active_element).attr('data-status_id');
var active_has_data_status_id = (typeof active_status_id !== 'undefined' && active_status_id !== false) ? true : false;
$('textarea').each(function(){
if($(this).hasClass('status_comment_textarea'))
{
var status_id = $(this).attr('data-status_id');
if($('#comment_textarea_'+status_id).val() === '' && (!active_has_data_status_id || active_status_id !== status_id))
{
hide_status_comment_submit(status_id);
}
}
else if($(this).attr('id') === 'status_textarea')
{
if($('#status_textarea').val() === '' && $(active_element).attr('id') !== 'status_textarea')
{
$('#status_textarea').html($("#status_textarea").attr('placeholder'));
hide_status_submit();
}
}
});
return true;
}
});
$("#status_textarea").live('click', function(){
if($('#status_textarea').val() === $("#status_textarea").attr('placeholder'))
{
$('#status_textarea').html('');
}
show_status_submit();
return false;
});
$(".comment_toggle").live('click', function(){
var status_id = $(this).attr('data-status_id');
show_status_comment_submit(status_id);
return false;
});
$(".status_comment_submit").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_comment_submit_wrapper_'+status_id).addClass('status_comment_submit_successful');
return false;
});
$(".show_hidden_comments").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_hidden_comments_'+status_id).show();
$(this).hide();
return false;
});
function hide_status_submit()
{
$("#status_textarea").removeAttr('style');
$("#status_textarea").blur();
$("#status_block").removeClass('padding_b10');
$("#status_submit_wrapper").slideUp("fast");
return false;
}
function show_status_submit()
{
if ($("#status_submit_wrapper").is(":hidden"))
{
$("#status_block").addClass('padding_b10');
$("#status_submit_wrapper").slideDown('fast');
}
return false;
}
function hide_status_comment_submit(status_id)
{
if(!$('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#status_comment_submit_wrapper_'+status_id).hide();
$('#fake_comment_input_'+status_id).show();
$('#comment_textarea_'+status_id).removeAttr('style');
}
return false;
}
function show_status_comment_submit(status_id)
{
if($('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#fake_comment_input_'+status_id).hide();
$('#status_comment_submit_wrapper_'+status_id).show();
$('#comment_textarea_'+status_id).focus();
}
return false;
}
function status_comment_submit_successful()
{
hide_status_comment_submit($('.status_comment_submit_successful').attr('data-status_id'));
$('.status_comment_submit_successful').removeClass('status_comment_submit_successful');
return false;
}
I figured out that there were two main issues with my script...
1.) The document.body function and the #status_textarea live click funtioins were conflicting with each other.
2.) After adding the logic for the #status_textarea function into the document.body function I noticed that the script still didn't quite work as expected in internet explorer unless I had an alert in the function. The problem at this point was that the autoresize plugin that I'm using on the textarea was also conflicting with the document.body function.
I was able to rectify the situation by adding a dummy text input and hiding the status textarea. On click of the dummy text input the status textarea is shown and the the dummy text input is hidden. I have no idea why this worked, but it seems to have solved my problems.

Categories