Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - Open a URL From The Controller In New Window

I'm in my applications controller and I have a url string. How do I tell the app to open the url in the browser in a new window. Is there a way to set the target to blank?

For example

def link
  @url = 'www.google.com'
  ****??? Open @url ?? *** with target blank?
end
like image 794
ChrisWesAllen Avatar asked Oct 21 '11 21:10

ChrisWesAllen


4 Answers

This is not possible to do directly from the controller. Using redirect_to @url has the effect of opening an URL in the same "window", as it simply sends a HTTP redirect instruction back to the browser. redirect_to is not capable of opening new windows. The controller resides on the server side, and opening a new window belongs to the client side.

Some options:

a) render a link with <%= link_to 'Google', 'google.com', :target => '_blank' %> or <a href="google.com" target="_blank">Google</a> which the user can click on in a new view

b) use JavaScript to open the link automatically, but beware that browsers may treat this as a popup and block it

By combining these options you can open links in new window for browsers/users who allow it, and fall back to a regular URL in case that didn't work.

like image 71
Mads Mobæk Avatar answered Nov 09 '22 09:11

Mads Mobæk


As the others point out, you can't (and shouldn't) do this in the controller. In the view you can use

<%= link_to @url, :target => "_blank" %>
like image 36
Alex Peattie Avatar answered Nov 09 '22 08:11

Alex Peattie


Well, it's not that you CAN'T do it, it's just kind of a convoluted process. I did this in a project I'm working on. Basically, it's a mixture of Rails goodness and Javascript. I simply passed a flash notice on creation of an instance, and then used a script to set that flash notice equal to a js variable, and a redirect_url. If that particular flash notice pops up on that page, it redirects in the js script. Like I said, it's hack hack hack, but it works for my purposes.

like image 4
Don Avatar answered Nov 09 '22 10:11

Don


You can't do that in rails, because your script is being executed on a server. Use Javascript to work with browser on the client side.

like image 1
romaonthego Avatar answered Nov 09 '22 10:11

romaonthego