Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleMDE: How to set Html preview to open anchor tag in a new tab?

I am using SimpleMDE editor (version 1.10.1).

Is there a way to set Html preview to open anchor tag in a new tab with default previewRender which right now opens link in same tab. Reference image:

image

To my knowledge these are ways to achieve this -

  1. I know we can set a custom previewRender, but making a custom parser function for all markdown syntax just to add target="_blank" for links will be a lot.
  2. I can do this by simply changing function togglePreview in simplemde.js to replace anchor tag to have target="_blank" by this => replace(/a href/g, 'a target="_blank" href'), but that is not a permanent solution as this will be a hack which I will have to add on each update of SimpleMDE.

Apart from these 2 are there any other alternatives to do this?

like image 342
Nalin Sajwan Avatar asked Jan 17 '17 14:01

Nalin Sajwan


1 Answers

If you look at how simplemde renders html, it simply uses marked. A quick search led me to find marked users having the same issue we have. In short you will have to set a custom previewRender, however it is not so terrible using the solution outlined from csytan on the marked issues page of github:

var marked = require('marked');

var customPreviewRender = function (text) {
    var renderer = new marked.Renderer();
    var linkRenderer = renderer.link;
    renderer.link = (href, title, text) => {
        var html = linkRenderer.call(renderer, href, title, text);
        return html.replace(/^<a /, '<a target="_blank" rel="nofollow" ');
    };
    return marked(text, { renderer: renderer });
}

var options = {
    previewRender: customPreviewRender 
};

var simpleMde = new SimpleMDE(options);

like image 144
Jonathan Walton Avatar answered Nov 20 '22 10:11

Jonathan Walton