I’m using the following code (with the Underscore.js library) to add the attributes target="_blank" and rel="external" to all non-local links on page load. My code looks like the following:
(function($){
$(document).ready(function(){
// Create a matching regex pattern based on current host name
var regexPattern = new RegExp(location.origin);
// Gather all non-local links
nonLocalLinks = _(jQuery('a')).reject(function(link) {
return link.href.match(regexPattern);
});
// Add attributes to all non-local links
_(nonLocalLinks).each(function(item) {
item.target = '_blank';
item.rel = 'external';
});
})
})(jQuery)
This code works correctly in all tested browsers (Chrome 17, IE7, IE8, IE9, Safari) but does not work in Firefox 10. Links that had the target="_blank" attribute set on the anchor tag as part of the HTML output by the server function as expected. Will this not work on page load in Firefox, or is there something else I’m missing?
Also – I appreciate any and all input, but please don’t suggest that this is bad user experience, etc. I agree, but I don’t have a choice – this is for a client, and this is what they want; “no” is not an option.
EDIT: This “does not work” means that the link opens in the same tab. There are no errors in the firebug console – the link simply behaves as though target="_blank" is not set.
Firefox doesn’t have an
originproperty onwindow.location. That means that yourregexPatternends up being//and that leavesnonLocalLinksempty.Demo (watch the console): http://jsfiddle.net/ambiguous/tS4WB/
You’ll have to account for a missing
location.originwith something like this:Demo: http://jsfiddle.net/ambiguous/envWe/
You might want to add an
^anchor to your regex as well or just check ifindexOfgives you zero.If you have a look at the MDN documentation on
window.location, you’ll see that the following properties are supported:No origin.