Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect with turbolinks from javascript

Is it possible to make window.location.replace or window.location.href work with turbolinks like it's a simple link?

like image 398
droptheplot Avatar asked Sep 04 '14 16:09

droptheplot


3 Answers

From the documentation: https://github.com/rails/turbolinks#triggering-a-turbolinks-visit-manually

You can use Turbolinks.visit(path) to go to a URL through Turbolinks.

You can also use redirect_to path, turbolinks: true (or turbolinks: :advance) in Rails to perform a redirect via Turbolinks.


This should work:

Turbolinks.visit('http://google.com')
like image 90
MrYoshiji Avatar answered Nov 16 '22 01:11

MrYoshiji


Yes.

As written here

You can use Turbolinks.visit(path) to go to a URL through Turbolinks.

like image 31
mikdiet Avatar answered Nov 16 '22 00:11

mikdiet


In case you implement Turbo Hotwired the basic usage is

Turbo.visit(your_url);

As decribed here

other usage with a stimulus controller

import { Controller } from 'stimulus';
import { visit } from '@hotwired/turbo';

export default class extends Controller {

    myEvent(event){
       // do some code
       // eg <span data-action="click->myController#myEvent" data-url="https://example.com/...">Hello</span> in case 
       // in case element is an button you don't need specify the event (default is click)

       this.goToUrl(event.currentTarget.dataset.url);
    }
  
    goToUrl(url){
       visit(url);
    }
}
like image 42
Fabrice G Avatar answered Nov 16 '22 00:11

Fabrice G