Prevent opening Rails remote links in new tab
When you creating remote links in Rails usually you point them to JS actions and don’t expect that users will try to open that links in a new tab. But they will definitely try and you’ll get lots of ActionController::UnknownFormat
errors. To prevent this use the following snippet:
const remoteLinks = Array.from(document.querySelectorAll("a[data-remote='true']"))
remoteLinks.forEach(function(element) {
element.dataset.url = element.href
element.href = "javascript:void(0);"
})
Rails.href = function(element) {
return element.dataset.url || element.href
}
It will move actual url to data attribute and replace it with javascript:void(0);
which prevents browsers from opening link in new tab. And Rails.href
method will re-define how UJS pulls URL from remote link.
Put this snippet into you application.js
and don’t forget to wrap it with document.addEventListener('turbolinks:load', function() {})
if you use Turbolinks.