20

I am attempting to create a mini WYSIWYG editor for a custom CMS. It has the option to add and remove links. It adds links fine, but would like to have the option to add target="_blank" to the hyperlink. Also, if possible, I would like to be able to add alt="" and title="".

At the moment this is my code:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    editorWindow.document.execCommand('createlink', false, linkURL);
}

Been looking around, and can't seem to find a solution. Most of the solutions I've seen say to add:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    var newLink = editorWindow.document.execCommand('createlink', false, linkURL);
    newLink.target = "_blank";
}

But this doesn't seem to work. Any suggestions?

thelos999
  • 641
  • 2
  • 7
  • 19
  • Do you really want to use the execCommand functionality? Why not simply create a new link element and add it to the dom, or even better, use jQuery? => also, don't forget to escape the url the user can input to prevent possible XSS – Bart Enkelaar May 22 '14 at 15:40
  • Thanks for the reply. Don't exactly know how to go about this. I know you add create a new element with `document.createElement('a');` and then adding `setAttribute('target', '_blank');`. The only thing I don't see is how to apply the link to the text that has been highlighted. – thelos999 May 22 '14 at 17:05

6 Answers6

25

I was able to find a solution. Don't know if this is the right way to go, but it works. Following https://stackoverflow.com/a/5605841/997632, this is what I used for my code to work:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    var sText = editorWindow.document.getSelection();

    editorWindow.document.execCommand('insertHTML', false, '<a href="' + linkURL + '" target="_blank">' + sText + '</a>');
}

Just in case anyone else is looking and stumbles upon this...

Community
  • 1
  • 1
thelos999
  • 641
  • 2
  • 7
  • 19
  • 2
    "In IE 11, document.selection is gone and insertHTML is still not supported" http://stackoverflow.com/questions/3398378/execcommand-inserthtml-in-internet-explorer – Jim Nov 09 '14 at 03:23
  • You could use jQuery like this $("a").attr("target","_blank"); after the normal execCommand. It simply adds the attribute to every anchor - or you could try to target the specific anchor... it's ugly, but it works. – Edd Jul 29 '15 at 20:57
11

insertHTML can be frustrated if you have a bold or italic before. I use the following approach:

var url = 'example.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
selection.anchorNode.parentElement.target = '_blank';
Raphael
  • 119
  • 1
  • 2
5

I know this thread is quite old, but let me throw my 2 cents in, and maybe someone will find this useful ;) I'm working on a WYSIWYG editor too As I found the accepted solution fails for me when I try to make a link from a selected image in FF (the getSelection().getRangeAt(0) returns the image's parent div and treats the image as it never wasn't there (this is how I see it)), here's a dirty but working (and, I think, it's turbo-cross-browser) idea I came up with (jQuery):

//somewhere before losing the focus:
sel = window.getSelection().getRangeAt(0);

//reselecting:
window.getSelection().addRange(sel);

//link:
document.execCommand('createLink', false, 'LINK_TO_CHANGE');
$('a[href="LINK_TO_CHANGE"').attr('target', '_blank');
//any other attr changes here
$('a[href="LINK_TO_CHANGE"').attr('href', theRealHref);

Is it good idea? Works like a charm. And this simplicity ^^

Piotrek
  • 61
  • 1
  • 7
  • You are a very intelligent person! much love to you ... I am so very glad that you exist! Good luck++ to you every day! – Ben Muircroft Mar 20 '18 at 16:57
2

Since, there is no straightforward cross-browser solution, one cross-browser workaround could be programatically attaching an event handler to a inside your editor:

var aLinks = Array.prototype.slice.call(editorElement.querySelectorAll('a'));
aLinks.forEach(function(link) {
      link.addEventListener('click', function() {
          window.open(link.href, '_blank');
      }); 
});
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
0

Nobody seems to mention that as per specs, the document has to be in the design mode:

document.designMode = "on";

Then the following should work:

var url = 'http://google.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
Adam
  • 1,054
  • 1
  • 12
  • 26
0

The execCommand'createLink' does not always work. It will sometimes wrap the link text inside a link.
i.e

<a><a href="">label</a></a> 

Resulting the html link code appearing in the document and the link not working.

in this case ues execCommand 'insertHTML'

 val=`<a href="`+val+`" target="_blank">`+label+`</a>`      
//document.execCommand('createLink', false, val);
 document.execCommand('insertHTML', false, val);