Per a client request, we forced all external links to open in a new tab. Currently I am using a js script for that.
However, it is also forcing the tel and mailto links to open new tabs as well. And I think that is why I am getting an error on some devices when you click and email link, where a pop up box says "This website has been blocked from automatically composing an email" - that one was uncovered specifically on an iPhone 6.
How can I force external links- but exclude mail and telephone links? Any assistance is greatly appreciated.
This is the external link script that I am using currently. I thought maybe I could just make an alteration to look for only external links that had "http" but an else statement for tel and mailto. But I am not sure how I could go about that.
jQuery(document).ready(function($) {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
});
Combined with my comment, I would opt to go for a check against the href attribute of each anchor, and check that it does not start with mailto: or tel::
(and the external link is not working at all, I guess that is caused by the snippet environment)
jQuery(document).ready(function($) {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href) && this.href.substr(0,4)!='tel:' && this.href.substr(0,7)!='mailto:') {
$(this).attr('target', '_blank');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
website,
e-mail and
phone.
I must admit that it is not ideal to check for all protocols that you might want to exclude, but it definitely is easier than checking for everything that you would like to open in a new window/tab.
Related
I have a link which when clicked redirects the user to the same page except with additional parameters:
<a id="lnkExportToPDF" href="javascript:void(0)">Export</a>
$('#lnkExportToPDF').click(function (e) {
e.preventDefault();
window.location.href = path + 'users/export/' + parm1 + '/' + parm2;
});
On the server side I handle it by checking for "export" in the request path, and if it's found I write a PDF file to the response:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/pdf");
response.AddHeader("Content-Disposition", String.Format("attachment; filename=" + filename + ".pdf; size={0}", buffer.Length.ToString()));
response.BinaryWrite(buffer);
response.End();
Everything works and the user can download the file, but any additional actions by the user that uses the loader.gif which is on the page shows an unanimated loader.
What could be causing this to happen? Is there any way to refresh/reload the page/javascript after the response is complete?
edit: I've found a useful JS tool here: http://fgnass.github.io/spin.js/ but I'd prefer not to use it unless absolutely necessary
edit2: I also tried using a generic handler (.ashx) to handle the request (ie. changing the href to point to the handler), but as soon as the page redirects and the file is written, same thing happens
edit3: The problem is only happening in Firefox so far. I've tried Chrome and IE and the gif stays animated in those browsers. (latest versions of each)
edit4: If I use an iframe with the src as the image it solves the issue, but it's very hacky and the style of it looks different across all browsers with regards to centering/padding/margins.
edit5: Yeah. If I inspect the frozen gif with firebug it magically unfreezes itself.
I managed to recreate the problem in firefox and I really can't find a way to "unfreeze" the gif. When I added a completely different file after a download and that too was frozen I gave up with that approach.
What I did instead was to test different ways to trigger the download. I found no window.location solutions that worked, what did work though was this:
window.open(path + 'users/export/' + parm1 + '/' + parm2);
window.open opens a new tab and downloads the file through that instead of the current tab as window.location does. It will return to the current tab as soon as the download starts.
Edit
You could also use a hidden iframe:
var iframe = document.getElementById('iframe');
iframe.src = path + 'users/export/' + parm1 + '/' + parm2;
I confirm that I have the same behavior with firefox, and the first that come to my mind is to use SetTimeOut but still the same behavior, so on firefox for some reason, this window.location.href is also call the "Stop" on browser, that this cause the gif animation to stop.
So what I found and you can solve your issue, that this is not happends on simple links.
And if you change your code you can archive the same effect with a link.
So change this
$('#lnkExportToPDF').click(function (e) {
e.preventDefault();
window.location.href = "page.aspx";
});
to something like this
$('#lnkExportToPDF').attr("href", "page.aspx");
and you have the same results, and gif will still moving.
Here is the fiddle test.
On the test I add to move to paypal, because is slow moving and you can see the animation stop or not, also pp not let show on iframe, so on example you stay on example and not load the page.
When you click on this example, the issue is appears only on firefox !
http://jsfiddle.net/hn7S9/4/
One other issue that I think is that if you need to make your parametres to the next page on click, you probably need to redesign that and fix them before your click.
This is possible because for sure is not depends on the last click on the dynamic create link. So make the link with their parametres before the click.
You could try an asynchronous approach on the click to allow the browser to parse the event queue after the click has initiated:
$('#lnkExportToPDF').click(function (e) {
e.preventDefault();
setTimout(function() {
window.location.href = path + 'users/export/' + parm1 + '/' + parm2;
}, 20);
});
How about allowing the link to actually fire, but opening it in a new tab?
That shouldn't interrupt anything about the gif, and is semantically fine, other than I guess it would leave a tab open. You could get rid of the content-disposition, and allow the browser /user to decide what to do with it though.
<a id="lnkExportToPDF" target="_blank">Export</a>
$('#lnkExportToPDF').click(function (e) {
$(this).attr("href", path + 'users/export/' + parm1 + '/' + parm2);
});
Instead of setting the window.location.href, you can use a form with method="get" and submit it. This form could either be coded into your HTML or created dynamically. See this Answer:
https://stackoverflow.com/a/21742326/1614903
Here's my solution. It's faster and easier than any fix or workaround I've found. Just open the problem page in Chrome. Chrome has it's own problems, but this isn't one of them. Whenever I encounter a page full of gifs that causes Firefox to freeze, I just copy the URL, close the tab, open Chrome, and paste in the URL. I works every time! :o)
I have page the has some data in tabs, Im trying to write a function so that when links are click from another page can load the page with the tabs on and show the correct tab. This is working with the code below, minus the actual changing tabs function. But for some reason using the window.location..... as a variable still scroll the page down to the matching id. Is there another way to get the string in the url after the #. Or can i do it this way but not have to jump to the id? thanks
function loadTab(){
var linkToTab = window.location.hash.substr(1);
var linkClass = '.'+linkToTab
if(window.location.hash != '') {
changeTabs(linkClass);
}else{
$('.companyLink:first').addClass('active');
$('.companyBio:first').addClass('active');
$('.companyBio:first').fadeIn();
};
}
The hash character is for anchors.
Use a question mark instead of a hash.
<a href="index.html?tabname">
and
var linkToTab = window.location.search.substr(1);
var linkClass = '.'+linkToTab
if(window.location.search != '') {
The # part of the URL is traditionally used for anchors. The 'jumping' you see is the original feature.
Modern websites and web-applications use it build a history as HTML5's history feature isn't widely supported yet.
To avoid the jumping add event.preventDefault to your links, like:
Tab1
<script type="text/javascript">
document.getElementById("tab1handle").onclick = function (event) {
event.preventDefault();
}
</script>
You can also make sure the anchor is not defined. In this case the browser will jump to the top of the page. It's up to you whether this is undesirable or not.
I've been working on a Frame busting buster (what's in a name, hehe), which kept my users on my page and open a new window with the target URL. I'm using a Lightbox script to display iframes, this is what I'm doing:
1) Added an event for all .lightbox clicks, f.e:
$('.lightbox').live("click", function(e) {
e.preventDefault();
$('#redirectURL').val($(this).attr('href'));
$(this).lightbox();
}
2) Added a frame busting buster:
<script type="text/javascript">
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2
window.top.location = 'http://server-which-responds-with-204.com'
}
}, 1)
</script>
3) Modified the frame busting buster code to fit my needs, which are:
detect if an iframe wants to change the window.top.location
if so, prevent this from happening using the 204 server respond
open a new page: window.open( $('#redirectURL', '_blank' );
close lightbox: $('.jquery-lightbox-button-close').click();
So far, this is what I've come up with:
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
redirectURL = $('#redirectURL').val();
if(redirectURL != "") {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
window.open(redirectURL, "_blank");
$('.jquery-lightbox-button-close').click();
$('#redirectURL').val('');
} else {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
}
}
}, 1);
// EDIT: Before I forget, 'nocontent.php' is a file that returns a 204 header
For Firefox it acts as I programmed it, if there's a change detected in the window.top.location it opens a new frame/page and prevents the iframe from reloading the top location and to round it up, it closes the jQuery lightbox.
Safari/Chrome act similar, they open a new browser screen (not sure if theres an option to say target="_newtab" or something?). Only bad thing is they do not really display a message of the popup is blocked, but I can work around that by displaying a popup balloon on my website with a link to the page.
Internet Explorer is, what a shocker, the only black sheep left.. IE does not open a new popup, nor blocks the window.top.location reset by the iFrame and simply continues refreshing the complete page to the '#targetURL'. It does the same with the default busting code.. so it's not because of some of my edits.
Anyone who is able to spot a mistake in my code?
Also, I would need a little modification that sees if the request has been made by an iframe or by the user itself, because now there is really NO option for a user to leave my page by changing the address in the toolbar or by clicking a link, which is not really needed LOL.
Thanks in advance.
PENDO, I tried to simulate the whole process you described, ligthbox-jquery, javascript their own codes and controls opening pages via lightbox. I could not simulate at all, and as time is running out I'm sending a suggestion to broaden the range of possibilities and solutions.
I suggest replacing the redirect page:
...
redirectUrl = $ ('# redirectUrl'). val ();
...
window.top.location = 'http://www .****. with / ajax / nocontent.php';
window.open (redirectUrl, "_blank");
Replaced with a DIV container that simulates a page, using ajax calls and taking the content and overwritten the contents of the DIV.
...
$.post(redirectoURL /* or desired URL */, function(data) {
$('DIV.simulateContent').html(data);
});
...
or
...
$('DIV.simulateContent').load(redirectoURL);
...
This approach also avoids the problem of preventing the user from even leaving your page using the address bar (as you yourself mentioned).
Sorry, let me give you a complete solution, but time prevented me.
PENDO, a little more work on alternatives to the problem, I found a customizable jQuery lightbox plugin for working with custom windows yet (iframe, html, inline ajax etc.). Maybe it will help. The following link:
http://jacklmoore.com/colorbox/
If you don't need javascript running in your iframe in IE, you can set the iframe security attribute :
<iframe security="restricted" src="http://domain.com" />
http://msdn.microsoft.com/en-us/library/ms534622(v=VS.85).aspx
Instead of linking directly to files for download on a web site we link to a page that says "thank you for downloading". The page has tracking codes on it so we know how many people have downloaded the file. The page launches the download file using the jQuery code shown which adds a short delay after the page loads before the download begins. The download location has a content disposition header so it always downloads properly in the browser leaving the "thank you for downloading" page visible. This all works well.
The problem comes if the user carries on browsing past this page and then hits back. The download fires again.
Using window.location.replace(href); didn't seem to fix it.
The issue is further complicated by the fact that the CMS delivering the page has set it to expire immediately so it's not being cached.
Suggestions for (i) ways to avoid this problem; (ii) any better ways to handle file download / thank you pages?
jQuery Code
$(document).ready(function () {
$('a.autoDownload').each(function () {
setTimeout('navigateToDownload("' + $(this).attr('href') + '")', 4000);
});
});
function navigateToDownload(href) {
document.location.href = href;
}
One possible approach would be to set a cookie via Javascript when the page first loads. Then, if that page is ever loaded again, you can check for the presence of the cookie, and if present, do not execute the auto download?
Using the Cookie plugin for jQuery as an example:
$(document).ready(function () {
$('a.autoDownload').each(function () {
var hasDownloadedThisLink = $.cookie("site." + $(this).attr('id'));
if (!hasDownloadedThisLink) {
$.cookie("site." + $(this).attr('id'), "true");
setTimeout('navigateToDownload("' + $(this).attr('href') + '")', 4000);
}
});
});
This is just an example. If you went this way, you'd have to consider how many possible download links there might be, as there is a limit on how many cookies you can set. Also notice that I used an id attribute of the links to identify them in the cookie - I figured this would be more suitable that using some form the href attribute. I also prefixed the cookie name with site..
Well there are a couple of solutions to this. Here's an example:
function navigateToDownload(href){
var e = document.createElement("iframe");
e.src=href;
e.style.display='none';
document.body.appendChild(e);
}
Other implemenatations might exist, but I doubt they're less "hacky".
Background: I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like
http://example.com/#foobar
and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.
Now the question: When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn http://example.com/#foobar into http://example.com/ to update the permalink display. However, doing so using parent.location.hash = '' causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using window.location.href = '/#' won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?
As others have mentioned, replaceState in HTML5 can be used to remove the URL fragment.
Here is an example:
// remove fragment as much as it can go without adding an entry in browser history:
window.location.replace("#");
// slice off the remaining '#' in HTML5:
if (typeof window.history.replaceState == 'function') {
history.replaceState({}, '', window.location.href.slice(0, -1));
}
Since you are controlling the action on the hash value, why not just use a token that means "nothing", like "#_" or "#default".
You could use the shiny new HTML5 window.history.pushState and replaceState methods, as described in ASCIIcasts 246: AJAX History State and on the GitHub blog. This lets you change the entire path (within the same origin host) not just the fragment. To try out this feature, browse around a GitHub repository with a recent browser.
Put this code on head section.
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
There is also another option instead of using hash,
you could use javascript: void(0);
Example: Open Div
I guess it also depends on when you need that kind of link, so you better check the following links:
How to use it: http://www.brightcherry.co.uk/scribbles/2010/04/25/javascript-how-to-remove-the-trailing-hash-in-a-url/
or check debate on what is better here: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
$(document).ready(function() {
$(".lnk").click(function(e) {
e.preventDefault();
$(this).attr("href", "stripped_url_via_desired_regex");
});
});
So use
parent.location.hash = '' first
then do
window.location.href=window.location.href.slice(0, -1);
As others have said, you can't do it. Plus... seriously, as the jQuery Ajaxy author - I've deployed complete ajax websites for years now - and I can guarantee no end user has ever complained or perhaps ever even noticed that there is this hash thing going on, user's don't care as long as it works and their getting what they came for.
A proper solution though is HTML5 PushState/ReplaceState/PopState ;-) Which doesn't need the fragement-identifier anymore:
https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
For a HTML5 and HTML4 compatible project that supports this HTML5 State Functionality check out https://github.com/browserstate/History.js :-)