I need to convert a rails 2.3 site so that all external URLs open in a new window. I could go though every call to link_to
and add :target => '_blank'
, but I'd like to do it in one step for all links, present and future. Is there a way I can monkey patch link_to to get the desired behaviour?
You can easily set external links to open in a new tab in WordPress. In the Classic Editor, just insert your link and click Link Options to open the advanced insert link popup. Then check the box labeled “Open link in a new tab.”
You can make a HTML link open in a new tab by adding the target=”_blank” attribute. You should insert this after the link address.
You just need an anchor ( <a> ) element with three important attributes: The href attribute set to the URL of the page you want to link to. The target attribute set to _blank , which tells the browser to open the link in a new tab/window, depending on the browser's settings.
External links, for instance, should always open in a new browser tab. Your goal in designing a website is to get more visitors to convert. Letting an external link replace your website in the open tab will only decrease the chances of that happening.
You should not have to change your server-side code for this view problem.
You should use Unobscursive javascript. This example will only make external links showing up in a new window :
// jQuery
//
$(document).ready(function() {
$("a").click(function() {
link_host = this.href.split("/")[2];
document_host = document.location.href.split("/")[2];
if (link_host != document_host) {
window.open(this.href);
return false;
}
});
});
In the end I went with this, in an initialiser:
module ExternalLinksInNewTabs
def new_tab_link_to *args, &block
if block_given?
options = args.first || {}
html_options = args[1] || {}
if options.is_a? String
if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
html_options[:target] = '_BLANK'
end
end
same_tab_link_to options, html_options, &block
else
name = args.first
options = args[1] || {}
html_options = args[2] || {}
if options.is_a? String
if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
html_options[:target] = '_BLANK'
end
end
same_tab_link_to name, options, html_options
end
end
def self.is_external_link? host, url
host.sub! /^www\./, ''
url =~ /^http/i && url !~ /^http:\/\/(www\.)?#{host}/i
end
end
module ActionView
module Helpers
module UrlHelper
include ExternalLinksInNewTabs
alias_method :same_tab_link_to, :link_to
alias_method :link_to, :new_tab_link_to
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With