ruby-on-railstrixactiontextstimulusjs

How to open Action Text Trix attachments or links in new window (target _blank)


How to make links that I add in Trix (ActionText) editor open the link in a new window with target="_blank"?

class Post < ApplicationRecord
  has_rich_text :rich_text_content
end

Solution

  • Add a Stimulus controller richtext_controller.js :

    import { Controller } from "stimulus"
    
    export default class extends Controller {
      connect() {
        this.element.querySelectorAll('a').forEach(function(link) {
          if (link.host !== window.location.host) {
            link.target = "_blank"
          }
        })
      }
    }
    

    add your content like this :

    <div data-controller="richtext">
      <%= post.rich_text_content %>
    </div>