3

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
Nicolas Maloeuvre
  • 3,069
  • 24
  • 42

1 Answers1

5

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>
Nicolas Maloeuvre
  • 3,069
  • 24
  • 42