How can I catch opening of the link - javascript

I have a HTML page with multiple links. Is there any ability to catch the event of opening the link? Users can just click on link or can open it on the new window or tab by right click.
Links refers to external resources and I can not control of its content.

There's a few client-side options that I can think of, none of which ideal:
You could replace the link's href with a javascript: url that ran any code you wanted, and then navigated to the correct URL (location.href = "http://example.com"). This is nasty though, since it breaks if the user does right click -> new tab or has JavaScript disabled.
You can add an event listener to the click event of the <a>. But this would not get triggered on right-click -> open, or a user tabbing over and pressing enter.
You can use an onunload event handler on the document itself, but this won't tell you where the user is going, and wouldn't work if the user opened a new tab.
If you just want to track where your users are navigating to, then a server-side solution is the only foolproof way. You would have to send users to your own server, which would in turn send an HTTP 302 code to redirect the browser to the correct URL. This would, of course, require more infrastructure than you may want.

Yeah you can use javascript to do something like...
$('a').click(function(){
event.preventDefault();
$(this).alert("do something");
});

try
var links = document.getElementsByTagName('a');
for(var i = 0; i< links.length; i++) {
links[i].onmousedown = function(e) {
console.log(this.href, this)
if ((e.which && e.which == 3) || (e.button && e.button == 2)) { // not sure about IE
alert('right click');
}
}
}

Related

How to override default alt-key + click action? Browser makes a download, but

By pressing the alt-key and click on a url, chrome makes a download. This because of the browsers default alt+click action. How can I prevent that? It should exchange the url.
The code works with other keys (for example x == 88), where the browser has no default actions. But how with the alt-key?
//ALT-key recognition
document.onkeydown=function(){
var keyCode = event.keyCode;
if(keyCode == 18) //alt-key
{
console.log(keyCode);
document.getElementById("hist").setAttribute ('href', "history_by-date.php?wdate=all");
}
}
<div id="history">
should be just a link - not a download (when alt is pressed)
</div><!-- end history -->
Another user here skyline3000 has an interesting article with prevent code, but I bring it not to work. Thanks for any help.
evt.preventDefault();
evt.stopPropagation();
return false;
Rather than listening to a keypress I think you need to listen to the link click events and check the event.altKey property. I'm not 100% if this is bulletproof vs alt-click download, but it seems to work. Note, using this.click() to invoke the link will only work if it's a normal href, no javascript or click events. There are other more complex ways to do that part otherwise.
document.querySelectorAll('a').forEach(a => {
a.addEventListener('click', function (e) {
if (e.altKey) {
e.preventDefault(); // no download
this.href = 'history_by-date.php?watchdate=all';
this.click(); // fake a normal click
}
});
});
<a href='http://example.com'>alt-click me</a>
What you are asking is to change the users' browser's default actions. This is not possible. A default action from the browser wont run in the HTML DOM, thus not being detectable.

My requirement is that I want to show a message to user while closing the browser tab or window

I am trying using following code-
window.onunload = function(e){
return "Do you really want to quit without saving."
}
**
But message is also appearing if I will try to navigate from one page
to another
**. I only want this functionality if user clicks on the [x] button not on any event change.
I have also tried following-
window.onbeforeunload = function(e){
return "Somethig"
}
Note- I want to identify the event when user only closing the browser, not for any other page event.
Using Jquery:
$(window).unload(function() {
//your code
});
using javasscript:
window.onbeforeunload = function(e){
var displaymessage = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = displaymessage;
return displaymessage;
}
This question is a duplicate of this question.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
Also, in recent versions of Chrome, the feature has been deprecated.
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)

detect if the user have an intention to redirect from it's page

How can I detect if a user has any intention to leave his current page and redirect to any page from my website is their any javascript function that can handle this event I have more than 25 links in my page
<script type="text/javascript">
if(//user clicks a link )
confirm("do you want to continue ?");
</script>
Is their any javascript function that can check if the user click on any link on the page
This code will intercept all clicks on links in your page.
$("a").click(function() {
// this.href will be the href of the link they clicked on
// return false from this function if you want to abort the click on the link
});
FYI, unless there are very special circumstances in your page, it's kind of obnoxious to force a user to confirm that they actually want to go to the link they just clicked on. Can you imagine how terrible the web browser would be if you had to confirm every click.
There is also a generic way to prompt if the user wants to leave your page using the onbeforeunload event.
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
Note: this is also obnoxious unless there are very special circumstances.
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
});

How to handle browser's window.onbeforeunload event

I want to handle window.onbeforeunload event. I can handle it this way
window.onbeforeunload = function() {
return "MSG";
}
But in this case it shows a popup asking for user confirmation i dont want that confirmation dialog instead it will directly return false like event.cancel = true.
You cannot do this in the onBeforeUnload. The for this reason is; the user has already sent in a request to move away from the page and the event has been intercepted. The confirm is the best you can do, unless you prevent the event further up the event chain (such as with onkeydown).
For instance, if you want the user to not be able to use their keyboard to go backwards and forwards in history, or to reload the page, this could be achieved using;
var catchKey = {
37: true, /// left
39: true /// right
};
window.onkeydown = function(event) {
if (catchKey[event.keyCode] && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
}
}
Hope that helps!
Basically you want to prevent the user from closing the browser window/tab or navigate away from your page at all?
I am sure no browser maker will let you do that... then the only way to close the browser in such a case would be to kill the process.
So: Not possible, as far as I can see.

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories