Step-by-step Guide To Add a Custom Export from Markdown Button to Froala

Custom Export Markdown Button

The Froala Markdown feature allows users to write content using a simplified markup language that is easy to read and write. This feature is important because it enables users to format their text with headings, lists, links, and other elements quickly, without needing to use complex HTML tags. Markdown’s simplicity also boosts productivity, making it a favorite among content creators and developers.

 Add a Custom Export from Markdown Button to Froala

We covered how the Markdown feature is working in previous articles:

Today, we’ll show developers how to add a custom export from markdown button. This will let users easily save their work as a markdown file while maintaining the format of their markdown document. The Froala Editor provides a powerful way to extend its functionality, making this implementation straightforward.

Why Add a Custom Export to Markdown Button?

Markdown is a lightweight markup language that has become increasingly popular among developers and writers alike. It offers a simple and efficient way to format text, making it a preferred choice for tasks such as writing documentation, creating README files, and composing blog posts. By adding a custom button to your Froala-powered application, you provide users with a seamless way to export their content in the Markdown format, enabling them to:

  • Easily share their work with others who prefer the Markdown syntax
  • Integrate their content into other tools that support Markdown
  • Maintain a clean and organized workflow by keeping their documents in a standardized format

Creating the Custom Button

Froala makes it easy to add a new toolbar button to the editor. Let’s create a custom “Export to Markdown” button step-by-step:

Step 1: Include Froala in your Project:

To include Froala in your project, follow the setup instructions in the Froala documentation according to your programming language and framework. For this demo, I only used the core Froala editor and the Markdown plugin to keep my project simple, avoiding unnecessary features. Here’s the resulting template:

<!DOCTYPE html>
<html>

<head>
    <title>Froala WYSIWYG Editor</title>
    <!-- Include Froala CSS -->
    <link href="{{editor__download__folder}}/css/froala_editor.min.css" rel="stylesheet"
        type="text/css" />
    <link href="{{editor__download__folder}}/css/plugins/markdown.min.css" rel="stylesheet"
        type="text/css" />
</head>

<body>
    <!-- HTML element where the editor will be initialized -->
    <div id="editor">
    </div>


    <!-- Include Froala Editor JS files -->
    <script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.min.js"></script>
    <script type="text/javascript" src="{{editor__download__folder}}/js/plugins/markdown.min.js"></script>
 
</body>

</html>

Step 2: Define an Icon for the Button:

With Froala, you can easily define icons for toolbar buttons. You can define the icon using one of the wide range templates Froala provides. I prefer using SVG icons. First, I’ll add the SVG path for the “Export” icon to the FroalaEditor.SVG object:

FroalaEditor.SVG.export  ="M15.293 5.293L12 8.586V2h-1v6.586L8.707 5.293 7.293 6.707 12 11.414l4.707-4.707zM18 11h-1v4H7v-4H6v5h12v-5z";

Then, I’ll register the icon using the FroalaEditor.DefineIcon method:

FroalaEditor.DefineIcon("export", { NAME: "Export", SVG_KEY: "export" });

Step 3: Define the Custom Button:

To create the new “Export to Markdown” button, I’ll define a new object with the following properties:

title

The title represents the label of the button. It is set to “Export from Markdown”.

title: "Export from Markdown",

type

Defines whether this is a button or a dropdown. In this case, it is set as a button.

type: "button",

plugin

Associate the button with a specific plugin. Here, it is linked to the Markdown plugin.

plugin: "markdown",

undo

Since the button’s function doesn’t need to be added to the undo stack, this is set to false.

undo: false,

showOnMobile

To make the button visible on mobile devices, this is set to true.

showOnMobile: true,

disabled

Determines the initial state of the button—whether it should be disabled or enabled. Since the button should only be available when the editor is in Markdown mode, I set it to true.

disabled: true,

refreshAfterCallback

When set to true, the editor will refresh all toolbar buttons after the button’s callback is executed.

refreshAfterCallback: true,

refresh

Defines the function executed during the toolbar button refresh process. The button is initially disabled, I will utilize this function to enable the button when the Markdown feature is active. I will use themarkdown.isEnabled() method to check the state of the Markdown feature:

  • If true, I will enable the button.
  • If false, I will disable the button.
  refresh: function refresh($btn) {
    if (this.markdown.isEnabled()) $btn[0].classList.remove("fr-disabled").setAttribute('aria-disabled', 'true');
    else $btn[0].classList.add("fr-disabled").setAttribute('aria-disabled', 'false');
  },

forcedRefresh

To ensure the button’s refresh method is triggered whenever the user clicks any toolbar button, forcedRefresh is set to true.

forcedRefresh: true,

Callback Function

Defines the action executed when the button is clicked. In this case, it handles Markdown export, allowing users to save their content as a downloadable .md file.

Steps to Export Markdown

Markdown feature

Follow these steps to enable users to export content from the Froala Editor in Markdown format. This process involves retrieving the editor content, creating a Markdown file, and providing a seamless download option via a custom toolbar button.

1. Retrieve Editor Content

To obtain the content in Markdown format:

  • Use commands.selectAll() to select all text.
  • Extract the text with selection.text().
  • Ensure the cursor position remains unchanged using selection.save() and selection.restore().
    this.selection.save();
    this.commands.selectAll();
    const markdownContent = this.selection.text();
    this.selection.restore();

2. Create a File with Markdown Content

  • Utilize the Blob constructor to create a file.
  • Set the type to text/markdown;charset=utf-8.
  • Generate a downloadable URL using URL.createObjectURL().
    const blob = new Blob([markdownContent], {
      type: "text/markdown;charset=utf-8",
    })
    const url = URL.createObjectURL(blob)

3. Download the File

  • Create an <a> element and assign the Blob URL.
  • Set the download attribute to specify the filename.
  • Trigger a click event to start the download.
  • Use URL.revokeObjectURL(url) to release the memory.
    const a = document.createElement("a")
    a.href = url
    a.download = "markdown.md"
    a.click()
    URL.revokeObjectURL(url)

Step 4: Register the Custom Button:

With the button object defined, I’ll use the FroalaEditor.RegisterCommand method to register it as a custom button.

FroalaEditor.RegisterCommand("export", {
  title: "Export from Markdown",
  type: "button",
  undo: false,
  refreshAfterCallback: true,
  forcedRefresh: true,
  disabled: true,
  plugin: "markdown",
  showOnMobile: true,
  refresh: function refresh($btn) {
    if (this.markdown.isEnabled()) $btn[0].classList.remove("fr-disabled").setAttribute('aria-disabled', 'true');
    else $btn[0].classList.add("fr-disabled").setAttribute('aria-disabled', 'false');
  },
  callback: function () {
    this.selection.save();
    this.commands.selectAll();
    const markdownContent = this.selection.text();
    this.selection.restore();
    const blob = new Blob([markdownContent], {
      type: "text/markdown;charset=utf-8",
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "markdown.md"
    a.click()
    URL.revokeObjectURL(url)
  },
})

Step 5: Initialize the Froala Editor:

Now I’m ready to initialize the Froala Editor and display it to the users.
new FroalaEditor('#editor');

6. Add the Custom Button to the Froala Toolbar:

To make the custom button available in the Froala toolbar, add it to the toolbarButtons configuration option:

new FroalaEditor('#editor', {
 toolbarButtons: ["bold", "italic", "underline", "markdown", "|", "export"],
 });

This adds the “Export to Markdown” button to the Froala toolbar alongside other buttons. When users click it, their markdown document will be downloaded as an .md file to their device. See the code in action.

Benefits of Adding the Custom Button

Integrating a custom “Export to Markdown” button into your Froala-powered application offers several benefits:

  1. Increased Flexibility: Users can easily export their content in the Markdown format, which is widely supported by various platforms. This allows them to write content once and use it across multiple systems.
  2. Improved Workflow: By providing a way to export to Markdown, you’re streamlining your users’ workflow. They can focus on content creation, knowing they can easily export their work in the desired format.
  3. Enhanced User Experience: The addition of the custom button enhances the overall user experience. Being able to convert and download their work directly from the editor saves time and reduces the need to copy/paste between applications.

Additional Customization Options

You can further enhance this functionality to:

  • Allow users to specify a filename before download
  • Add support for exporting to other formats like HTML file or PDF file
  • Include syntax highlighting in the exported code blocks
  • Apply custom CSS to the markdown editor
  • Add options to import content from external sources

Integrating with External Services

Beyond basic exporting, you can extend your Markdown functionality to integrate with popular development platforms:

GitHub Integration

Adding GitHub integration to your custom Markdown export button allows users to directly push their content to repositories. This is particularly useful for teams working on documentation or README files. You can implement a workflow that lets users select a target repository, specify the file path, and upload their markdown content with a single click from the editor.

Document Storage Solutions

For teams that need more robust document management, you can integrate with various storage solutions to help users organize their markdown files. This allows for better version control and collaboration. When implementing this feature, consider how search functionality could enhance the user experience, making it easier to find and reuse previously created content.

eBook Publishing Extensions

For content creators who want to publish longer-form content, adding EPUB export capabilities can be valuable. This feature allows users to convert their markdown documents into properly formatted eBooks that can be rendered on various devices. The process involves converting markdown to HTML and then packaging it with the necessary metadata into an EPUB file, complete with custom CSS styling.

By implementing these extensions, you provide users with a complete solution for their content creation and publishing needs, reducing the need to switch between multiple applications and streamlining their workflow across multiple pages of content.

Advanced Editor Configurations

Take your Markdown editing experience further with advanced configurations. Customize the textarea for better usability, implement additional command options, and enhance functionality to cater to specific Markdown editing needs.

Custom Textarea Enhancements

When working with Markdown in Froala, you can customize how the textarea appears and functions to make editing more comfortable. This includes adjusting the default appearance, implementing custom keyboard shortcuts, and defining specialized editing behaviors for markdown-specific syntax.

Supporting Additional Command Options

Enhance your export functionality by adding additional command options that give users more control. These could include the ability to insert predefined templates, search within the markdown content, or generate an index of headings. Each command can be configured to process the markdown in different ways depending on the user’s needs.

Conclusion

In this blog post, you’ve learned how to add a markdown button to the Froala WYSIWYG HTML Editor. By leveraging Froala’s customization features, you can easily extend the editor’s functionality to meet specific needs. This enhancement allows users to seamlessly export their markdown content as a file, improving their document management workflow.

The process demonstrates how toolbar buttons can be defined, customized, and integrated into the Froala editor, showcasing its flexibility as a powerful and extensible text editor. Implement this feature in your Froala-powered application to give users more control over their content.

Posted on March 6, 2025

Mostafa Yousef

Senior web developer with a profound knowledge of the Javascript and PHP ecosystem. Familiar with several JS tools, frameworks, and libraries. Experienced in developing interactive websites and applications.

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *